Unable to get django declared app routes working as pages - python

I am creating an Django app and am facing issues with routes not being identified. It is the same DJango poll app I am trying to create but the documentation code does not work. Here is my code below:
djangoproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^simpleapp/', include('simpleapp.urls')),
url(r'^admin/', admin.site.urls),
]
simpleapp/views.py
from django.shortcuts import render
from django.http import HttpResponse, request
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
simpleapp/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /simpleapp/
# url('', views.index, name='index'),
# ex: /simpleapp/5/
url('<int:question_id>/', views.detail, name='detail'),
# ex: /simpleapp/5/results/
url('<int:question_id>/results/', views.results, name='results'),
# ex: /simpleapp/5/vote/
url('<int:question_id>/vote/', views.vote, name='vote'),
]
If I un-comment the first url of '' path of simpleapp/urls.py code, all the pages shown are '' path. However, if I keep the url '' path commented, then the routes give me the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/simpleapp/34/
Using the URLconf defined in simple_django.urls, Django tried these URL patterns, in this order:
^simpleapp/ <int:question_id>/ [name='detail']
^simpleapp/ <int:question_id>/results/ [name='results']
^simpleapp/ <int:question_id>/vote/ [name='vote']
^admin/
The current path, simpleapp/34/, 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.
I was unable to get the path() imported using django.conf.urls or django.urls. url() was successful. I am using python version 3.6.7 and Django version 2.1.5. What am I missing?

