Django - Model id in Detail View URL, 1st id not working - django

I have a model, Position, which I have created a detail view to view each individual position.
views.py
def position_detail_view(request, id=None):
position = get_object_or_404(Position, id=id)
context= {
'object': position,
}
return render(request, 'positions/position_detail.html', context)
positions/urls.py
from django.urls import path, include
from .views import position_list_view, position_detail_view
urlpatterns = [
path('', position_list_view),
path('<int:id>', position_detail_view, name='detail')
]
When I go to http://localhost:8000/apply/1/, where the id=1, I get a Page Not Found 404 Error. However, with any other id, the page loads just fine. Any ideas on why the first id in the model gives a 404 error?
Edit 1: Traceback Error
Page not found (404) Request Method: GET Request
URL: http://localhost:8000/apply/1/ Using the URLconf defined in
bta_website.urls, Django tried these URL patterns, in this order:
admin/ [name='home'] apply/application/ apply/ apply/
[name='detail'] The current path, apply/1/, 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.

Django get_object_or_404 works like below.
get_object_or_404(klass, *args, **kwargs)
Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.
In your case,
your URL path is not properly configured.
Try to make changes this:
path('/<int:id>/', position_detail_view, name='detail')

Related

Django, Error 404, Not Found: /products/5

I have quation regarding Django, I tried to solve it myself during 2 days, but need some help.
I read a book about Django, and there is example:
urls.py
from django.urls import re_path
from django.urls import path
from firstapp import views
urlpatterns = [
re_path(r'^products/?P<productid>\d+/', views.contact),
re_path(r'^users/(?P<id>\d+)/?P<name>\D+/', views.about),
re_path(r'^about/contact/', views.contact),
re_path(r'^about', views.about),
path('', views. index),
]
views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("<h2>Main</h2>")
def about(request):
return HttpResponse("<h2>About site</h2>")
def contact(request):
return HttpResponse("<h2>Contacts</h2>")
def products(request, productid):
output = "<h2>Product № {0}</h2>".format(productid)
return HttpResponse(output)
def users(request, id, name):
output = "<h2>User</h2><h3>id: {О} " \
"Name:{1}</hЗ>".format(id, name)
return HttpResponse(output)
But after using this link http://127.0.0.l:8000/products/5, I get this text:
Using the URLconf defined in hello.urls, Django tried these URL patterns, in this order:
^products/?P<productid>\d+/
^users/(?P<id>\d+)/?P<name>\D+/
^about/contact/
^about
The current path, products/5, 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.
And this thing in terminal:
Not Found: /products/5
[08/Feb/2023 12:17:13] "GET /products/5 HTTP/1.1" 404 2597
Haven't tested this solution myself yet - but it looks like you're missing some parentheses. Also the product mapping is wrong (should be views.products instead of views.contact).
I believe the first path you've configured should be something like:
re_path(r'^products/(?P<productid>\d+)/', views.products),
This should work, but will match products/5 as well as products/5/anything/else/here which is probably not the behaviour you're after. In that case the path should be something like:
re_path(r'^products/(?P<productid>\d+)/$', views.products),
The django docs do a pretty good job at explaining how all this works in any level of detail you need, see https://docs.djangoproject.com/en/4.1/ref/urls/#re-path

Django 404 Error page not found...the current path matched the last one

I'm new to django and I'm playing around with my own variation of the polls tutorial. My app was working fine, every page loaded correctly. Then I made a single change; I created and then deleted a model. Now, many of urls seem broken. And I don't understand this error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/pick/
Raised by: polls.views.pick
Using the URLconf defined in mySite.urls, Django tried these URL patterns, in this order:
polls/ [name='index']
polls/ <int:pk>/ [name='detail']
polls/ <int:pk>/results/ [name='results']
polls/ <int:question_id>/vote/ [name='vote']
polls/ <int:question_id>/tally/ [name='tally']
polls/ <int:question_id>/pick/ [name='pick']
The current path, polls/1/pick/, matched the last one.
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.
So I don't understand why it says both that: The current path, polls/1/pick/, matched the last one.
and also page not found? How does that work? And what could have caused this when the app was working fine previously?
My urls.py:
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('<int:question_id>/tally/', views.tally, name='tally'),
path('<int:question_id>/pick/', views.pick, name='pick'),
path('<int:pk>/video/', views.VideoView.as_view(), name='video'),
path('<int:pk>/reveal/', views.RevealView.as_view(), name='reveal'),
]
And views snippit:
def pick(request, question_id):
question = get_object_or_404(Question, pk=question_id)
player = get_object_or_404(Player, pk=1)
question.score = player.score
question.save()
return HttpResponseRedirect(reverse('polls:video', args=(question.id,)))
This line of the error
Raised by: polls.views.pick
Is telling you that you didn't get a 404 due to not finding a matching URL, you got a 404 because your view function polls.views.pick raised a 404. You have two lines in that function that could raise a 404
question = get_object_or_404(Question, pk=question_id)
player = get_object_or_404(Player, pk=1)
So in your database, you either don't have a Question with pk=1 or you don't have a Player with pk=1.

