django 2.0.7 NoReverseMatch at /posts - python

Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name.
After Django goes to 2.0.7, I set up some url rules. It works locally at 127.0.0.1 on my computer, but not remotely on the machine (ubuntu 1604).
code:
post_list.html:
{% for post in posts %}
<div>
<p>published: {{ post.published_date }}</p>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}
blog.urls:
urlpatterns = [
path('', views.home_page, name='home_page'),
path('posts', views.post_list, name='post_list'),
path('post/<pk>/', views.post_detail, name='post_detail'),
]
blog.views:
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
mysite.urls:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
Solved. I need to add 'blog' as my app_name in blog.url and add 'blog' as my namespace in mysite.url
Thanks guy!
In 2.0.7, I need to add an app_name (blog) in blog.url and add a namespace in mysite.url (blog). Only adding a namespace in mysite.url without adding an app_name in blog.url -> django will tell me to add an app name. Only adding an app_name in blog.url without adding a namespace in mysite.url -> django will tell me blog is a not registered namespace. Also remember to refresh gunicorn.

Suppose your app name is blog so in your blog's urls.py add
app_name= 'blog'
and in template use {% url 'blog:post_detail' pk=post.pk %}

Related

Show a list of Posts in a different URL

Django Blog APP comes with an out of the box index.html where it shows a list of all posts.
I need to show this list in a new URL, when I somply copy the html code from index.html and paste onto planoacao.html it doesn´t show anything.
This is the index.html:
{% for post in post_list %}
<div class="card mb-4" style="width: 18rem; ">
{% if post.get_finalizado_display == 'Não' %}
<!--<p class="card-text text-muted h6"> NOK </p>-->
<div class="card-body" style="background-color:#FF0909;">
{% else %}
<!--<p class="card-text text-muted h6"> ok </p>-->
<div class="card-body">
{% endif %}
{% endfor %}
This is my views.py:
from django.views import generic
from .models import Post
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
class Calendar(generic.DetailView):
model = Post
template_name = 'calendar.html'
class Planoacao(generic.DetailView):
model = Post
template_name = 'planoacao.html'
This is my urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
url(r'^planoacao/', TemplateView.as_view(template_name="planoacao.html")),
url(r'calendar', TemplateView.as_view(template_name="calendar.html")),
url(r'^admin/', admin.site.urls),
url(r'^', include('blog.urls'), name="Blog"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
How can I show a list of all posts in a different URL? xxx/planoacao.html ? Simply copying the html from index.html doesn´t work.
Note that I don´t want to change the regular index.html post list, I just want to add a second post list page.
It seems you want to show your PostList view at /planoacao, so in urls.py you can hook this path up to that view:
url(r'^planoacao/', PostList.as_view()),
Note that in Django there is no direct link between the path of a view and the template used. You can use any template with any path, all you have to do is define which template to use in the view.

Django 2.0 - Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name

I'm having this error message after trying to change my app's password.
Do you have any idea of what's causing this route to fail?
Actually, it is changing the password but it isn't rendering the success template "password_change_done.html".
Thanks!
app/urls.py
from django.contrib.auth import views as auth_views
from django.urls import path
​
from . import views
​
app_name = 'account'
​
urlpatterns = [
# path('login/', views.user_login, name='login'),
path('', views.dashboard, name='dashboard'),
​
# login / logout urls
path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'),
​
# change password urls
path('password-change/', auth_views.PasswordChangeView.as_view(), name='password_change'),
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
]
​
​
ERROR MESSAGE
# NoReverseMatch at /account/password-change/
# Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name.
# Request Method: POST
# Request URL: http://localhost:8000/account/password-change/
# Django Version: 2.0.4
# Exception Type: NoReverseMatch
# Exception Value:
# Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name.
# Exception Location: C:\env\django_social_website\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632
# Python Executable: C:\env\django_social_website\Scripts\python.exe
# Python Version: 3.6.3
# Python Path:
# ['C:\\Projects\\django_social_website',
# 'C:\\env\\django_social_website\\Scripts\\python36.zip',
# 'C:\\ProgramData\\Anaconda3\\DLLs',
# 'C:\\ProgramData\\Anaconda3\\lib',
# 'C:\\ProgramData\\Anaconda3',
# 'C:\\env\\django_social_website',
# 'C:\\env\\django_social_website\\lib\\site-packages',
# 'C:\\env\\django_social_website\\lib\\site-packages\\setuptools-28.8.0-py3.6.egg',
# 'C:\\env\\django_social_website\\lib\\site-packages\\pip-9.0.1-py3.6.egg']
# Server time: Thu, 5 Apr 2018 21:34:22 +0000
​
app/templates/registration/password_change_form.html
{% extends "base.html" %}
​
{% block title %}Change your password{% endblock %}
​
{% block content %}
<h1>Change your password</h1>
<p>Use the form below to change your password.</p>
<form action="." method="post">
{{ form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Change"></p>
</form>
{% endblock %}
​
​
app/templates/registration/password_change_done.html
{% extends "base.html" %}
​
{% block title %}Password changed{% endblock %}
​
{% block content %}
<h1>Password changed</h1>
<p>Your password has been successfully changed.</p>
{% endblock %}
Thanks for your help!
I think the problem here is, as Tobit hints, is that your URLs are using an application namespace called account. That has been defined by the presence of app_name = 'account' in your urls.py.
The PasswordChangeView does not expect a namespace when looking up the password_change_done view. However, you can override that in your urls.py by specifying an explicit success_url attribute:
from django.urls import reverse_lazy
​
# change password urls
path('password-change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('account:password_change_done')), name='password_change'),
More info on namespaces: https://docs.djangoproject.com/en/2.0/topics/http/urls/#url-namespaces-and-included-urlconfs
It works for me:
# account urls.py
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
from django.urls import reverse_lazy
app_name = 'account'
urlpatterns = [
#Password Changes URLs
path('password_change/', auth_views.PasswordChangeView.as_view(
success_url=reverse_lazy('account:password_change_done')
), name='password_change'),
path('password_change/done/',auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
]
The main link is here:
https://django.fun/en/qa/11928/

Displaying content in home page in django

I am following the Django tutorial. I have a /films page and /films/id page displaying successfully. I would like to divert slightly from the tutorial and one step of this is to display the content which is currently appearing in /films in the website home e.g. http://127.0.0.1:8000/
I currently have:
index.py:
def index(request):
latest_film_list = Film.objects.order_by('-pub_date')[:5]
context = {'latest_film_list': latest_film_list}
return render(request, 'films/index.html', context)
index.html:
{% if latest_film_list %}
<ul>
{% for film in latest_film_list %}
<li>{{ film.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No films are available.</p>
{% endif %}
films/urls.py:
urlpatterns = [
path('', views.index, name='index'),
# # ex: /films/5/
path('<int:film_id>/', views.detail, name='detail'),
# # ex: /films/5/results/
path('<int:film_id>/results/', views.results, name='results'),
# # ex: /films/5/vote/
path('<int:film_id>/vote/', views.vote, name='vote'),
]
mysite.urls.py
urlpatterns = [
url(r'^films/', include('films.urls')),
url(r'^admin/', admin.site.urls),
]
I realise I probably just need to add/adjust the films/urls.py file but have been unsuccessful so far. Home currently displays a 404.
You can simply change your url as follows:
From this:
url(r'^films/', include('films.urls'))
To this:
url(r'^', include('films.urls'))

django.urls.exceptions.NoReverseMatch: Reverse for 'sign_up' not found. 'sign_up' is not a valid view function or pattern name

Django version 1.11.5,
views.py
class SignupPage(CreateView):
form_class = forms.UserSignupForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
website/urls.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.contrib.auth.views import LoginView,LogoutView
from . import views
app_name = 'website'
urlpatterns = [
url(r'^login/', auth_views.LoginView.as_view(template_name='signin_2_w.html'), name='login'),
url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),
url(r'^signup/', views.SignupPage.as_view(), name='sign_up'),
forms.py
class UserSignupForm(UserCreationForm):
class Meta:
fields = ('username','email','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = "Display Name"
self.fields['email'].label = "Email Address"
self.fields['password1'].label = "Password"
self.fields['password2'].label = "Confirm Password"
proj/urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.HomePage.as_view(),name='home'),
url(r'^website/',include('website.urls',namespace='website')),
url(r'^website/',include('django.contrib.auth.urls')),
url(r'^website/',views.StreamyePage.as_view(),name='streamye'),
url(r'^thanks/$',views.ThanksPage.as_view(),name='thanks'),
url(r'^congrats/$',views.CongratsPage.as_view(),name='congrats'),
url(r'^aboutus/$',views.AboutusPage.as_view(),name='about_us'),
HTML
<ul class="nav navbar-nav navbar-right">
{% if user.is_authenticated %}
<li>Logout</li>
{% else %}
<li>Login</li>
<li>Signup</li>
{% endif %}
</ul>
In the above code, the signup page is throwing me a error -- "django.urls.exceptions.NoReverseMatch: Reverse for 'sign_up' not found. 'sign_up' is not a valid view function or pattern name."
Please someone help me out where im wrong!
Thanks in advance!
You have to fix the links in the template to target the website urls :
{% if user.is_authenticated %}
<li>Logout</li>
{% else %}
<li>Login</li>
<li>Signup</li>
{% endif %}
In my case, the reason was that the session cookie was corrupted due to code changes.
I solved it by opening my app url in the incognitio mode(which will create fresh session cookie),
Then try non-incognitio normal url login.
If you are using Django rest framework, this may help.
When you have router as,
router.register("path", SomeViewSet, basename="some-name")
Call the reverse as,
reverse("some-name-list")

404 error when viewing details of a poll in Django

I'm working through the Django tutorial anf. For some reason, if I try to manually type in the URL like so: http://localhost:8000/polls/1/ I can view the poll (in this case the id of the poll is 1). But if I'm at the index of all the polls, which would be the URL: http://localhost:8000/polls and I try to click on one of the polls, it takes me to an error page with the following:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/ ^$ [name='index']
^polls/ ^(?P<pk>\d+)/$ [name='detail']
^polls/ ^(?P<pk>\d+)/results/$ [name='results']
^polls/ ^(?P<poll_id>\d+)/vote/$ [name='vote']
^admin/
The current URL, polls/{% url 'polls:detail' poll.id % }, didn't match any of these.
Here's my polls/urls file:
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
And my mysite/urls file:
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^admin/', include(admin.site.urls)),
)
And my template file:
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
I've seen similar questions but it doesn't seem that they apply to me. Why does it work when I type in the URL but not when I click on the link that should take me to the same place?
You have space between % and }, try this
<a href="{% url 'polls:detail' poll.id %}">

Categories