NoReverseMatch: Reverse for 'INSERT URL NAME' not found - django

I am learning about Django forms and am struggling to render a basic 'results' page for the form.
I would be greatly appreciative if somebody could point out what I'm doing wrong! Thanks in advance :)
ERROR
NoReverseMatch at /search_query/
Reverse for 'results' not found. 'results' is not a valid view function or pattern name.
Request Method: POST
Request URL: http://ozxlitwi.apps.lair.io/search_query/
Django Version: 2.0
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'results' not found. 'results' is not a valid view function or pattern name.
Exception Location: /mnt/data/.python-3.6/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 632
Python Executable: /mnt/data/.python-3.6/bin/python
Python Version: 3.6.5
Python Path:
['/mnt/project',
'/mnt/data/.python-3.6/lib/python36.zip',
'/mnt/data/.python-3.6/lib/python3.6',
'/mnt/data/.python-3.6/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6',
'/mnt/data/.python-3.6/lib/python3.6/site-packages']
Server time: Fri, 1 Jun 2018 10:00:20 +0900
views.py
def search_query(request):
# If POST request, process the Form data:
if request.method == 'POST':
# Create a form instance and populate it with the data from the request (binding):
form = SearchQueryForm(request.POST)
# Check if the form is valid:
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('results'))
else:
form = SearchQueryForm()
context = {'form':form}
return render (request, 'mapping_twitter/search_query.html', context)
def results(request):
context = {'form':form}
return render(request, 'mapping_twitter/results.html', context)
mapping_twitter/urls.py
from django.urls import path
from . import views
app_name = 'mapping_twitter'
urlpatterns = [
path('', views.search_query, name='search-query'),
path('results/', views.results, name='results'),
]
mapping_data/urls.py
urlpatterns = [
path('search_query/', include('mapping_twitter.urls')),
path('admin/', admin.site.urls),
path('', RedirectView.as_view(url='/search_query', permanent=True)),
]
mapping_twitter/results.html
<!--- DRAFT --->
Display search results here

If your results endpoint is in an app called mapping_twitter, then you can get at it with reverse('mapping_twitter:results').
Further reading on reversing namespaced URLs: https://docs.djangoproject.com/en/2.0/topics/http/urls/#reversing-namespaced-urls

Related

Function in Django Views causing others to throw 404 errors

I have a weird bug where one view:
def view_dashboard (request, username):
# If no such user exists raise 404
try:
user = User.objects.get(username=username)
print(user)
except:
raise Http404
template = 'testingland/dashboard.html'
return render (request, template)
Is causing others to throw 404 errors when I visit their urls. Note: I get a 404 when I visit the above view's connected url but also when I visit another view's url. For instance, visiting the url associated with this view also throws a 404:
def write_description(request):
return render(request, 'testingland/write_description.html')
Here are my url.py:
urlpatterns = [
path('index', views.cafes_home, name='cafes_home'),
path('', views.index_2, name='cafes_home'),
path('venue/<int:venue_id>/', views.venue_page, name='venue_page'),
url('electra/cafe_list/', views.cafe_list.as_view(), name='cafe_list'),
url('electra/marker_info/', views.marker_info, name='marker_info'),
url('electra/info_box/', views.info_box, name='info_box'),
url('electra/new_marker/', views.new_marker, name='new_marker'),
url('electra/broadsheet_scraper/', views.broadsheet_scraper, name='broadsheet_scraper'),
url('electra/get_cafe/', views.get_cafe, name='get_cafe'),
url('add_cafe', views.add_cafe, name='add_cafe'),
url('add_description', views.add_description, name='add_description'),
url('add_image', views.add_image, name='add_image'),
url('add_broadsheet', views.add_broadsheet, name='add_broadsheet'),
url('add_broadsheet', views.add_broadsheet, name='add_broadsheet'),
path('profile', views.profile, name='profile'),
path('users', views.users, name='users'),
path('<username>', views.view_dashboard, name='view_dashboard'),
url('electra/get_users/', views.get_users, name='get_users'),
path('electra/getUserMarkers/', views.getUserMarkers, name='getUserMarkers'),
#auth
path('signup', views.SignUp.as_view(), name='signup'),
path('login', auth.views.LoginView.as_view(), name='login'),
path('logout', auth.views.LogoutView.as_view(), name='logout'),
#placelist
path('write_description', views.write_description, name='write_description'),
# path('write_image', views.write_image, name='write_image'),
path('broadsheet', views.broadsheet, name='broadsheet'),
path('<int:pk>', views.DetailList.as_view(), name='detail_list'),
path('<int:pk>/update', views.UpdateList.as_view(), name='update_list'),
path('<int:pk>/delete', views.DeleteList.as_view(), name='delete_list'),
]
Here is the error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/dashboard
Raised by: testingland.views.view_dashboard