using Handler404 in django url dispatcher cause server error

I followed this https://stackoverflow.com/a/31381075/10087274 because I want when url does not exist a json shows error but the problem is here that I get server error 500 when I add handler404 in my url dispatcher
here is my project url :
from django.urls import path, include
from django.conf.urls import handler404
from api.exception import custom404
handler404 = custom404
urlpatterns = [
path('api/v1/', include('acl.urls')),
]
and I have exception.py inside my project folder (near settings.py) contains this:
from django.http import JsonResponse
def custom404(request):
return JsonResponse({
'status_code': 404,
'error': 'The resource was not found'
})
I dont know how can I solve my problem
Unfortunately, you haven't provided much information regarding the error traceback. Anyway, The very first thing I noticed in your code, you've missed one optional parameter to the custom404 function. That function should take two parameters, request and exception
def custom404(request, exception=None):
response = {
'status_code': 404,
'error': 'The resource was not found'
}
return JsonResponse(response, status=404)
Reference
1. Custom Error Views
Well django rest framework is open source, so if you want to replicate certain behaviour you can read the code and pick and chose what you like. For instance, you can see that the Generic Error view (custom server and bad request error views) provided in drf docs are located inside exceptions.py inside rest_framework you can look it up here and see how it can be done.
Create a custom 404 view, like this:
def not_found(request, exception, *args, **kwargs):
""" Generic 404 error handler """
data = {
'error': 'Not Found (404)'
}
return JsonResponse(data, status=status.HTTP_404_NOT_FOUND)

Django - get_object_or_404 returns 500 instead of 404

I was trying to test get_object_or_404 method in my view. So I set DEBUG=False and set ALLOWED_HOSTS=['*'].
Now, when I go to http://127.0.0.1:8000/profile/correctusername/, it returns a correct profile. The problem is that if I try to write incorrect username, it returns 500 instead of 404 - according to name of the functio I suppose that it should return 404.
def get_user_profile(request, username):
# user = User.objects.get(username=username)
user = get_object_or_404(User, username=username)
jobs = user.jobs.all()
table = MyJobsTable(jobs)
context = {
'my_jobs': table,
"user_": user
}
return render(request, 'auth/profiles/my-profile.html', context=context)
Why is that so and how to fix it?
I encountered the same problem and Milano Slesarik's comment helped me figure out the solution. It turns out that I recently assigned a custom 404 handler but didn't do it correctly.
Here's what I did right:
add following line to urls.py. No need to add from django.conf.urls import handler404:
handler404 = views.error404
Here's what I did wrong. In my views.py I added this function:
def error404(request):
return HttpResponseNotFound('custom 404 not found')
But I forgot to import HttpResponseNotFound in views.py:
from django.http import HttpResponse, HttpResponseNotFound
So it was raising an exception. But since I just set DEBUG=False I couldn't see the error. I just saw the 500 response code.
Hope that helps someone!
with the following line in urls.py:
handler404 = 'views.error404'
If the project has several apps with their own urls.py you should add handler404 = 'app_name.views.my_handle404' to to the root url conf (that exists in project directory by default)
For me the only solution that worked (Django 3.7) dev/prod is here
Please see #elano7 answer

Django Unable to Find reverse() URL

I have the following URLConf setup:
urlpatterns = patterns('myapp.views',
url(r'^$', 'index', name="home"),
url(r'^login$', 'login'),
)
So far in my views, I have this:
def index(request):
"""Displays paginated message views"""
return HttpResponseRedirect(reverse("myapp.views.login"))
def login(request):
"""Displays login screen"""
return render_to_response('myapp/login.html', {
"title": "Login"
})
The problem arises when I try to go to the login page. Django seems to be unable to find my URL.
Going to the url http://localhost:8000/login, I receive the following error:
Page not found (404)
Request Method: GET Request
URL: http://localhost:8000/login
'login' could not be found
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.
It seems that even though I am using the reverse function to find Django's own recommended URL based on my URLConf, it is still unable to find its own URL!
Any ideas?
EDIT:
I need to clarify somethings: The problem is not that Django is unable to figure out the correct URL, it is that once that URL is loaded, Django is unable to find the view associated with that.
can you please put name attribute to your url like this
url(r'^$', 'index', name="home"),
then call reverse with this name
examples
urlpatterns = patterns('',
url(r'^archive/(\d{4})/$', archive, name="full-archive"),
url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"),
)
from django.core.urlresolvers import reverse
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
It turns out the error was caused by me changing the STATIC_URL variable in my settings.py file. Changing that back to "/static/" made everything work.