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.
Related
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.
Error:
NoReverseMatch at /
Reverse for 'detail' with arguments '(3,)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'$(?P<college_id>[0-9]+)/$']
The error is on this line:
<li>{{ college.college_name }}</li>
Here is the whole template (index.html):
{% if latest_college_list %}
<ul>
{% for college in latest_college_list %}
<li>{{ college.college_name }}</li>
{% endfor %}
</ul>
{% else %}
<p> No colleges available </p>
{% endif %}
The view:
from django.shortcuts import get_object_or_404, render
from .models import College
# Create your views here.
def index(request):
latest_college_list = College.objects.order_by('college_name')
context = {'latest_college_list': latest_college_list}
return render(request, 'app/index.html', context)
def detail(request, college_id):
college = get_object_or_404(College, pk=college_id)
return render(request, 'app/detail.html', {'college':college})
urls.py:
from django.conf.urls import url
from . import views
app_name = "app"
urlpatterns = [
# campusarchitecture.com/
url(r'^$', views.index, name="index"),
# /college_name
url(r'^(?P<college_id>[0-9]+)/$', views.detail, name="detail")
]
root urls conf:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('app.urls')),
url(r'^login/$', include('login.urls')),
url(r'^admin/', admin.site.urls),
]
Anyone know what the problem is?
Here is the issue:
url(r'^$', include('app.urls')),
Should be
url(r'^', include('app.urls', namespace="app")),
Note the $ should be removed as it indicates the end of the regex pattern, and it would not discover the included url patterns.
Secondly, you need to explicitly specify the namespace in the include. More on this in the documentation here.
Similarly, remove the $ after the login/ URL pattern match too.
Have the following problem; I am following Django by Example, Antonio Mele.The exercise here, is to set up user login and logout.Using the default contrib.auth views. When the code in the book is used. The logout view is that of the admin page logout; seems to be same issue as described here
django logout redirects me to administration page. Have tried all there no success
I have been working on this problem. My code now works, in that the admin template is no longer rendered. However, I am still unable to use my own logout.html. I can redirect to my own login.html... but not the logout.html.The logging out itself is working. User can log in, and out only this issue with the templates. I now only receive one browser error
The page isn't redirecting properly Iceweasel has detected that the >server is redirecting the request for this address in a way that will >never complete.This problem can sometimes be caused by disabling or >refusing to accept cookies.
checked the cookies can see csrf token is accepted
no traceback available no errors :-(
If I use the code below , all works with one exception. I am redirected at logout to the Django Administration logout template, and not my own logout.html....This is when using coede in the book.... My own modified code, with a seperate logout function also did not work generating a maximum recurson error.Editing the URLS.PY stops the rendering of the admin template. but the modified code seems to have an issue in the urls i.e .....
THIS IS NOT WORKING !!!!!
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/logout'}, name='logout'),
THIS WORKS PERFECTLY !!!!
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/login'}, name='logout'),
The code from the book is as follows
FROM BOOK SETTINGS.PY
from django.core.urlresolvers import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
FROM BOOK VIEWS.PY
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import LoginForm
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
FROM BOOK MAIN URLS.PY
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^account/', include('account.urls')),
]
MYAPP(account) URLS.PY
from django.conf.urls import url
from . import views
urlpatterns = [
# url(r'^login/$', views.user_login, name='login'),
url(r'^$', views.dashboard, name='dashboard'),
# login / logout urls
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
MY MODIFIFED CODE
I have now include a seperate logout definition in my view's and now also pass a {key:value} pair of {'next_page': '/account/logout'}.
if the logout def is used and mapped in the urls file it generates a maximum recursion error at line logout(request)
def logout(request):
logout(request)
request.session.flush()
request.user = AnonymousUser
# Redirect to a success page.
return HttpResponseRedirect(request,'/account/logout.html',context_instance = RequestContext(request))
without this def the only error generated is
"""
The page isn't redirecting properly
"""Iceweasel has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.""""
"""
I checked cookies in the browser, and see the csrf_token being accepted
For me the strange thing is that if the code: {'next_page': '/account/logout'} is changed to {'next_page': '/account/login'} everything works perfectly. Have tried all suggestions found, am at a loss any help appreciated ....
MY CODE
VIEWS.PY
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.contrib.auth.models import User
# Create your views here.
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html',{'section': 'dashboard' })
def user_login(request):
cd = None
if request.method=='POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],
password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled Account')
else:
return HttpResponse('Invalid Login')
else:
form = LoginForm()
return render(request, 'account/login.html',{'form': form},context_instance = RequestContext(request))
def logout(request):
logout(request)
request.session.flush()
request.user = AnonymousUser
# Redirect to a success page.
return HttpResponseRedirect(request,'/account/logout.html',context_instance = RequestContext(request))
MY CODE
account/urls.py
from django.conf.urls import url, patterns
from . import views
urlpatterns = [
# post views
#url(r'^login/$', views.user_login, name='login'),
# login/logout urls
url(r'^$', views.dashboard, name='dashboard'),
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout',{'next_page': '/account/logout'}, name='logout'),
url(r'^logout-then-login/$','django.contrib.auth.views.logout_then_login', name='logout_then_login'),
]
MY CODE
MAIN URLS.PY
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^account/', include("account.urls")),
]
MYCODE
SETTINGS.PY
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
INSTALLED_APPS = (
'account',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
# urlpatterns += patterns('django.contrib.auth.views',
# #url(r'^login/$', 'login', { 'template_name': 'registration/login.html'}, name='login' ),
# #url(r'^logout/$', 'logout', { 'template_name': 'registration/logout.html', 'next_page':reverse('index') }, name='logout' ),
# )
MYCODE
logout.html
{% extends "base1.html" %}
{% block title %}Logged Out{% endblock %}
{% block content %}
<h1>
Logged Out
</h1>
<p>
You have been successfully logged out. You can Log-in again
</p>{% endblock %}
MYCODE
base1.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}">
</head>
<body>
<div id="header">
<span class="logo">
BookMarks
</span>
{% if user.is_authenticated %}
<ul class="menu">
<li {% if section == "dashboard" %}class="selected"{% endif %}>
My dashboard
</li>
<li {% if section == "images" %}class="selected"{% endif %}>
Images
</li>
<li {% if section == "people" %}class="selected"{% endif %}>
People
</li>
</ul>
{% endif %}
{%if user.is_authenticated %}
<span class="user">
Hello {{ user.first_name }} {{ user.last_name }},
Logout
{% else %}
<a href='{% url "login" %}'>Log-in</a>
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
I was having same issue, but then I kept reading
"If you are seeing the log out page of the Django administration site instead of your own log out page, check the INSTALLED_APPS setting of your project and make sure that django.contrib.admin comes after the account application. Both templates are located in the same relative path and the Django template loader will use the first one it finds."
You are using contrib.auth's logout view in your urls.py. This view redirects to the URL specified by 'next_page'. You provide '/account/logout' as next_page -- where again the logout view is called!
That leads to an (infinite) redirect loop: the view redirects to itself.
Try instead: in your own logout view:
# no redirecting here!
return render(request, 'account/logout.html',
context_instance=RequestContext(request))
Add a url for that view in account/urls.py:
url(r'^post-logout/$', logout, name='post-logout'),
# logout being your own view
Then provide that url as 'next_page' to the actual (auth) logout:
url(r'^logout/$', 'django.contrib.auth.views.logout',
{'next_page': '/account/post-logout'}, name='logout'),
The solution to the problem is to map the url as follows
url(r'^logout/$', 'django.contrib.auth.views.logout', { 'template_name': 'account/logout.html',}, name='logout' ),
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.
So I'm also getting the noReverseMatch error at the very end of the 4th chapter of the Django tutorial. But none of the other answers seems to help out in my case. And I can't understand why the tutorial would provide something that doesn't work.
I type everything myself, so there could certainly be a typo somewhere, but I've tried exchanging all the code with copy/paste from chapter 4, and I'm still getting the same error:
Here is the error:
NoReverseMatch at /polls/
Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<pk>[0-9]+)/$']
Error during template rendering
In template /home/MyName/tutorial/mysite/polls/templates/polls/index.html, error at line 4
Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<pk>[0-9]+)/$']
Here is urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote')
]
Here is views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Question, Choice
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question':p,
'error_message': "You didn't select a choice",})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
And here is index.html:
{% 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 %}
Change this
{% url 'polls:detail' question_id %} to {% url 'polls:detail' question.id %}
You are rendering question so to access its value it should be question.value not question_value:
user {% url 'polls:detail' question.id %"
where question.id is the numeric argument to the url.