What does 'Reverse' means in errors when running Django? - python

I'm trying to run a blog build with django on the browser. And I got this error:
NoReverseMatch at /
Reverse for 'blog.views.post_detail' not found.
'blog.views.post_detail' is not a valid view function or pattern name.
My url.py of my app looks like:
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail),
]
It seems that when I type 127.0.0.1:8000/.
The url will direct to views.post_list.
And my views.py looks like:
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__isnull=False)
return render(request, 'blog/post_list.html', {'posts': posts}
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
post_list() will render the request with post_list.html.
Inside post_list.html, the error comes from the line:
<h1>{{ post.title }}</h1>
I don't really understand what 'Reverse' means in the error message. 'blog.views.post_detail' does exist in views.py. I think I got everything needed for the code and can't figure out what went wrong.
I'm new to django, sorry if the question is basic and thanks for answering!

Django 1.10 removed the ability to reverse urls by the view's dotted import path. Instead, you need to name your url pattern and use that name to reverse the url:
urlpatterns = [
url(r'^$', views.post_list, name='post-list'),
url(r'^(?P<pk>\d+)/$', views.post_detail, name='post-detail'),
]
And in your template:
<h1>{{ post.title }}</h1>

It seems that your urls.py should be as follows:
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list),
url(r'^(?P<pk>\d+)/$', views.post_detail),
]

You should define a name for your url:
urlpatterns [
url(r'^$', views.post_list,name=post_list),
]
then use url tag like this:
AppName is you django application name.

Related

django the print() is not working in the terminal

I am currently doing Django project with sqlite3 with ORM method.
I am unable to debug as print() is not working in the terminal even if I put print() function in views.py.
I checked in python shell, the queryset is working.
In views.py
from django.shortcuts import render,redirect
from .models import BookBoardModel
def index(request):
all_books = BookBoardModel.objects.all()
print(all_books)
for item in all_books:
print(item.title)
context = {'all_books': all_books}
return render(request, 'category_books_page/index.html', context)
The terminal shown with warning sign and not giving print():
Due to this, the variable all_books are not properly rendered in the index.html which will not generate any objects in index.html
In index.html
{{all_books}} It is not showing at all :(
In category_books_page.urls.py
from django.urls import path
from django.contrib import admin
from . import views
urlpatterns = [
path('', views.index, name='bookHome'),
]
In config.urls.py
from django.contrib import admin
from django.urls import path, include
from signup_page import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('default_page.urls')),
path('category_books_page/', include('category_books_page.urls')),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
You can try in template:
{% for book in all_books %}
{{ book.title }}
{% endfor %}
Try to restart runserver project

django objects method is not responding in views.py [duplicate]

I am currently doing Django project with sqlite3 with ORM method.
I am unable to debug as print() is not working in the terminal even if I put print() function in views.py.
I checked in python shell, the queryset is working.
In views.py
from django.shortcuts import render,redirect
from .models import BookBoardModel
def index(request):
all_books = BookBoardModel.objects.all()
print(all_books)
for item in all_books:
print(item.title)
context = {'all_books': all_books}
return render(request, 'category_books_page/index.html', context)
The terminal shown with warning sign and not giving print():
Due to this, the variable all_books are not properly rendered in the index.html which will not generate any objects in index.html
In index.html
{{all_books}} It is not showing at all :(
In category_books_page.urls.py
from django.urls import path
from django.contrib import admin
from . import views
urlpatterns = [
path('', views.index, name='bookHome'),
]
In config.urls.py
from django.contrib import admin
from django.urls import path, include
from signup_page import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('default_page.urls')),
path('category_books_page/', include('category_books_page.urls')),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
You can try in template:
{% for book in all_books %}
{{ book.title }}
{% endfor %}
Try to restart runserver project

Django Page not found with post request