You are using path syntax, not regexes, in your simpleapp/urls.py. Change it to:
urlpatterns = [
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
Your project URLs are using regexes, so you shouldn't change those, although you might want to make them consistent.

You define routes like Django 1.x
url(r'^simpleapp/', include('simpleapp.urls')),
url(r'^admin/', admin.site.urls),
This is Django 1.x type route definition
In Django 2 you must define routes like this:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
In Django 2 routes define without regular expression
See docs for route define in Django 2

Related

django 4.1 polls tutorial, all done Admin working fine but index not found

ok polls tutorial is done and can enter questions, vote, etc. but from the admin pages View site aka localhost:8000 gives...
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
dose/
admin/
The empty path didn’t match any of these.
Now I have polls/views.py...
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""
Return the last five published questions (not including those set to be
published in the future).
"""
return Question.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
and mysite/urls.py set to ...
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
and polls/urls.py set to...
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'),
]
The only hint I can find is that all the imports show error highlights in VSCode with the Error "reportMissingModuleSources"
But python and django run perfectly well everywhere but index.html
No url at http://localhost:8000/ address is expected behaviour, where you want to go is http://localhost:8000/polls/.
If you want go directly to the desired View without writing polls/ prefix you should define your urls this way:
urlpatterns = [
path('', include('polls.urls')),
path('admin/', admin.site.urls),
]
So you place path() call without url prefix. Generally if you include any url group you define the beginning of address this way.

Adding paths in Django to create more views

I am following the tutorial on the Django website. I try and replicate this:
My code is as follows:
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def detail(request, film_id):
return HttpResponse("You're looking at film %s." % film_id)
def results(request, film_id):
response = "You're looking at the results of film %s."
return HttpResponse(response % question_id)
def vote(request, film_id):
return HttpResponse("You're commenting on film %s." % film_id)
films/urls.py
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
# url(r'^$', views.index, name='index'),
# ex: /polls/
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'),
]
With this I am getting ERR_CONNECTION_REFUSED. If I comment out all the paths leaving only the index url, and also comment out from django.urls import path a page displays, but that is where I was at before trying to add more views.
You are referring to the documentation for newer Django version as path() did not exist in older versions. You can select the documentation version by clicking on the Documentation version button at the bottom right here.

Why am I getting a 404 error when trying to access my website's domain name, yet if I domain name/home it works?

Okay... let's try to explain things clearly. I've used Python Django to create a dynamic webpage/web-app. After completing the website I have published it using DigitalOcean and have successfully attached my purchased domain name to the name server of DigitalOcean. When I access my website, ordinanceservices.com, i get an error 404; however, if I type ordinanceservices.com/home it works as it should and displays the home page. How, by editing the python files, can I have it to where ordinanceservices.com will display the home page as opposed to error 404? I feel like there's something that I am doing that is fundamentally wrong regarding my .urls structure and thus a rewrite/redirect in the nginx config should not be necessary.
Here is the specific error:
Page not found (404)
Request Method: GET
Request URL: http://ordinanceservices.com/
Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order:
^admin/
^ ^home/ [name='home']
^ ^contact/ [name='contact']
^ ^services/ [name='services']
The current URL, , didn't match any of these.
I somewhat understand what is happening here though I do not know how to fix this. Next I will provide my .urls files for each folder that contains such:
/django_project urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('company.urls')),
)
/company urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^home/', views.home, name='home'),
url(r'^contact/', views.contact, name='contact'),
url(r'^services/', views.services, name='services'),
]
/company views.py
from django.shortcuts import render
def home(request):
return render(request, 'company/home.html')
def contact(request):
return render(request, 'company/contact.html')
def services(request):
return render(request, 'company/services.html')
What I am aiming to do, without needing to redirect the main URL using the nginx config files to do so, is to edit my urls and views structure of my Python files to ensure that the normal URL, ordinanceservices.com, will actually display a page; preferably the home page of my webpage.
I have a hunch that it has to do with the fact that I do not have a views.index for the r'^admin/' to reach to. I am not certain but I have been trying to figure this out for hours. Does anyone have a clue what I can do to fix this?
You haven't defined anything at the root url. Add one more line to your company urls.py so it becomes
//company urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^home/', views.home, name='home'),
url(r'^contact/', views.contact, name='contact'),
url(r'^services/', views.services, name='services'),
]
First of all, check if you have added www.yourdomain.com or yourdomain.com to ALLOWED_HOST = ['www.yourdomain.com','yourdomain.com'] in your settings.py
and then in your company/urls.py do this
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^services/$', views.services, name='services'),
]
and in your main urls.py add this code
from django.conf.urls import url,include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('company.urls')),
]

Root url file is not communicating with app url file

I've created a project from official docs. Everything is same but still I am not able to communicate with my root urls.py through my app urls.py.
If I use views to redirect to app urls.py they don't work. But same if do with root urls.py it works fine.
My settings are:
ROOT_URLCONF = 'mysite.urls'
root urls:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/$', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
app urls.py:
from django.conf.urls import url
from polls import views
urlpatterns = [
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
Simple view I am trying to present is:
from django.shortcuts import render, HttpResponse, RequestContext, loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'index.html', context)
Please help
After removing the dollar from polls/$, I get a new error:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
^static\/(?P<path>.*)$
^media\/(?P<path>.*)$
The current URL, , 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.
Remove the dollar sign from the url that is including the polls urls.
url(r'^polls/', include('polls.urls')),

how to display a view in Django?

I'm totally new to Django, and I'm trying to understand how does it work (I'm more used to PHP and Spring frameworks.
I have a project called testrun and inside it an app called graphs, so my views.py looks like:
#!/usr/bin/python
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, World. You're at the graphs index.")
then, in graphs/urls.py:
from django.conf.urls import patterns, url, include
from graphs import views
urlpatterns = patterns(
url(r'^$', views.index, name='index'),
)
finally, at testrun/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'testrun.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^graphs/', include('graphs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
However, when I try to access http://127.0.0.1:8000/graphs/ I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/graphs/
Using the URLconf defined in testrun.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, graphs/, 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.
What am I doing wrong that I can't get that simple message to be displayed in the browser?
To expand on my comment, the first argument to patterns() function is
a prefix to apply to each view function
You can find more information here:
https://docs.djangoproject.com/en/dev/topics/http/urls/#syntax-of-the-urlpatterns-variable
Therefore in graphs/urls.py you need to fix the patterns call like so:
urlpatterns = patterns('', # <-- note the `'',`
url(r'^$', views.index, name='index'),
)

Categories