Django 404 Error Raised by: blog.views.post_detail - python

Hello, Everyone
I'm a novice programmer trying to follow Antonio Mele tutorial on blog creation using django.
Am stuck with the post/detail.html which is not responding
below are the codes.Kindly help.
Problem: Am unable to view details of the post
404 Error: Page not found
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/2020/3/13/more-post/
Raised by: blog.views.post_detail
No Post matches the given query.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Error:Page not found
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
1.admin/
2.blog/
The empty path didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.*
urls.py/blog
urls.py/mysite
views.py
urls.py/blog
from django.urls import path
from . import views
app_name = 'blog'
urlspatterns = [
path('', views.post_list, name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',
views.post_detail,
name='post_detail'),
]
urls.py/mysite
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls', namespace='blog')),
]
views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request,
'blog/post/list.html',
{'posts':posts})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request,
'blog/post/detail.html',
{'post': post})

Someone had the same problem with the previous version of the book, asked here and published his solution (there must be a much more elegant way), have a look here:
Django get_object_or_404() with DateTimeField
In addition, use the shell to debug items, you should have seen that the date in DB is recorded in UTC:
>>> post = Post.objects.get(title__startswith='who')
>>> post.publish
datetime.datetime(2020, 8, 18, 1, 18, 56, tzinfo=<UTC>)

Take a look at the admin area, where the articles have a 'draft' status. Change them to 'published' status. In the views.py in the function post_list(), change the output of posts on a page with only the status published:
def post_list(request):
posts = Post.objects.filter(status='published')
return render(request, 'blog/post/list.html', {'posts': posts})
In this case, articles with only the status published are displayed on the posts page. By clicking on the article link, you should be transferred to a full post without error.

#FOLLOW THIS PROCEDURE.I HOPE IT HELPS YOU OR ANY ONE ELSE IN THE FUTURE
#blog/models.py
from django.db import models
from django.utils import timezone
class Post(models.Model):
published = models.BooleanField(True)
created_on = models.DateTimeField(auto_now=timezone.now)
# At blog/urls.py
from django.urls import path
from .views import (post_list, post_detail)
urlspatterns = [
path('', post_list, name='post_list'),
path('<str:slug>/', post_detail, name='post_detail'),
#At mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
#At blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.filter(published)
template_name = blog/post_list.html
context = {'posts':posts}
return render(request, template_name, context)
def post_detail(request, slug):
posts = get_object_or_404(Post, slug=slug)
template_name = blog/post_detail.html
context = {'posts':posts}
return render(request, template_name, context)
# At the template/blog/post_list.html
{% block content %}
{% for post in posts %}
<article>
<div>
<small>{{ post.created_on|date:"F d, Y" }}</small>
<h2>{{ post.title }}</h2>
<p >{{ post.body }}</p>
</div>
</article>
{% endfor %}
{% endblock content %}
# At template/blog/post_detail.html
<article>
<div>
<small>{{ posts.created_on|date:"F d, Y" }}</small>
<h2>{{ posts.title }}</h2>
<p>{{ posts.body }}</p>
</div>
</article>
#The above code should fix the the issue properly.

Related

Django - Urls are appending to one another

I'm making a web app in django and currently I'm facing this problem. I have a dashboard page and an upload page. There's a button in dashboard page which links to the upload page. but whenever I click the button then the upload page url appends the dashboard page.
below is the code:
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import Registration
from .forms import UploadForm
from django.urls import reverse
# Create your views here.
def homepage(request):
return render(request, 'index.html', {})
def dashboard(request):
posts = Registration.objects.all()
return render(request, "dashboard.html", {'posts': posts})
def upload(request):
form = UploadForm()
return render(request, "upload.html", {'form': form})
def uploadimage(request):
if request.method == 'POST':
form=UploadForm(request.FILES['image'], request.POST)
if form.is_valid():
pic = request.FILES['image']
desc = request.POST
post = Registration(pic='pic', desc='desc')
post.save()
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.homepage, name='homepage'),
path('dashboard/', views.dashboard, name='dashboard'),
path('upload/', views.upload, name='upload'),
path('create/', views.uploadimage, name='uploadimage'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
dashboard.html
<div class="profile">
<div class="left-s col s12 m3 l3">
<div class="profile-overview">
<img src="{%static 'images/group.jpg' %}" alt="profile-pic" class="circle responsive-img">
<p>Daljit Singh</p>
<p>Lorem ipsum dolor sit amet.</p>
</div>
<hr>
<div class="container">
<ul>
<li>About</li>
<li>Friends</li>
<li>Photos</li>
<li>Likes</li>
</ul>
</div>
<hr>
<button>Upload post</button>
</div>
error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/dashboard/upload/
Using the URLconf defined in main.urls, Django tried these URL patterns, in this order:
[name='homepage']
dashboard/ [name='dashboard']
upload/ [name='upload']
create/ [name='uploadimage']
^media\/(?P<path>.*)$
The current path, dashboard/upload/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Help would be appreciated.
It should be - Upload post
If you enter '/' (/upload/) before the path it will append to the base URL and if '/' (upload/) doesn't exist then it will append to the existing path.
Or the Different way suggested in the comment -
Upload post

How do I fix this NoReverseMatch in Django? [duplicate]

This question already has an answer here:
Unexpected NoReverseMatch error when using include() in urls patterns
(1 answer)
Closed 5 years ago.
Edit: this question is different from django 1.8 NoReverseMatch at error because this one specifically asks how to do it with the ModelViewSet class
I'm trying to make a blog post/facebook wall type app and am getting a NoReverseMatch Error in Django. It happens after trying to submit the post form.
Here's my views.py
from django.shortcuts import render, get_object_or_404, redirect
from wall.models import Post
from .forms import PostForm
def index(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'wall/index.html', {'form': form})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'wall/post_detail.html', {'post': post})
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^post_detail/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
The error page says
Reverse for 'post_detail' with keyword arguments '{'pk': 5}' not found
1 pattern(s) tried: ['$post_detail/(?P<pk>\\d+)/$']
I've looked at this answer already, but none of the suggestions help. My regex and url names are all spelled correctly.
How do I fix this error?
Here is my base urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('wall.urls'), name='index'),
url(r'^accounts/register/$', views.register, name='register'),
url(r'^accounts/register/complete/$', views.registration_complete, name='registration_complete'),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'^accounts/logout/$', auth_views.logout, name='logout'),
url(r'^accounts/loggedin/$', views.logged_in, name='loggedin'),
]
I think your issue is on the redirect after the form submission, change
return redirect('post_detail', pk=post.pk)
to
return redirect(reverse('post_detail', kwargs={'pk': post.pk}))
(to import reverse use : from django.core.urlresolvers import reverse)
As Alasdair pointed out, a $ on include was also missing from your base urls.py
It looks as if you have a dollar in your regex when you include your app's urls. Remove it.

