I have a Django project, the working urls.py looks like:
urlpatterns = [
path('', views.index, name='index'),
path('polls/search', views.search, name='search'),
]
Then I want to add additional path for my image in the urls.py
urlpatterns += patterns('django.views.static',(r'^media/(?P<path>.*)','serve',{'document_root':settings.MEDIA_ROOT}), )
But I got:
unresolved reference 'patterns'
I am using python 3.4 and Django 2.0.8. How do I properly add the additional path to my original urls.py ? Thanks!
It looks like using patterns won't work anymore. Since you're trying to serve static files, try this:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And set MEDIA_URL and MEDIA_ROOT in your settings.py.
In order to get it to work in your templates, you'd do something like this:
{% load static %}
<body data-media-url="{% get_media_prefix %}">
Django docs
Related
Im developing a website on python and I found a theme that I like on the internet. It includes the index.html, css folder, js folder and the images. Like in other projects I copies all of the data into the templates folder in my project. I replaced my base.html with this new index.html. The problem is that Django can't find the css and js folders that are being references in the html. I have read some post about this, and everybody mentions taking the index.html outside of templates (doesn't work) or using a static folder to store my css and js files (doesn't work. Can someone give me some clues? thank you!!
Project
mysite
templates
assets
css
js
index.html
link href="{% static 'css/styles.css' %}" rel="stylesheet"/
from django.contrib import admin
from django.urls import path
from personal.views import home_screen_view
from account.views import registration_view, logout_view, login_view, account_view
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_screen_view, name="home"),
path('register/', registration_view, name="register"),
path('logout/', logout_view, name="logout"),
path('login/', login_view, name="login"),
path('account/', account_view, name="account"),
# Password reset links (ref: https://github.com/django/django/blob/master/django/contrib/auth/views.py)
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'),
name='password_change_done'),
path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change.html'),
name='password_change'),
path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_done.html'),
name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'),
name='password_reset_complete'),
]
Django is looking for my static files in the wrong place and I dont understand why
Not Found: /account/login/style.css
[26/Feb/2021 19:27:16] "GET /account/login/style.css HTTP/1.1" 404 2434
but my file should be in /static/css/style.css
This is the code in my settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'staticfiles')
]
I use staticfiles folder to place my static files afterwards I do py src\manage.py collectstatic to transfer my files in static folder
This is my layout of the project:
In my template I am using {% load static %} and I try to load the style.css with {% static 'css/style.css' %}
Here is the urls.py in core:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('accounts.urls', namespace='accounts')),
]
if settings.DEBUG:
# test mode
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urls.py in accounts:
app_name = 'accounts'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name="registration/login.html",
authentication_form=UserLoginForm), name='login'),
]
Login page is the one that I have the problem with http://127.0.0.1:8000/account/login/
Template:
DEBUG is true in settings
Do you have any idea what could be the problem?
I want to create a setting in admin panel which will help me to change the website logo from the admin panel. I create a model for database and it's working and uploading an image to the database + folder. but I cannot get this image to the Website template. when I'm viewing page source image SCR is empty.
my Model.py
class WebLogo(models.Model):
Logotitle = models.CharField(max_length=50,unique=False)
SiteLogo = models.ImageField(upload_to='webimages')
def __str__(self):
return self.Logotitle
my Views.py
from .models import Post,WebLogo
def Display_WebLogo(request):
# getting all the objects of hotel.
WebsiteLogo = WebLogo.objects.all()
return render((request, 'index.html',{'web_images' : WebsiteLogo}))
my project Urls.py
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my Html Code
<a href="index.html"><img src="{{ WebLogo.SiteLogo.url }}" class="img-fluid" alt="logo">
</a>
my app url
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
In HTML Code, use 'web_images' not WebLogo like this
<a href="index.html"><img src="{{ web_images.0.SiteLogo.url }}" class="img-fluid" alt="logo">
</a>
It looks like {{ data.0 }}. See Variables and lookups.
You should write the required information in the settings.py file.
https://docs.djangoproject.com/en/dev/ref/settings/#media-root
I made a template to list documents with a download link, but instead of linking to :
http://127.0.0.1:8000/media/mydoc.csv
it links to :
http://127.0.0.1:8000/myapp/myview/media/mydoc.csv
In myapp/templates/myapp/list.html
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
{% endfor %}
</ul>
document.docfile.url does actually links to media/mydoc.csv so that I guess it has to do with the template engine.
Versions
Python : 3.7.2
Django : 2.1.7
OS : Windows 10
In myapp/models.py
class Document(models.Model):
docfile = models.FileField(upload_to='documents')
In myapp/views.py
def myview(request):
documents = Document.objects.all()
return render(request, 'myapp/list.html', {'documents': documents})
In myapp/urls.py
app_name = 'myapp'
urlpatterns = [
path('', views.index, name='index'),
path('myview/', views.myview, name='myview'),
]
In myproject/urls.py
urlpatterns = [
path('', views.index, name='index'),
path('myapp/', include('myapp.urls')),
path('admin/', admin.site.urls),
]
In settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'
Since it is my fist Django app (and first webapp ever) I guess I missed something very basic. Do you have an idea ?
Your MEDIA_URL is wrong. You missed the starting slash.
MEDIA_URL = '/media/'
I am trying my hand at learning Django and trying out the step-by-step tutorial at https://docs.djangoproject.com/en/2.0/intro/tutorial03/.
I have completed the app (well, till the Part 7) and is working as expected (and has been explained in the tutorial).
The only problem (so far) I am facing is when I am trying to navigate from the "Admin" page to the linked page "VIEW SITE" when I am being presented with "Page not found (404)" error. An image is being attached to make the situation clearer.
The link is pointing to "http://127.0.0.1:8000/" whereas it should be pointing to "http://127.0.0.1:8000/polls/". When I add the missing part of the path (manually) in the address bar the correct page (as expected) is presented.
I have tried to search on this as well as many other forums but could not get the right solution.
I am using Django 2.0.6 and Python 3.6.4 on mac sierra.
Shall be grateful for a lead on this.
Thanks
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
mysite/polls/urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
polls/template/polls/index.html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Error on navigation at VIEW SITE
you should open http://127.0.0.1:8000/polls/
not
http://127.0.0.1:8000/.
If you wanna use http://127.0.0.1:8000/ then your path should be
from django.urls import include, path
urlpatterns = [
path('', include('polls.urls')),
path('admin/', admin.site.urls),
]
It should be like this:
path('', include('polls.urls')),
not like this:
path('polls/', include('polls.urls'))
Because it should be the root url of your website
Here is what I have done (may be not the most elegant solution but works just fine).
I have modified the "mysite/urls.py" file as shown:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('polls.urls')),
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
This way I am able to access the "polls" page from both "View Site" link on the Django Admin page (url: "127.0.0.1:8000") as well as from link residing elsewhere (url: "127.0.0.1:8000/polls/").
Thanks for all the help.
PS. Visiting https://docs.djangoproject.com/en/2.0/topics/http/urls/ may be of help to learners like me.