i try to include urls from my Api folder
i tried path('api/', include("main.Apps.Api.apps.urls")) but it doesn't work
in my settings.py i add the app by INSTALLED_APPS += ["main.Apps.Api.apps.ApiConfig"]
and i changed the app name in Api.apps.py to name = 'MikeWebsite.Apps.Api' Everything works
But include the urls return me
ModuleNotFoundError: No module named 'MikeWebsite.Apps.Api.apps.urls'; 'MikeWebsite.Apps.Api.apps' is not a package
my project file tree look like this
main
└───_main
├── __init__.py
├── settings.py
├── urls.py
├── wsgi.py
└──_Apps
├──_Api
| └── urls.py
└── ...
What I'm doing is wrong?
And if you have a good source of information on how to work with apps nested in Django
Related
I have the static folder in my app folder and that's where I have js, css, images etc. folders.
I reference them like this in my templates:
<script src="/static/js/main.js"></script>
and it works locally. But, when the app is published to production, I get a 404 for all static files. I'm new to flask so I guess I'm serving them wrong.
I don't have the static folder set as a designated static files folder anywhere in the app - is it done automatically if it's called 'static' or do I need to set it in code?
My project structure:
app/
├── static/
│ └── js/
| |__ css/
├── templates/
│ └── index.html
└── __init__.py
application.py
application.py:
from app import create_app
application = create_app()
init.py:
from flask import Flask
from config import BaseConfig
def create_app():
server = Flask(__name__)
server.config.from_object(BaseConfig) # this is just for the secret key
return server
Flask automatically adds a static view that takes a path relative to the $YOUR_APP/static directory and serves it.
Typically you would include your js/css files in your templates like so:
{{ url_for('static', filename='main.js') }}
First part of the solution was Bert's answer above which described how to correctly reference assets from the templates.
The other part I was missing was this:
server = Flask(__name__, static_url_path="", static_folder="static")
instead of what I had before:
server = Flask(__name__)
Adding static_url_path and static_folder fixed the issue for me.
I have following code structure in Django.
├── docs
│ └── _build
│ ├── doctrees
│ └── html
│ └── index.html
│
├── localcoinswap
├── scripts
├── _static
├── _templates
├── tests
└── manage.py
Here the docs folder contains static html files. i.e index.html
Here are some questions regarding to problem:
The docs folder's html should be served as url <domain>/docs/index.html in Django project. How to achieve this
It should be restricted to User's who have is_staff attribute True.
What urlpattern should I use and Which View is useful to serve those static files (Admin restricted)?
Thank you in advance!
Add the base directory for your docs in TEMPLATES setting in settings.py.
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, '_templates'), "add your base directory here"],
...
}
]
In your urls.py, serve the files using TemplateView. To further restrict the url to only the staff users, you can wrap the view in staff_member_required decorator.
from django.contrib.admin.views.decorators import staff_member_required
...
urlpatterns += [url(r'^docs/index\.html$', staff_member_required(TemplateView.as_view(template_name='index.html')), name="index"),]
Make sure the file names for your templates and doc templates don't clash, else the first one evaluated according to the DIR list will always be considered.
I'm writing a django rest framework API (backend) with a react SPA frontend. For the production environment, the front end is served up via nginx at http://example.com/ and the backend is proxied to gunicorn and served from the same domain with a different path - http://example.com/api/
This is all working fine in production, there are no CORS issues as the frontend and backend are both served up under the same domain via nginx.
For local development, I want to be able to replicate a similar setup using ./manage.py runserver and have django serve up the frontend from project/frontend/dist (built by npm build seperately).
Has anyone got any urlpattern wizardry that will allow this to happen and also let the react-router play nicely? I just can't figure it out and it's starting to drive me nuts...
The project structure is something like this if it helps in any explanations.
Project
|
── backend
│ ├── apps
│ ├── config
| | ├── settings.py
| | ├── settings_local.py
| | ├── urls.py
│ ├── manage.py
│ ├── requirements.txt
│ └── venv
├── frontend
│ ├── dist (contains the npm build webpack)
│ ├── node_modules
│ ├── package.json
│ ├── package-lock.json
│ ├── scripts
│ ├── src
│ ├── webpack.config.js
Edit #1
Thanks to another post I was able to get partially the way there by adding this to my urls.py
if settings.DEBUG:
from django.views.generic import RedirectView
from django.contrib.staticfiles.views import serve
bundle_path = os.path.abspath(os.path.join(root_dir, 'frontend', 'dist'))
settings.STATICFILES_DIRS += (bundle_path,)
urlpatterns += [url(r'^$', serve, kwargs={'path': 'index.html'})]
urlpatterns += [url(r'^(?!/?static/)(?!/?media/)(?P<path>.*\..*)$',
RedirectView.as_view(url='/static/%(path)s', permanent=False))]
The only issue I have here is that if I go directly to one of the JS router links, then django tries to interpret it and can't find the route.
What I need now is a catch-all that will redirect to '/' but also keep any extra URL path information on the url
Finally got this to work with all the routing.
Added the webpack dist folder to settings.STATICFILES_DIRS
Added the webpack frontend path to settings.TEMPLATES
Added 3 new urlpatterns to urls.py ( based on a conditional, settings.DEBUG)
urlpatterns += [
url(r'^(?!/?static/)(?!/?media/)(?P<path>.*\..*)$',
RedirectView.as_view(url='/static/%(path)s', permanent=False)),
url(r'^$', TemplateView.as_view(template_name='dist/index.html'), name='frontend'),
url(r'^(?P<path>.*)/$', TemplateView.as_view(template_name='dist/index.html'), name='frontend'),
]
The first redirects any of the asssets for the bundle to be served using django's static files.
The second pattern serves the root path / as a template from the webpack dist folder
The final piece handles all the leftover JS routing paths to go back to the initial root view.
You can use nginx reverse proxy to serve them.
No need config Django's url.
See example here:
http://www.codingpedia.org/ama/how-to-configure-nginx-in-production-to-serve-angular-app-and-reverse-proxy-nodejs
I am taking a test Driven Development course for python (which is awesome) Obeythetestinggoat and so my Django needs work. So I'm taking the Djangoproject.com course and I get all the code entered and the server runs but the polls won't change.
The home page http://127.0.0.1:8000 shows
"It worked!
Congratulations on your first Django-powered page."
Which is great but it won't show the polls or the admin buttons and I've run out of ideas on how to redirect it but not sure the problem.
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
I'm rather proud that I figured out the server and other areas but I just don't know what I am missing to get the page to show the polls.
https://docs.djangoproject.com/en/1.10/intro/tutorial01/
Yes, all you need to do is go to http://127.0.0.1:8000/polls/ . Otherwise if you want put your default polls page on the home page like you intended to do in http://127.0.0.1:8000/
you could do this in your urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
hope it helps.
http://127.0.0.1:8000 is the main page of your preoject, but in the urls, you define (with regex) how to manage requests to http://127.0.0.1:8000/polls/ and http://127.0.0.1:8000/admin/. You should visit those URLs.
There's a urls.py at the wrong place made by the django-admin startproject mysite command.
.
├── db.sqlite3
├── manage.py
├── mysite
│ ├── asgi.py
│ .
│ .
│ │
│ ├── urls.py <-- right place
│ └── wsgi.py
├── polls
│ .
│ .
│ ├── urls.py
│ └── views.py
└── urls.py <-- wrong place
If you forget to remove it, and keep it, while creating the right one at the right place, it prevents the rules of the right one to be applied.
I have a question about putting django apps into "apps" subdirectory. I have the app called “faktura” in a project_root. I didn’t like the fact it lies there and I want to store all my apps under “apps” subdirectory.
So, I found out that I could extend python path to “apps” subdir, so after looking in the internet, I added this string to settings.py: sys.path.insert(0, os.path.join(PROJECT_PATH, "apps")). Then I added the app to INSTALLED_APPS like “faktura”. Everything worked smooth until I added url(r'^faktura/', include('faktura.urls')) to urls.py in the root. Since that, Django throws the error message “No module named faktura” full taceback is here: http://dpaste.com/737380/
What can be wrong here, why only urls.py can’t find the app? And does it can’t find this app if I added it to the PATH? I spent a morning trying to figure out what’s wrong and now I need your help.
I don't know why the previous answer got -1 aside from maybe a few redundant lines that can be corrected. Anyway, I found a slightly different method that doesn't involve adding anything to the python path.
This is my final directory structure, I will explain in a moment:
mysite
├── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── apps
│ ├── __init__.py
│ └── myfirstapp
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── manage.py
No matter if you have just created your project or if you want to move your apps, create the apps subdirectory that should contain your apps. The trick is to add an __init__.py to that directory.
mkdir apps
touch apps/__init__.py
Now you can move your existing apps into the apps subdirectory. If you would like to create a new one instead here are the commands:
python manage.py mysecondapp
mv mysecondapp apps/
Warning: Don't be tempted to call python manage.py ./apps/mysecondapp. For some reason this deletes all other apps in that directory. I just lost a day of work this way.
Next, you will need to fix a few imports. Your settings.py should be prefixed with apps:
INSTALLED_APPS = (
...
'apps.myfirstapp',
'apps.mysecondapp'
)
Lastly, fix your project's urls.py to prefix apps:
urlpatterns = patterns('',
url(r'^myfirstapp', include('apps.myfirstapp.urls')),
...
)
Depending on how you wrote them, you might also have to fix a few imports inside your app. Either just use from models import MyFirstModel or also prefix it using from apps.myfirstapp.models import MyFirstModel.
In short, if you make your apps directory a python package (by adding __init__.py), you can use it as part of the import path. This should work regardless of the deployment method with no extra configuration.
Use BASE_DIR variable from the settings.py. It should be already defined:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Better not use the __file__ attribute in manage.py and wsgi.py, as they are located in different directories.
So, just add the following to manage.py and wsgi.py (and to the celery.py if you use Celery):
from django.conf import settings
sys.path.append(os.path.join(settings.BASE_DIR, "apps"))
You will end up with the following project structure:
project
├── project
│ ├── __init__.py
│ ├── celery.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── apps
│ ├── app1
│ └── app2
└── manage.py
To keep your Django applications in a subfolder (such as apps/), first add the following to your settings.py:
import os
PROJECT_ROOT = os.path.dirname(__file__)
Then in manage.py:
Right under #!/usr/bin/env python add:
import sys
from os.path import abspath, dirname, join
from site import addsitedir
Right before if __name__ == "__main__" : add:
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
#Radu Gheorghiu's answer; It is not necessary to edit settings.py, and the insert path line can be condensed to 1 line of code.
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "apps"))
I sourced this answer from http://obroll.com/nested-application-inside-apps-sub-folder-in-django-1-3/