Django cant be reached via parameterized url - python

Hello StackOverflow community,
I'm currently learning how to use the library Django combined with Python. However, I've ran into some issues which are somehow strange. My situation is the following. I have a project called "animals" which is the base of the Django application. My app is called "polls". Then I've defined the following views.
polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
def animals(request, animal_id):
return HttpResponse("%s" % animal_id)
def index(request):
return HttpResponse('Hello world')
So far, so good. Unfortunatly I can't say the same about the urlpatterns.
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
# Redirects to localhost:8000/polls/<animal_id>
path('<int:animal_id>/',views.animals,name='animals')
]
Whenever I want to navigate to the url "localhost:8000/polls/10/" Django reminds me of the fact, that the url is not accepted by the application and a 404 Error is thrown inside my browser. Am I missing something here?
UPDATE
I've managed to resolve the problem by fixing a rather trivial error. While the polls/urls.py was alright, the problem lay inside the animals/urls.py file. This file looked like this:
animals/urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
url(r'^admin/', admin.site.urls),
path('polls',include('polls.urls')),
]
As one can see, the "polls" path is not finished with a "/" sign. This indicates to Django that my desired route would be localhost:8000/polls where is any integer I add to the url. However, you have to add the slash at the end. Otherwise Django won't work as expected.

Related

Avoid Django form being resubmitted by using HttpResponseRedirect

My views.py runs code fine when I press a button on my HTML page, views.py:
def start_or_end_fast(request):
#If starting fast, add a row to the db:
#fast_finished = False
#start_date_time using = current time
#end_date_time using = current time
if request.method == 'POST' and 'start_fast' in request.POST:
add_fast = logTimes(fast_finished=False,start_date_time=datetime.now(),end_date_time=datetime.now())
add_fast.save()
print(add_fast.start_date_time,add_fast.end_date_time)
print('Fast started')
#return render(request,'startandstoptimes/index.html')
return HttpResponseRedirect('startandstoptimes/index.html')
You can see my commented return line, this works but when I refresh the page I can resubmit the data, I want to avoid this. In researching my solution, I saw this could be solved using HttpResponseRedirect but I am not able to get this to work with my code, the more I change the more broken things become.
My application urls.py:
from turtle import home
from django.urls import path,include
from . import views
urlpatterns = [
path('', views.start_or_end_fast,name="start_or_end_fast")
]
My project urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('startandstoptimes.urls'))
]
I believe it is related to the URLs, due to the 404 message I see:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/startandstoptimes/index.html
Using the URLconf defined in myfastingsite.urls, Django tried these URL patterns, in this order:
admin/
[name='start_or_end_fast']
The current path, startandstoptimes/index.html, didn’t match any of these.
Am I going down the right route trying to use HttpResponseRedirect or is there a better solution?
class HttpResponseRedirect¶
The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g.
'https://www.yahoo.com/search/'), an absolute path with no domain
(e.g. '/search/'), or even a relative path (e.g. 'search/'). In that
last case, the client browser will reconstruct the full URL itself
according to the current path. See HttpResponse for other optional
constructor arguments. Note that this returns an HTTP status code 302.
See this link for more details: docs
As what the documentation says, HttpResponseRedirect accepts URL and not the path of your template. You should be doing it something like this:
from django.urls import reverse
return HttpResponseRedirect(reverse('start_or_end_fast'))

Page not found 404 - Django