issue in redirecting user to home page django

When I try to login, it does not reedirect me to home page. instead, it shows me an error
the url should be http://127.0.0.1:8000/ it shows http://127.0.0.1:8000/login
I tried to user both function and path names
urls.py
app_name = "accounts"
urlpatterns = [
path('', views.home,name="home"),
path('register/',views.register, name='register'),
path('login/',views.loginPage, name='login')]
views.py
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request,username=username, password=password)
if user is not None:
login(request,user)
return redirect('home')
return render(request,'accounts/login.html')
Error
NoReverseMatch at /login/
Reverse for 'home' not found. 'home' is not a valid view function or pattern name.
Request Method: POST
Request URL: http://127.0.0.1:8000/login/
Django Version: 3.0.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'home' not found. 'home' is not a valid view function or pattern name.
Exception Location: C:\Users\Mahmoud Ishag\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677
In views.py the url name works differently to when in template.
You can try to change return redirect('home') to return redirect('') or return redirect('/'), depends on how you defined the URL in path('', views.home, name="home").

How to make custom 404 page for the Detail view with <int:pk>, if the instance not found?

so the error is Page not found(404) when I am requesting the instance that does not exist. I would like to customize the 404 page, instead of displaying the general error.
Here is my new_wiki/urls
from django.urls import path
from . import views
from .views import IndexView, InstanceView, AddPostView, EditPost
urlpatterns = [
# path('', views.index, name="index")
path('', IndexView.as_view(), name="index"),
path('instance/<int:pk>', InstanceView.as_view(), name="instance"),
path('create_post/', AddPostView.as_view(), name="create_post"),
path('instance/edit/<int:pk>', EditPost.as_view(), name="edit_post")
]
And my InstanceView class
class InstanceView(DetailView):
model = Post
template_name = 'new_wiki/instance.html'
I have tried to use the solution from Django documentation:
def detail(request, post_id):
try:
p = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
raise Http404("Poll does not exist")
return render(request, 'new_wiki/instance.html', {'post': p})
but it is still returning the same 404 page. Thank you
You can just render a page with a 404 status:
def detail(request, post_id):
try:
p = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
return render(request, 'new_wiki/404error.html', status=404)
return render(request, 'new_wiki/instance.html', {'post': p})
If you want to specify a custom 404 page in general, you specify the handler404 [Django-doc] in the urls.py:
from django.urls import path
from . import views
from .views import IndexView, InstanceView, AddPostView, EditPost
urlpatterns = [
# path('', views.index, name="index")
path('', IndexView.as_view(), name="index"),
path('instance/<int:pk>', InstanceView.as_view(), name="instance"),
path('create_post/', AddPostView.as_view(), name="create_post"),
path('instance/edit/<int:pk>', EditPost.as_view(), name="edit_post")
]
handler404 = views.handler404
In the view you can then analyze the exception parameter and return a specific
# app/views.py
from django.http import HttpResponseNotFound
def handler404(request, exception):
data = exception.args
if data:
return HttpResponseNotFound(data[0])
return HttpResponseNotFound('some text')
This then works if you set the DEBUG setting [Django-doc] to False:
# settings.py
DEBUG = False
In that case the handler will be invoked when you raise a Http404.
Please use get_object_or_404 method
from django.shortcuts import get_object_or_404
def detail(request, post_id):
p = get_object_or_404(Post,pk=post_id)
return render(request, 'new_wiki/instance.html', {'post': p})
Please check this is working.

Handling errors 404/500 in Django

