How to write primary key in django 2.0.2 - python

the below code is working only for index page but it's not working for my DetailView. Please help me to fix (Using Django 2.0.2)
The below is my class for view:
from django.views import generic
from .models import Album
class IndexView(generic.ListView):
template_name = "newboston/index.html"
context_object_name = "all_album"
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DetailView):
model = Album
template_name = 'newboston/detail.html'
The below is my urls.py under my application.
from . import views
from django.urls import path
urlpatterns = [
path('', views.IndexView.as_view(), name='home'),
path('<slug:slug>/', views.DetailView.as_view(), name='detail'),
]

This is how you should refer to the primary key using pk in the urls.py file ...
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
Further details are in the documentation near the end of the page, or search for "polls/urls.py".

Related

Djnago : AttributeError: module 'django.views.generic' has no attribute 'Detail'

where can I import the detail attribute from?
views.py:
from django.shortcuts import render
from django.views import generic
from . import models
class Index(generic.TemplateView):
template_name='catalog/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['num_books'] = models.Book.objects.all().count()
context['num_instances'] = models.BookInstance.objects.all().count()
context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count()
context['num_authors'] = models.Author.objects.count()
return context
class BookListView(generic.ListView):
model = models.Book
template_name = 'catalog/book_list.html'
class BookDetialView(generic.Detail.View):
model= models.Book
template_name = 'catalog/book_detail.html'
urls.py
from django.urls import include, path, re_path
from . import views
from django.views.generic import TemplateView
app_name='catalog'
urlpatterns = [
path(r'', views.Index.as_view(), name='index'),
re_path(r'^$', views.Index.as_view(), name='index')
]
urlpatterns = [
path(r'^$', views.index, name='index'),
path(r'^books/$', views.BookListView.as_view(), name='books'),
path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
]
but the result:
class BookDetialView(generic.Detail.View):
AttributeError: module 'django.views.generic' has no attribute 'Detail'
Should be generic.DetailViewinstead of generic.Detail.View
In your BookDetailView you used generic.Detail.View instead of DetailView[Djano-doc].
Change your BookDetailView as
from django.views import generic
class BookDetialView(generic.DetailView): #<--- change here
model= models.Book
template_name = 'catalog/book_detail.html'
You have a couple of issues here.
(1) In your views you spell your view name as BookDetialView and in your url definition you spell it BookDetailView.
(2) I believe the correct inheritance is generic.DetailView instead of generic.Detail.View

Django reverse_lazy improperly configured

Under my once my user has signed up I would like to redirect them to the login page. However, reverse_lazy doesn't seem to be able to find my login path.
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUpView(CreateView):
form_class = forms.UserCreateForm
template_name = 'accounts/signup.html'
#Redirect login page once they have successfully signed up
succes_url = reverse_lazy('login')
urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
path('signup/', views.SignUpView.as_view(template_name='accounts/signup.html'), name='signup'),
]
That is because you specified an app_name = …, in that case you prefix the name of the view with the namespace:
class SignUpView(CreateView):
# …
success_url = reverse_lazy('accounts:login')
You furthermore made a typo, it is success_url [Django-doc], not succes_url.

Adding new pages in Django from existing data

I am trying to simply add a new 'blog' page in Django, which should replicate the home page. The home page is working fine, and if I view the URLs for my app, it looks like the following:
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
In my understanding of Django, I could add a 'blog' page by adding the following:
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
path('blog/', views.PostList.as_view(), name='blog'), #ADDED LINE
]
However going to my http://127.0.0.1:8000/blog/ page returns a 404 error. With Django debugging enabled, I get the following message:
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/blog/ Raised
by: main_site_app.views.PostDetail
From what I can observe, there is nothing additional that the index page has that the blog doesn't. Is there a step I'm missing here that is preventing the /blog/ page from showing up?
EDIT:
views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views import generic
from .models import Post
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index_2.html'
class PostListLimited(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')[:2]
template_name = 'index_2.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'

Trying to trace a circular import error in Django Python

I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
The issue started when I added a new app which has a urls.py like the following:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'login/$',
auth_views.LoginView.as_view(template_name='accounts/login.html'),
name='login'),
url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'),
url(r'signup/$',views.SignUp.as_view(), name='signup'),
]
My project urls.py has a line which points to the app and looks like the following code:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^test/$', views.TestPage.as_view(), name='test'),
url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks')
]
My application's view looks like the following:
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
My project's view looks like:
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'test.html'
class ThanksPage(TemplateView):
template_name = 'thanks.html'
class HomePage(TemplateView):
template_name = 'index.html'
Can anyone please help me identify where I could possibly be going wrong.
You are importing auth.urls twice. Remove url(r'^accounts/', include('django.contrib.auth.urls')) from your project's urls.py
I am importing wrong URL configuration, instead of 'reverse' I should import 'reverse_lazy',
change
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
to
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'

CreateView weird behaviour. Goes to the wrong view?

In my urls.py I have a ListView and a CreateView. When I have both the views in the urls patterns, the CreateView shows the html linked to the ListView. But when I remove the ListView from the url patterns, then the CreateView shows the correct html.
urls.py
If I have it like this, CreateView shows ListView html
urlpatterns = [
path("", views.TopicListView.as_view(), name="topic"),
path("<topic>/", views.PostListView.as_view(), name="post"),
path("create/", views.CreatePostView.as_view(), name="create_post")
]
This way, the CreateView behaves like I want it to. Shows the correct HTML
urlpatterns = [
path("", views.TopicListView.as_view(), name="topic"),
path("create/", views.CreatePostView.as_view(), name="create_post")
]
views.py
class PostListView(ListView):
model = models.ForumPost
template_name = "forum/post_list.html"
def get_context_data(self):
context = super().get_context_data()
return context
def get_queryset(self):
query_set = super().get_queryset()
return query_set
class CreatePostView(CreateView):
model = models.ForumPost
fields = ("title", "description")
template_name = "forum/create_post.html"
The reason as urls are checking one by one from up to down. So when you have 3 urls:
urlpatterns = [
path("", views.TopicListView.as_view(), name="topic"),
path("<topic>/", views.PostListView.as_view(), name="post"),
path("create/", views.CreatePostView.as_view(), name="create_post")
]
And try to use create/ it actually matches <topic>/ pattern as a string were passed. So what I recommend is to place it to very down:
urlpatterns = [
path("", views.TopicListView.as_view(), name="topic"),
path("create/", views.CreatePostView.as_view(), name="create_post")
path("<topic>/", views.PostListView.as_view(), name="post"),
]
But also it would be better if you add some additional path to urls in order it won't be double-minded like list/<topic>/.

Categories