I'm a newbie to Django and I know this probably has been asked alot of times.
So basically what's happening is when I try to create a new project and whenever I'm trying to run my server, by default it's opening http://127.0.0.1:8000/catalog/ and not http://127.0.0.1:8000/.
Even if I run the server with my other projects, I'm facing the same error.
I followed this django basics tutorial on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/skeleton_website
Idk but somehow I think it's default address is set to http://127.0.0.1:8000/catalog/.
Here's the link to the repo for the project:
https://github.com/Fanceh/django-404-error
Here's my project's urls.py:
from django.contrib import admin
from django.urls import path, include
from testuapp import urls
urlpatterns = [
path('admin/', admin.site.urls),
path('',include("testuapp.urls"))
]
Here's the code in my testuapp urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.testu),
]
Here's my webapp's views.py file:
from django.shortcuts import render
# Create your views here.
def testu(request):
render(request, 'Greetings!')
Is there any way I can change it?
Regards
From the tutorial link it mentions the redirect.
Any request for the root URL, will redirect you to /catalog.
Screenshot from the tutorial below.
HTH
so i assume you are below url pattern structure in your testuapp project.
urlpatterns = [
path('catalog',include("views.catalog"))
]
views.calalog is the name of the method in your view file.
Ok I think I figured it out, it's just the chrome cache. I cleared it and bam it's working!

When I try to write something in Django urls.py file, it doesn't show this in the browser

#code in urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name= 'index'),
path('about/', views.about, name ='about'),
]
#code in views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello")
def about(request):
return HttpResponse("about harry")
Body
I am doing this while watching a tutorial, and the same thing is working for him. Moreover, if mistakenly I write the wrong code and run, cmd shows the errors and on reloading the browser the server doesn't work more. Then I need to restart CMD and again run manage.py. Please tell me the reason and also the solution, Thanks.
What errors do you get?
Besides there're 2 urls' files: url routes for pages are inside urls.py in the same folder where views.py are. In another urls.py (the one which is in the same folder with manage.py) you may need to write following, assuming that 'polls' is the name of you application:
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
]
According to Django docs: include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.
If you still get the error: check that you’re going to http://localhost:8000/polls/ and not http://localhost:8000/

Django reporting 404 error on simple view?

I'm just barely getting started with Python and Django.
I've created my modules, migrated, added my modules to the admin section, etc. Now, I need to create my first view. I've been following this guide (Yes the machine I'm on is running 1.6)
My views.py file in the app (setup) looks like this...
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Setup Index")
My app'a urls.py looks like this...
from django.conf.urls import patterns, url
from setup import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
)
And my root urls.py looks like this...
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from django.conf.urls import include, patterns, url
from django.contrib import admin as djangoAdmin
from admin.controller import ReportWizard
from admin.forms import reportDetailsForm, reportDataViewsForm
from setup import views
djangoAdmin.autodiscover()
urlpatterns = patterns('',
url(r'^django-admin/', include(djangoAdmin.site.urls)),
#New User Wizard URL
url(r'^setup/', include('setup.urls')),
)
As far as I can tell I have followed the guide to the letter, but I am recieving a 404 error when navigating to myIP/setup.
There are no error messages on the 404 page. What is the issue?
For some reason your settings seem to override the default for either APPEND_SLASH or MIDDLEWARE_CLASSES.
Opening http://example.com/setup should cause a redirect to http://example.com/setup/, but somehow it doesn't for you.
Note that the latter URL is matched by your urls.py while the former is not (as should be the case).
The above should work if 'CommonMiddleWareis enabled andAPPEND_SLASHis set toTrue`.

Django Tutorial 3 - URL producing 404 error

I am following the Django 1.6 tutorial 3 (https://docs.djangoproject.com/en/1.6/intro/tutorial03/) and I have become stuck towards the beginning - "Writing your first view".
The Django tutorial first says to edit the views.py, which I have done as follows:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
Then it says to create a urls.py in the same directory, which I have done. My urls.py looks like this:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
The next instruction is to now check the URL http://localhost:8000/polls/ for the message 'Hello, world. You're at the poll index.' but my browser simply produces the Django 404 error - Page not found.
I'm sure I'm doing something pretty stupid but I can't what is wrong, I've tried restarting the python webserver. I've followed the previous 2 tutorials with success, can anybody help me out?
If it makes a difference, I'm using Windows7, Python 3.4.1 and Django 1.6.5
Your view.py for polls must be in projectname/polls/ directory when first urls.py will be in projectname/projectname/.
Then, if you decide to configure and add more polls app specific urls, you can create urls.py in projectname/polls/.

Categories