python - Django : Page Not found

I have looked around and can't really find a solution to my problem. Here is the error django throws. This error is being thrown when on my homepage I have a fiew links that upon clicking should direct you to a details view of said link.
Using the URLconf defined in untitled.urls, Django tried these URL patterns, in this order:
^$
^index/ ^$ [name='index']
^index/ ^(?P<distro_id>[0-9]+)/$ [name='distro_id']
^admin/
The current URL, index//, didn't match any of these.
To my knowledge I don't understand why this error is being thrown.
Here is my urls.py
from django.conf.urls import include, url
from django.contrib import admin
import index.views
urlpatterns = [
url(r'^$', index.views.index),
url(r'^index/', include('index.urls', namespace='index')),
url(r'^admin/', admin.site.urls),
]
My index/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# /index/
url(r'^$', views.index, name='index'),
#/distro/123/
url(r'^(?P<distro_id>[0-9]+)/$', views.detail, name='distro_id'),
]
My views.py
from django.shortcuts import get_object_or_404, render
from django.template import loader, RequestContext
from django.http import Http404
from .models import Distros
def index(request):
all_distros = Distros.objects.all()
context = {'all_distros': all_distros, }
return render(request, 'index/index.html', context)
def detail(request, distro_id,):
distro_id = get_object_or_404 (Distros, pk=distro_id)
return render(request, 'index/detail.html', {'distro_id': distro_id})
template code:
{% extends 'index/base.html' %}
{% block body %}
<ul>
{% for distro in all_distros %}
<li>{{ index.distro_id }}</li>
{% endfor %}
</ul>
{% endblock %}
I believe those are all the relevent files. I believe everything is setup correctly so I am not sure why the error is being thrown. I'm sure im missing something simple that i'm just overlooking.
Please don't use hardcoded URLs as they are error prone as in your situation. Instead of:
<a href="/index/{{ index.distro.id }}/">
use the url template tag with your namespace (index) and view name (distro_id):
<a href="{% url 'index:distro_id' index.id %}">
Note that you also have an error with index.distro.id as index is actually a Distros object. It has an id field, but not distro.id.

How to make a simple contact form using Django?