So I am new to Django and I'm trying to create a HTML form (just following the tutorial for the name input) and I can input the name but can't direct to the /thanks.html page.
$ views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
print(form)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/polls/thanks.html')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
$ name.html
<html>
<form action="/polls/thanks.html" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<html>
$ /mysite/urls
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 polls import views
urlpatterns = [
path('', views.get_name, name='index'),
]
When I go to to the page, I can enter my name fine but then when I submit i get
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
polls/ [name='index']
admin/
The current path, polls/thanks.html, didn't match any of these.
Even though thanks.html is inside /polls
Sorry if the fix is super easy I just haven't used Django before.
Thanks :)
Create a view called thanks in views.py
def thanks(request):
return render(request, 'thanks.html')
Now, Link the /poll/thanks/ url to the thanks template by adding path('thanks/', views.thanks, name='thanks') to your urls.py of the polls app.
$ mysite/polls/urls.py
from django.urls import path
from polls import views
urlpatterns = [
path('thanks/', views.thanks, name='thanks'),
]
Finally change the following line in your get_name view
return HttpResponseRedirect('/polls/thanks/')
Change your main urls.py:
url(r'^polls/', include('polls.urls')),
And in your app's urls.py:
url(r'^$', views.get_name, name='index'),
And in your views.py change to:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return render(request, 'thanks.html')

NoReverseMatch - not a registered namespace

I am new to Django and I was working at my first project, but I got:
NoReverseMatch with Exception Value: 'hiring_log_app' is not a
registered namespace in base.html
which follows:
href="{% url 'hiring_log_app:index' %}" >Hiring Log
href="{% url 'hiring_log_app:topics' %}" >Topics
I made sure my namespace was correct and I looked at the other topics already opened without figuring out how to solve the issue.
I paste urls.py:
from django.contrib import admin
from django.conf.urls import include, url
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include ('hiring_log_app.urls', namespace='hiring_log_app')),
hiring_log_app/urls.py:
"""Define URL patterns for hiring_log_app"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^topics/$', views.topics, name='topics'),
]
views.py:
from django.shortcuts import render
from .models import Topic
def index(request):
"""The home page for hiring_log_app"""
return render(request, 'hiring_log_app/index.html')
def topics(request):
""" list of topics"""
topics = Topic.objects.raw( "SELECT text FROM HIRING_LOG_APP_TOPIC;")
context = {'topics' : topics}
return render(request, 'hiring_log_app/topics.html', context)
Does anyone know where I am making a mistake?
You have wrongly specified the namespace in urlpatterns. Follow the pattern below:
from django.contrib import admin
from django.conf.urls import include, url
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include (('hiring_log_app.urls','hiring_log_app'), namespace='hiring_log_app'))
Edit:
If you are using Django 2.2.4 then you should use path instead of url since the usage of it is replaced by re_path.
from django.contrib import admin
from django.conf.urls import include
from django.urls import re_path
urlpatterns = [
re_path(r'^admin/', include(admin.site.urls)),
re_path(r'', include (('hiring_log_app.urls','hiring_log_app'), namespace='hiring_log_app'))

Django issue with passing PK in urlconf

Im working on a blog, i'm trying to create a comments link from each blog post, which will go a page where the individual post with comments can be seen.
In my "list.html", where all the blog posts are listed, i have this code for each blog post:
<div class="blogpost-comments">Comments</div>
This then submits to my URLconf shown below:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
# ex: /post/5/ pk=5
url(r'^post/(?P<pk>\d+)/$', views.post, name='post'),
)
And below my view is shown:
def post(request, pk):
post = Post.objects.get(pk=pk)
return render(request, 'blog/post.html', {'post': post, 'user': request.user})
Im wanting to have the URL structure:
/blog/post/{pk}/
To access individual posts. For some reason i'm currently getting the error:
NoReverseMatch at /blog
Reverse for 'post' with arguments '(6L,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog$post/(?P<pk>\\d+)/$']
Which i don't understand. Can anybody help?
EDIT:
the main urls.py is as follow:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^blog/$', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Remove the $ from
url(r'^blog/$', include('blog.urls')),
so that it is
url(r'^blog/', include('blog.urls')),
You aren't actually including your blog urls because the regex is stopping at the $

Categories

Resources