static and media configuration in settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend','build', 'static')
]
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
re_path('', TemplateView.as_view(template_name='index.html')),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Here i am using django with reactjs.
i have given the path of build folder in react app like this.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'frontend','build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
When i am going to http://127.0.0.1:8000/media/images_OkG6q2k.jpeg path to get images
in side media folder which are uploaded by users i am getting the react route page.
I am not getting the image from media folder.
How i can see the media photos through url.
Project structure
react home is coming instead media image like this when i amgoing url
I think I just overcame this problem with one of my projects with Django backend + React frontend. It is in your url patterns.
As I understand it, this catch-all pattern:
re_path('', TemplateView.as_view(template_name='index.html'))
essentially overrides the media url pattern you wrote (and any others below it), which prevents the Django backend from allowing you to access the media files. To fix this, simply make sure the catch-all route is the last one on your patterns. After you are done with the rest of the patterns, on a new line do this:
urlpatterns += [re_path('', TemplateView.as_view(template_name='index.html'))]
This way, you add it to your paths after all the rest and it doesn't "block" any of the others. hopefully this fixes it!
Related
i have problems with my django app. Since a few days i have the problem that the download dont work on production but i cant find the reason why...
I can upload files and they are stored in the correct folder, but as soon as i click on it i get a 404 error "file not found.."
Here is my setup:
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
.
.
.
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATIC_DIR = os.path.join(BASE_DIR, "static")
MEDIA_DIR = os.path.join(BASE_DIR, "media")
STATIC_ROOT = STATIC_DIR
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "staticfiles/static"),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = MEDIA_DIR
MEDIA_TEMPLATE_ROOT = os.path.join(MEDIA_ROOT, 'templates')
MEDIA_TEMP = os.path.join(MEDIA_ROOT, 'tmp')
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('jet/', include('jet.urls', 'jet')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I tried many different configurations of the media_url, media_root etc... without success..
In production, usually the django web app is behind a web server like nginx or apache http web server.
In that case, what is usually done is to configure your web server (nginx or apache) to serve directly the static files, thus you need to configure the virtualhost section.
If you can provide more information about your configuration, I could be more specific.
Thats the setup iam using:
https://lab.uberspace.de/guide_django/
Its my first time deploying the app on a server. Debug=False yes. The app it self works but it doesnt serve the files. But i have no clue what gunicorn does in this configuration, i just followed the link above to set it up.
The solution was to configure the uwsgi file:
static-map = /static=%(chdir)/staticfiles/static
There I modified the location of the media folder to the staticfiles/static folder. Then it worked!
I have created an app for the main template of my project (All other templates inherit from this one). The template includes header, footer and an aside in which i can add and delete posts from the admin panel. Now, when rendering all the templates everything (header, footer and the respective {% block content %}) is shown correctly but not the aside because i'm not passing any url to the view managing it.
I'm trying to pass that view to every URL of my project so the aside is always shown.
I just dont get the way of doing it.
Just to clarify: Following the code i'm going to show now the aside is shown in localhost:8000 only. Not in localhost:8000/inicio nor any other url.
Aside views.py
from django.shortcuts import render
from .models import asides
def post_aside(request):
aside_posts = asides.objects.all()
return render(request, "main/main.html", {"aside_posts" : aside_posts})
urls.py of the app with the aside
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_aside, name='main'),
]
urls.py of the project
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('inicio/', include('inicio.urls')),
path('galeria/', include('galeria.urls')),
path('mapa/', include('mapa.urls')),
path('contacto/', include('contacto.urls')),
path('usuarios/', include('usuarios.urls')),
]
urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Create context_processor.py in app where your asides model exists.
Then add inside:
from .models import asides
def website_content(request):
context = {
'aside_posts': asides.objects.all(),
}
return context
Then in your settings.py in context_processors list add on the end:
<your_app>.context_processor.website_content
it should look like:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'aside.context_processor.website_content', # HERE PATH TO YOUR CONTEXT PROCESSOR FUNCTION
],
},
},
]
after this use {% for post in aside_posts %} in your template anywhere you want.
I am trying to do a project for a blog by django 3.1.2 , but unable to link the templates.I tried fixing it with **'DIRS': [os.path.join(BASE_DIR, 'templates'),]** I cannot find the logic miss. The template does exist and when I review the code, the query is performing correctly. I'm at a loss.
my setting
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
my blog urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('', include('posts.urls')),
path('admin/', admin.site.urls),
]
my posts urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
my posts views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,'posts/index.html')
If your templates folder is in your application's directory
eg: app_name / templates / app_name /.html, then you do not need to add
'DIRS': [os.path.join(BASE_DIR, 'templates'),]'.
So, if your application name is my_posts, create a folder named templates in your application directory. Then again create a folder named my_posts(same as application name) in templates directory, and then inside it create all your html files. But remember in your views.py when you are rendering, you have to do it as such, 'my_posts/index.html'
You only need to add 'DIRS': [os.path.join(BASE_DIR, 'templates'),]' , if you have you template folder in your main/project directory.
Here are the codes to create the sitemap for one of my app 'blog' in my site: (using Django 2.0)
settings.py
INSTALLED_APPS += [
'django.contrib.sites',
'django.contrib.sitemaps',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
urls.py
from django.urls import include, path
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSiteMap
sitemaps = {'posts': PostSiteMap}
urlpatterns += [
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap')
]
sitempas.py (under 'blog' app directory)
from django.contrib.sitemaps import Sitemap
from .models import Post
class PostSiteMap(Sitemap):
changefreq = 'weekly'
priority = 0.5
def items(self):
return Post.published.all()
def lastmod(self, obj):
return obj.publish
The sitemap.xml doesn't appear: http://127.0.0.1:8000/sitemap.xml/
There is the url (the eighth) matching my inputted one. Why it says 'not match'?
Your code is good, your environment is what is wrong (maybe you are using the default Django site, that is www.example.com). Change it to a local environment (the typical 127.0.0.1:8000).
To do this in Django you need to do the following:
Check if you are running the local server in your command prompt, if is not, type python manage.py runserver.
go to http://127.0.0.1:8000/admin/sites/site/
Change the default site (typically the default in Django is example.com) to 127.0.0.1:8000. This needs to be done in the domain and display name (while you aren't in a production environment).
Press F5 in your local web page in your browser.
go to your sitemap page (http://127.0.0.1:8000/sitemap.xml)
And voilĂ ! there is your sitemap.
Write full /sitemap.xml like this and try
Enter this url and load page
http://127.0.0.1:8000/sitemap.xml/
The error is
Site matching query does not exist
which means that you have to setup and configure Sites framework.
To enable the sites framework, follow these steps:
Add 'django.contrib.sites' to your INSTALLED_APPS setting.
Define a SITE_ID setting:
SITE_ID = 1
Run migrate.
For more information check documentation.
I would like to run Django from location https://www.example.com/someuri/ so that I have the admin interface at https://www.example.com/someuri/admin/. I can see the login window but when I log in I get redirected to https://www.example.com/admin/.
Where can I set the base URL of Django to https://www.example.com/someuri/? I tried with BASE_URL but with no luck.
#AgileDeveloper's answer is completely correct for that one off case of admin. However, is the desire to set it this way for all URLs? If so, perhaps you should do something like this
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^someuri/', include([
url(r'^admin/', include(admin.site.urls) ),
url(r'^other/$', views.other)
])),
]
I have a project that has a similar setup. I have django running using a virtual environment with apache. In my 000-default.conf file, I set the WSGIScriptAlias to the following:
WSGIScriptAlias /someuri /path/to/wsgi.py
Here is the documentation on WSGIScriptAlias to serve the project from a subdirectory, https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode.
Than in the urls.py file I set the following:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^', include('someuri.urls')),
url(r'^admin/', admin.site.urls),
]
After logging in, I am redirected to http://example.com/someuri/admin/
The answer of #James Wallace works well assuming you have control of the web server hosting Django at /someuri. In that configuration, the server will pass a value of SCRIPT_NAME in the header to Django, who will then know it is being served on that sub-path.
However, if you do not have control of the front-end server, then you can force Django to assume that value by adding to settings.py in the project:
USE_X_FORWARDED_HOST = True
FORCE_SCRIPT_NAME = '/someuri'
Afterwards, you may still have problems with static files, the css, etc., even in the admin application. In the default config, these are served by the Django development server without changes. However, with the above changes the static files will be lost. Assuming you still want to serve these files through the internal Django development server (and not through an external web server) you need to add to the settings.py project file:
STATIC_SUFFIX = '/static/'
STATIC_URL = FORCE_SCRIPT_NAME + STATIC_SUFFIX
MEDIA_SUFFIX = '/media/'
MEDIA_URL = FORCE_SCRIPT_NAME + MEDIA_SUFFIX
In the same file, you also need to change TEMPLATES and add the following:
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ STATIC_ROOT ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
You will then want to gather the static files into the directory defined:
python manage.py collectstatic
or
python3 manage.py collectstatic
The project level urls.py file should look like this (Django v1.11):
import os
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.STATIC_SUFFIX, document_root=settings.STATIC_ROOT)
Thereafter, the admin package should work okay, with appropriate stylesheets and everything. The only thing that does not seem to work well is the "VIEW SITE" link since it misses a slash. I did not find a solution for that but probably it involves hacking the admin application.
Beyond that, there are various guides online for installing Django under a sub-path. It's messy but the above avoids the worst headaches.
This should work for you.
from django.conf.urls import patterns, url
urlpatterns = patterns('',
(r'^someuri/admin/', include(admin.site.urls) ),
)