There is a little problem with my Django application: my project is a blog with several posts. You can access the first post by typing localhost:8000/blog/post/1 in the URL bar. To read the post no. X you have to type localhost:8000/blog/post/X. So I need to display a custom "Error 404" page when an inexistant post is requested (for example localhost:8000/blog/post/32 if there are only 3 posts available). The problem is, instead of throwing a 404 error, it throws a Server Error (500) error however I never coded something to throw this kind of error.
Here is the concerned code parts, but not my full code which I think is useless.
Project name is red_pillers, app name is blog.
in red_pillers/settings.py
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
red_pillers/urls.py
from django.contrib import admin
from django.urls import path, re_path, include
from django.conf.urls import handler404
from . import views
handler404 = 'red_pillers.views.handler404'
urlpatterns = [
re_path('^blog/', include('blog.urls')),
re_path('^$', views.home),
re_path('^admin/', admin.site.urls),
]
red_pillers/views.py
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
def handler404(request):
return render(request, 'errors/404.html', {}, status=404)
blog/pycode/post.py
from django.http import Http404
class Post:
POSTS = [
{'id': 1, 'title': 'First Post', 'body': 'This is my first post'},
{'id': 2, 'title': 'Second Post', 'body': 'This is my second post'},
{'id': 3, 'title': 'Third Post', 'body': 'This is my third post'},
]
#classmethod
def all(cls):
return cls.POSTS
#classmethod
def find(cls, id):
try:
return cls.POSTS[int(id) - 1]
except:
raise Http404('Error 404...')
EDIT: added more code
blog/urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
re_path('^$', views.index),
re_path('^posts/(?P<id>[0-9]+)$', views.show),
]
blog/views.py
from django.shortcuts import render
from .pycode.post import Post
def index(request):
posts = Post.all()
return render(request, 'blog/index.html', {'posts': posts})
def show(request, id):
post = Post.find(id)
return render(request, 'blog/show.html', {'post': post})
Use get_object_or_404, which will redirect you if it doesn't exist.

Django login doesn't work

I tried to create a login view like the following:
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('rango/index.html')
else:
return HttpResponse('Your Rango account is disabled!')
else:
print("Invalid login details: {0}, {1}".format(username, password))
return HttpResponse("Invalid login details supplied!")
else:
return render(request, 'rango/login.html', {})
This seems to be the correct way to do so, but when I try to open the page in my browser, I get the following error:
TypeError at /rango/login/
login() missing 1 required positional argument: 'user'
Request Method: GET
Request URL: http://localhost:8000/rango/login/
Django Version: 1.9.10
Exception Type: TypeError
Exception Value:
login() missing 1 required positional argument: 'user'
Exception Location: C:\Users\Johannes\tangowithdjango\lib\site-packages\django\core\handlers\base.py in get_response, line 147
Python Executable: C:\Users\Johannes\tangowithdjango\Scripts\python.exe
Python Version: 3.6.0
Python Path:
['C:\\Users\\Johannes\\tangowithdjango\\tango_with_django_project',
'C:\\Users\\Johannes\\tangowithdjango\\Scripts\\python36.zip',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36\\lib',
'C:\\Users\\Johannes\\AppData\\Local\\Programs\\Python\\Python36',
'C:\\Users\\Johannes\\tangowithdjango',
'C:\\Users\\Johannes\\tangowithdjango\\lib\\site-packages']
Server time: Thu, 12 Jan 2017 17:56:38 +0100
Has anyone encountered something similar or knows a solution to the problem? I already searched and tried around for a bit but couldn't find an answer.
Your code looks good, make sure that you are importing this
from django.contrib.auth import authenticate, login
Also check your views
This is the first url:
url(r'^login', example_views.login, name='log'),
And you have to change to this:
url(r'^log', example_views.log, name='log'),
I followed that tutorial and came across the same error.
I solved it by correcting one line in urls.py
urlpatterns = patterns(
...
url(r'^login/$', views.login, name='login'),
)
into this:
urlpatterns = patterns(
...
url(r'^login/$', views.user_login, name='login'),
)
It should be the name of the login view you created, which is 'user_login' in your case.