I'm at the last part of this tutorial.
from django.conf.urls import patterns, include, url
from django.views.generic import DetailView, ListView
from polls.models import Poll
urlpatterns = patterns('',
url(r'^$',
ListView.as_view(
queryset=Poll.objects.order_by('-pub_date')[:5],
context_object_name='latest_poll_list',
template_name='polls/index.html')),
url(r'^(?P<pk>\d+)/$',
DetailView.as_view(
model=Poll,
template_name='polls/detail.html')),
url(r'^(?P<pk>\d+)/results/$',
DetailView.as_view(
model=Poll,
template_name='polls/results.html'),
name='poll_results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
)
The ListView works, but when I visit a url with DetailView, I get.
AttributeError at /polls/2/
Generic detail view DetailView must be called with either an object pk or a slug.
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/2/
Django Version: 1.4.1
Exception Type: AttributeError
Exception Value:
Generic detail view DetailView must be called with either an object pk or a slug.
Exception Location: /home/yasith/coding/django/django-tutorial/lib/python2.7/site-packages/django/views/generic/detail.py in get_object, line 46
Python Executable: /home/yasith/coding/django/django-tutorial/bin/python2
Python Version: 2.7.3
I'm not sure what I'm doing wrong. Any help would be appreciated.
EDIT: Add the main urls.py
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)),
)
I think the code you posted above, is not the one you have on your disk.
I had the same problem, but then I looked carefully at both, my code and the tutorial. The regex I had in my code was different from the tutorial.
This was my code:
url(r'^(?P<poll_id>\d+)/$',-$
url(r'^(?P<poll_id>\d+)/results/$',-$
This is the correct core:
url(r'^(?P<pk>\d+)/$',-$
url(r'^(?P<pk>\d+)/results/$',-$
Note that *poll_id* was in the previous sections of the tutorial, but generic views require pk. Also note that the tutorial is correct, and you posted the correct code (from the tutorial.)
Look Carefully in the Tutorials they have mentioned to change the urlpatterns to use primarykey instead of question_id.
Related
I used the official Django documentation to create this code and I consistently get a 404 error when I put localhost:server/polls/ in the search bar. I followed the tutorial pretty much identically but it still doesn't seem to work. Anyone know a solution to get text displayed at localhost:server/polls/ or at localhost:server?
polls/views.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(response):
return HttpResponse('Polls')
polls/urls.py:
from django.urls import path
from . import views
urlpatterns =[
path('', views.index, name='index'),
]
mysite/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/', include('polls.urls')),
]
Error message:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/
The current path, polls/, didn't match any of these.
I have looked at lots of different potential solutions and none of them seem to work. Please let me know if you need more info/code, thanks
So far, I have built a REST API with Django Rest Framework (DRF) which can be consumed by any front-end. Let call this API backend.
I am trying to add another Django app (a regular one this time i.e. no DRF) which shares the same models. Let call this app webapp
However, it seems that the URLs linked to webapp are not available.
Here is my urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from rest_framework.authtoken import views as token_views
from backend import views
from webapp import views as webapp_views
router = routers.SimpleRouter()
router.register(r'users', views.UserViewSet, 'User')
router.register(r'games', views.GameViewSet, 'Game')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^connect/', views.CustomObtainAuthToken.as_view()),
url(r'membership_create/', views.MembershipCreate.as_view()),
url(r'auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()),
url(r'auth/connect_with_credentials/', views.TokenViewWithData.as_view()),
url(r'debug/', views.UserLoginAndIdView.as_view()),
url(r'^auth/', include('rest_framework_social_oauth2.urls'),
url(r'^test/', webapp_views.home, name='test'), # the new view
)
]
urlpatterns += router.urls
And the single view (from webapp.views):
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return HttpResponse("""
<h1>WEBAPP !</h1>
<p>test webapp</p>
""")
I am thus wondering if DRF and regular Django views can be mixed so easily or if it is not the right way of doing it.
EDIT:
Using the URLconf defined in WMC.urls, Django tried these URL patterns, in this order:
^admin/
^connect/
membership_create/
auth/connect_with_fb/
auth/connect_with_credentials/
debug/
^auth/
^users/$ [name='User-list']
^users/(?P<pk>[^/.]+)/$ [name='User-detail']
^users/(?P<pk>[^/.]+)/games/$ [name='User-games']
^games/$ [name='Game-list']
^games/(?P<pk>[^/.]+)/$ [name='Game-detail']
The current URL, test/, didn't match any of these.
Moving url(r'^test/', webapp_views.home, name='test') before url(r'^admin/', admin.site.urls) solves the problem although I do not know why.
urlpatterns = [
url(r'^test/', webapp_views.home, name='test'),
url(r'^admin/', admin.site.urls),
url(r'^connect/', views.CustomObtainAuthToken.as_view()),
url(r'^membership_create/', views.MembershipCreate.as_view()),
url(r'^auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()),
url(r'^auth/connect_with_credentials/', views.TokenViewWithData.as_view()),
url(r'^debug/', views.UserLoginAndIdView.as_view()),
url(r'^auth/', include('rest_framework_social_oauth2.urls'),
)
]
I am trying to learn about class based views and django in general. The project is notes_project and in it I have created an app notes. Below is the urls.py for both of these and views.py for notes app:
notes_project/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
import notes
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'notes_project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^notes/', include('notes.urls')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
)
notes/urls.py
from django.conf.urls import include, patterns, url
from .views import IndexView
urlpatterns = patterns(r'^$/', IndexView.as_view())
notes/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
class IndexView(View):
def get(request):
return HttpResponse("Welcome to notes index")
However, whenever I access the URL http://127.0.0.1:8000/notes/, I keep getting below error:
Request Method: GET
Request URL: http://127.0.0.1:8000/notes/
Django Version: 1.7.4
Exception Type: AttributeError
Exception Value:
'function' object has no attribute 'resolve'
Exception Location: /path/notes/venv/lib/python3.4/site-packages/django/core/urlresolvers.py in resolve, line 345
Python Executable: /path/notes/venv/bin/python
Python Version: 3.4.2
Python Path:
['/path/notes/notes_project',
'/path/notes/venv/lib/python3.4',
'/path/notes/venv/lib/python3.4/plat-x86_64-linux-gnu',
'/path/notes/venv/lib/python3.4/lib-dynload',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/path/notes/venv/lib/python3.4/site-packages']
The first argument to patterns is a string that acts as prefix to the rest of the patterns. Also each pattern needs to be a tuple of its own. You've done that correctly in the main urls.py but missed it in the notes one. It should be:
urlpatterns = patterns('',
(r'^$', IndexView.as_view()),
)
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'),
)
Trying to teach myself Django but running into a snag.
Generic Views seem to be a great idea but I personally find the documentation a little cryptic at times (maybe I'm being prissy).
So I have been trying to use the Date Based generics views in and specifically ArchieveIndexView.
I have even attempted following some non-djangoproject.com examples and still have problems.
I used the example provided at this site.
Here is my current project/urls.py.
I am also at this point, not worrying about pattern matching, just trying to get it to work.
from django.conf.urls import patterns, include, url
from django.views.generic.dates import ArchiveIndexView
from blog.models import Entry
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', ArchiveIndexView.as_view('date_field': 'pub_date', 'queryset': Entry.objects.all())),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
With this setup I keep receiving a Invalid Syntax error at the line describing ArchiveIndexView class.
If I comment out this line the problem goes away. If I decouple the URLs to their appropriate app I get the same error.
The error suggest I just have something out of place, a comma or something but I have yet to conclude what it is.
Thank you!
use the below code
from django.conf.urls import patterns, include, url
from django.views.generic.dates import ArchiveIndexView
from blog.models import Entry
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', ArchiveIndexView.as_view({'date_field': 'pub_date', 'queryset': Entry.objects.all()})),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
You seem to forget the {} brace required for dict in url(r'^$', ArchiveIndexView.as_view('date_field': 'pub_date', 'queryset': Entry.objects.all())),
line.
Ah. I solved my own question thanks to a little pushing from shiva.
The dictionary works but only for the extra_content argument.
It was just done like that on the website I was trying to copy and for extra content in the documentation so I kept overlooking that glaringly obvious problem.
from django.conf.urls import patterns, include, url
from django.views.generic.dates import ArchiveIndexView
from blog.models import Entry
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', ArchiveIndexView.as_view(date_field='pub_date', queryset=Entry.objects.all())),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Just needed to sleep on it...