I am new to Django 1.9 and I am currently coding a website. I am trying to make a contact form to go on the contact page. I have used the following code - which is in the a file called email.html:
{% extends 'blog/base.html' %}
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
I've defined it in the view.py file:
from .forms import PostForm, ContactForm
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['nmam.ltd#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
return render(request, "blog/email.html", {'form': form})
def thanks(request):
return HttpResponse('Thank you for your message.')
.....
As well as in the forms.py file:
from django import forms
class ContactForm(forms.Form):
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea)
Also, in the urls.py file:
from django.conf.urls import patterns, url
from . import views
urlpatterns = [
url(r'^general.html/$', views.general, name='general'),
url(r'^dcmain.html/$', views.dcmain, name='dcmain'),
url(r'^dcmain.html/big_data.html/$', views.big_data, name='big_data'),
url(r'^dcmain.html/Data_Architecture.html/$', views.Data_Architecture, name='Data_Architecture'),
url(r'^dcmain.html/BI_MI.html/$', views.BI_MI, name='BI_MI'),
url(r'^dcmain.html/Master_Data.html/$', views.Master_Data, name='Master_Data'),
url(r'^dcmain.html/Data_Q.html/$', views.Data_Q, name='Data_Q'),
url(r'^dcmain.html/Project_M.html/$', views.Project_M, name='Project_M'),
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
]
When I link the email.html file to the main page and click on the link and it just shows the home page even though the url says I am on the email.html page (shown below):
I am totally new to programming in Django. I have tried researching it however, I can't find a solution. Please can someone help me.
Your URLs are most likely the problem. You can read more on Django URLs here.
Note, as the Django docs mention, the first URL pattern which matches the requested URL will be used. As a basic rule of thumb, I recommend putting your more specific URL patterns before your blank url patterns. For instance:
urlpatterns = [
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
url(r'^$', views.index, name='some_name'),
]
If this urls.py file is being included from a project urls.py file, you'll want these urls to be included before your root url pattern.
urlpatterns = [
url(r'^blog/', include('blog.urls', namespace='blog'),
url(r'', views.site_home, name='site_home'),
]
Which would then make your url to this page
Email
Which would render as
Email

How can I display a user profile using Django?

I am new to django and I am currently trying to build a website that allows users to sign in and view other users profiles. So far I have managed to let users sign in but I can't work out how to view other peoples profiles.
Each profile uses the users username to create a url for their profile. Currently if I sign in as one user and change the URL to another users profile URL, it still displays the current users profile. I want something similar to pinterest where any person whether they are signed in or not can view peoples profiles.
Any help would be appreciated!
View
from django.http import HttpResponse
from django.shortcuts import render
from howdidu.forms import UserProfileForm
from howdidu.models import UserProfile
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
def index(request):
context_dict = {'boldmessage': "I am bold font from the context"}
return render(request, 'howdidu/index.html', context_dict)
#user profile form
#login_required
def register_profile(request):
profile = UserProfile.objects.get(user=request.user)
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
return index(request)
else:
print form.errors
else:
form = UserProfileForm()
return render(request, 'howdidu/register_profile.html', {'form': form})
#profile page using user name as url
#login_required
def profile_page(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'howdidu/profile.html', {'profile_user': user})
project url
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView): #redirects to home page after registration
def get_success_url(self,request, user):
return '/register_profile'
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'howdidu_project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'', include('howdidu.urls')),
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'), #redirects to home page after registration
(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^(?P<username>\w+)/', include('howdidu.urls')), #do i need this?
)
# media
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
app url
from django.conf.urls import patterns, url
from howdidu import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register_profile/$', views.register_profile, name='register_profile'),
url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
)
template
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}{{ user.username }}{% endblock %}
{% block body_block %}
{% if user.is_authenticated %}
<h1>{{ user.username }} welcome to your profile page</h1>
<img src="{{ user.userprofile.profile_picture.url }}" width = "150" height = "150" />
<h2>{{ user.userprofile.first_name }}</h2>
<h2>{{ user.userprofile.second_name }}</h2>
<h2>{{ user.userprofile.user_country }}</h2>
{% endif %}
{% endblock %}
Register urls of your app in the configuration folder project_name/urls.py :
E.g :
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^user/', include('<app_name>.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Add a new route in your <app_name>/urls.py.
E.g :
from . import views
urlpatterns = [
url(r'profile/(?P<username>[a-zA-Z0-9]+)$', views.get_user_profile),
]
Add a view in <app_name>/views.py that take username (username of the user) to retrieve its information and send them into a template
E.g :
from django.shortcuts import render
def get_user_profile(request, username):
user = User.objects.get(username=username)
return render(request, '<app_name>/user_profile.html', {"user":user})
Create a template file in <app_name>/templates/<app_name>/user_profile.htmlto display user object :
{{ user.username }}
{{ user.email }}
{{ user.first_name }}
{{ user.last_name }}
Replace <app_name> by the name of your app and it should be good.

Categories

Resources