Why is Django template engine adding myapp/myview to my URLs? - python

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/'

Related

Issue with Django Static Files 3.1

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?

Django urlpatterns settings

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

Django object.image.url not displaying even though path is correct

I have images I uploaded through django admin, but they are not displaying. The weird thing is that I have another project with the EXACT same code and it works. object.image.url outputs /media/media/image.jpg as does my other project. But this project does not show the image. if I put an image from my static folder or if I hardcode an image, it works fine. The problem is only when I try an image uploaded from the admin it does not work. Am I missing something in my settings.py file? or anywhere?
Models.py:
from django.db import models
# Create your models here.
class Connect(models.Model):
title = models.CharField(max_length=70)
short_description = models.TextField(null=True, blank=True)
description = models.TextField()
image = models.ImageField(upload_to='media', blank=True, null=True)
def __str__(self):
return self.title
views.py:
def index(request):
about = About.objects.all()
staff = Staffmembers.objects.all()
ministries = Ministries.objects.all()
connect = Connect.objects.all()
context = {
'template': 'home',
'connect': connect,
'about': about,
'staff': staff,
'ministries': ministries,
}
return render(request,'home/index.html', context)
template(index.html):
<div class="connect-wrapper row">
<h1 class="title connect-title">Connect</h1>
{% for object in connect %}
<div class="home-div connect-div col-md-4">
<h4>{{ object.title }}</h4>
<p>{{ object.short_description }}</p>
{% if object.image %}
<img class="connect-image-home" src="{{object.image.url}}" alt="connect">
<p>{{object.image.url}}</p> //sanity check
{% endif %}
</div>
{% endfor %}
</div>
settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
]
I believe you need to add the media urls to your urls.py. Something like:
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
On production environment Django does not load the media root automatically so that we can we can overcome that issue by adding following after url patterns:
urlpatterns = [
''''
your urls
''''
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
If you are using more than one app and including app urls on main app url, just add this on main project url.

Django: uploaded image is not showing in template

I'm trying to write a simple blog using a Django framework. I want to have a cover image for a every post.
I uploaded an image via Admin site and everything seems to be fine but image is not rendering in a browser.
Here is my files:
models.py
(...)
class Post(models.Model):
author = models.ForeignKey('Author', on_delete=models.CASCADE)
title = models.CharField(max_length=250)
slug = models.SlugField(unique=True, blank=True, max_length=250)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
modified = models.DateTimeField(auto_now=True, auto_now_add=False)
image = models.ImageField(upload_to="images/%Y/%m/", blank=True, null=True)
content = models.TextField()
(...)
django_blog_project\urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
blog\urls.py
(...)
urlpatterns = [
url(r'^posts/create/$', PostCreate.as_view(), name="post_create"),
url(r'^posts/([\w-]+)/$', AuthorPostList.as_view(), name="posts_by_author"),
url(r'^(?P<slug>[-\w]+)/$', PostDetailView.as_view(), name="post_detail"),
url(r'^', PostListView.as_view(), name="post_list"),
]
settings.py
(...)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
(...)
post_detail.html
{% extends "blog/base.html" %}
{% block content %}
<h1>{{ post.title }}</h1>
<img src="{{ post.image.url }}" >
<p>{{ post.content }}</p>
<p>Autor: {{ post.author }}</p>
<p>Opublikowano: {{ post.modified }}</p>
{% endblock %}
Dir tree
My directory tree
URL of the image resolving to
<img src="/media/images/2016/12/fotolia_97812586.jpg">
Adding $ char in pattern solved a problem.
blog\urls.py
(...)
urlpatterns = [
url(r'^posts/create/$', PostCreate.as_view(), name="post_create"),
url(r'^posts/([\w-]+)/$', AuthorPostList.as_view(), name="posts_by_author"),
url(r'^(?P<slug>[-\w]+)/$', PostDetailView.as_view(), name="post_detail"),
# url(r'^', PostListView.as_view(), name="post_list"), # WRONG!
url(r'^$', PostListView.as_view(), name="post_list"), # CORRECT!
]

How to render Image on the web page using path from DB in Django?

So I am trying to display an image on the web page, i save the image path in the database as media/imagename and in my html page i am doing this :
{% for stuff in profile %}
<div class="alert alert-success" role="alert"> {{ stuff.text }} </div>
<img scr='/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media/{{ stuff.thumbnail }}' width="200">
{% endfor %}
And in my settings.py i do this:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, '/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media')
But the image doesn't display. What am i doing wrong here? Thanks!
Edit:
#urls.py
from django.conf.urls import patterns, url
from django.conf import settings
from social import views
urlpatterns = [
# main page
url(r'^$', views.index, name='index'),
# signup page
url(r'^signup/$', views.signup, name='signup'),
# register new user
url(r'^register/$', views.register, name='register'),
# login page
url(r'^login/$', views.login, name='login'),
# user doesnt exist webpage
url(r'^user-doesnt-exist/$', views.login, name='user-doesnt-exist'),
#page to show that the password is incorrect
url(r'^wrongpass/$', views.login, name='wrongpass'),
#webpage to show an error when a user tries to input nothing in the fields when signing up
url(r'^novalues/$', views.register, name='novalues'),
# logout page
url(r'^logout/$', views.logout, name='logout'),
# members page
url(r'^members/$', views.members, name='members'),
#invites page
url(r'^invites/$', views.invites, name='invites'),
# friends page
url(r'^friends/$', views.friends, name='friends'),
# user profile edit page
url(r'^profile/$', views.profile, name='profile'),
# messages page
url(r'^messages/$', views.messages, name='messages'),
# Ajax: check if user exists
url(r'^checkuser/$', views.checkuser, name='checkuser'),
#commiting again
]
if settings.DEBUG:
urlpatterns += patterns(''(r'^media/(P<path>.*)$','django.views.static.serve',
{'document_root':settings.MEDIA_ROOT,'show_indexes':True})),
Try setting your MEDIA_ROOT to:
MEDIA_ROOT = os.path.join(BASE_DIR, 'social/static/social/media')
MEDIA_URL = '/media/'
And in your project urls.py file add:
from django.conf import settings
from django.conf.urls import patterns
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))
Then, in your template call the image like:
{% if stuff.thumbnail %}
<img src="{{ object.thumbnail.url }}">
{% endif %}
And in models.py:
image = models.ImageField(upload_to='images/')
Here's some great documentation on serving media files, including how to serve them during development.

Categories