I'm new to CBV. Not sure why this isn't working...
views.py
class ItemDetailView(DetailView):
'''display an individual item'''
model = Item
template_name = 'boutique/item.html'
context_object_name = 'item'
# With model specified, following code would be redundant, wouldn't it?? However...
# def get_object(self):
# return get_object_or_404(Item, pk=self.kwargs.get('item_pk'))
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# add categories for navbar link texts
context['categories'] = Category.objects.all()
print('\ncontext= ', context, '\n')
return context
AttributeError at /item_8/ Generic detail view ItemDetailView must be called with either an object pk or a slug in the URLconf.
And the context isn't being printed out.
If I add get_object to the code, it's working fine:
class ItemDetailView(DetailView):
'''display an individual item'''
# model = Item
template_name = 'boutique/item.html'
# context_object_name = 'item'
def get_object(self):
return get_object_or_404(Item, pk=self.kwargs.get('item_pk'))
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# add categories for navbar link texts
context['categories'] = Category.objects.all()
print('\ncontext= ', context, '\n')
return context
However, if I changed get_object function to:
def get_object(self):
obj = super().get_object()
obj = get_object_or_404(Item, pk=self.kwargs.get('item_pk'))
# obj = obj.filter(pk=self.kwargs.get('item_pk')) # doesn't work, same error
# obj = obj.get(pk=self.kwargs.get('item_pk')) # doesn't work, same error
return obj
ImproperlyConfigured at /item_8/ ItemDetailView is missing a QuerySet. Define ItemDetailView.model, ItemDetailView.queryset, or override ItemDetailView.get_queryset().
I'm confused... DetailView should work without having to define get_object at all no??
additional files:
url.py
app_name = 'boutique'
urlpatterns = [
# show index page
path('', views.IndexView.as_view(), name='index'),
# show a specific item
path('item_<int:item_pk>/', views.ItemDetailView.as_view(), name='item'),
# show categories of products for men or women
path('<slug:gender>/', views.CategoryListView.as_view(), name='show-all'),
# show a specific category for men or women
path('<slug:gender>/cat_<int:category_pk>/', views.CategoryListView.as_view(), name='category'),
# show a specific subcategory under a specific category for men or women
path('<slug:gender>/cat_<int:category_pk>/subcat_<int:subcategory_pk>/', views.CategoryListView.as_view(), name='subcategory'),
]
models.py
class Item(models.Model):
'''Each item represents a product'''
category = models.ForeignKey(Category, on_delete=models.CASCADE)
subcategory = models.ForeignKey(
SubCategory, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
price = models.IntegerField(default='0')
discount = models.IntegerField(null=True, blank=True)
uploaded_date = models.DateTimeField(
auto_now_add=True, null=True, blank=True)
class Meta:
ordering = ['-uploaded_date']
def __str__(self):
return self.name
def discounted_price(self):
'''to calculate the price after discount'''
return int(self.price * (100 - self.discount) * 0.01)
def get_item_url(self):
return reverse('boutique:item', kwargs={'item_pk': self.pk})
item.html
<!-- display each item in its own box -->
<div class="col-6 col-md-4 col-lg-3 px-1 px-sm-2 d-flex flex-column">
<!-- image anchor -->
<a href="{{ item.get_item_url }}">
<img class="rounded-sm" src="{{item.itemimage_set.first.image.url}}" width="100%"
alt=""></a>
<!-- /image anchor -->
<!-- item price tag -->
<div class="text-left p-1 mt-auto" style="font-size: 16px;">
<div class="font-weight-light pt-2">
{{item}}
</div>
<div class="font-weight-lighter">
{% if item.discount %}
<p>
<strike class="text-muted">₽ {{item.price}}</strike>
<b class="text-danger">₽ {{item.discounted_price}}</b>
<small class="text-danger">(-{{item.discount}}%)</small>
</p>
{% else %}
<p>₽ {{item.price}}</p>
{% endif %}
</div>
</div>
<!-- /item price tag -->
</div>
Your first example is correct, you don't need to define get_object() explicitly but you should use pk argument instead of item_pk in url path when using details CBV:
path('item_<int:pk>/', views.ItemDetailView.as_view(), name='item'),
Since by default get_object() method using self.kwargs["pk"] to search object.
If you still want to use item_pk you need to specify in in view using pk_url_kwarg:
class ItemDetailView(DetailView):
pk_url_kwarg = 'item_pk'
From docs:
The URLconf here uses the named group pk - this name is the default
name that DetailView uses to find the value of the primary key used to
filter the queryset.
If you want to call the group something else, you can set pk_url_kwarg
on the view. More details can be found in the reference for DetailView
Related
Accessing primary keys in Django class based view
Let's start from the beginning. I have 2 models, Recipe, and Ingredient. They look like this.
In models.py
class Recipe(models.Model):
name=models.CharField(max_length=20, help_text='Enter the name of this recipe')
description=models.TextField(max_length=75, help_text='Describe your recipe')
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('recipe-detail', kwargs={'pk': self.pk`})
class Ingredient(models.Model):
recipe=models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient=models.CharField(max_length=100)
class Meta:
ordering = ['ingredient']
def __str__(self):
return self.ingredient
What I want to be able to do is have a detail view, where I can access the Recipe attributes, like the name and description, as well as, be able to loop through the ingredients. This is what I have working so far:
In views.py
def recipe_detail_view(request, pk):
recipe = get_object_or_404(Recipe, pk=pk)
context = {
'recipe': recipe,
'ingredients': Ingredient.objects.filter(recipe=pk)
}
return render(request, 'recipes/recipe_detail.html', context=context)
In urls.py
# ...
path('recipes/<str:pk>', views.recipe_detail_view, name='recipe-detail')
# ...
In template
<h1 class="title is-1">{{ recipe.name }}</h1>
<p>{{ recipe.description }}</p>
<h3 class="title">Ingredients</h3>
{% for ingredient in ingredients %}
<h4 class="">{{ ingredient.ingredient.title }}</h3>
{% endfor %}
I am wondering how I could turn this into a class based view however. More specifically, I am wondering how I can access and pass in the primary key to the filter like so:
class RecipeDetailView(generic.DetailView):
model = Recipe
template_name = 'recipes/recipe_detail.html'
context_object_name='recipe'
extra_context = {
'ingredients': Ingredient.objects.filter(recipe=pk),
}
Can anyone help?
You can use get_context_data and get_object to get the data you want to your template.
class RecipeDetailView(generic.DetailView):
model = Recipe
template_name = 'recipes/recipe_detail.html'
context_object_name='recipe'
def get_context_data(self, **kwargs)
ctx = super().get_context_data(**kwargs)
ctx['ingredients'] = Ingredient.objects.filter(recipe=self.get_object().pk)
return ctx
I am adding a search field in my blog so people can put the name of the blog they want to read and a list of items come up and after clicking on any of the list items, it will redirect to the detail view. However, in my case,If I put anything in search, it is not redirecting to a detail view but going to http://127.0.0.1:8000/home/search/2 instead of http://127.0.0.1:8000/home/list/2/.
I have posted my models, views, URLs and template files below.
Is there any reverse method I need to use here to redirect and what changes I need in my template file?
models.py
from django.db import models
class Category(models.Model):
cat_name = models.CharField(max_length = 256, blank = True)
def __str__(self):
return self.cat_name
class Blog(models.Model):
name = models.CharField(max_length = 256, blank = True)
pub_date = models.DateTimeField('date published')
text = models.TextField(blank = True)
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name='categories', verbose_name = 'blog_categories')
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from homepage.models import Blog
from django.views.generic import TemplateView, ListView, DetailView
from homepage import models
from django.db.models import Q
class Home(TemplateView):
template_name = 'homepage/index.html'
class BlogListView(ListView):
context_object_name = 'blogs'
model = models.Blog
template_name = 'homepage/blog_list.html'
class BlogDetailView(DetailView):
context_object_name = 'blogs_detail'
model = models.Blog
template_name = 'homepage/blog_detail.html'
def get_queryset(self):
query = self.request.GET.get('q')
return Blog.objects.filter(
Q(name__icontains = query) | Q(name__icontains = query) )
class SearchResultsListView(ListView):
model = Blog
context_object_name = 'blog_list'
template_name = 'homepage/search_result_list.html'
def get_queryset(self):
query = self.request.GET.get('q')
return Blog.objects.filter(
Q(name__icontains = query) | Q(name__icontains = query) )
urls.py
from django.urls import path
from homepage import views
from homepage.views import SearchResultsListView
app_name = 'homepage'
urlpatterns = [
path('', views.Home.as_view(), name = 'index'),
path('list/', views.BlogListView.as_view(), name = 'blog-list'),
path('list/<int:pk>/', views.BlogDetailView.as_view(), name = 'blog-list'),
path('search/', SearchResultsListView.as_view(), name = 'search_result'),
]
index.html
<div class="grid-item-1">
<h1>G</h1>
<input type="button" name="" value="Back to Home" placeholder="">
<form action="{% url 'home:search_result' %}" method = 'get'>
<input type="text" name="q" placeholder="search">
</form>
</div>
search_result_list.html
{% for blog in blog_list %}
<ul>
<li>
{{blog.name}}
{{blog.address}}
here
</li>
</ul>
{% endfor %}
the URL redirects to http://127.0.0.1:8000/home/search/2 and its a 404 page.
how can I redirect it to the detail view page http://127.0.0.1:8000/home/list/1/ and see the detail of the list pulled by search result.
The reason this happens is because {{ blog.id }} just contains a number, for example 2. It will be appended to the URL. You can fix this by prepending the URL with a slash (/) and write list with:
{{blog.name}}
{{blog.address}}
here
But it is likely better to make use of the {% url … %} template tag [Django-doc]:
{{blog.name}}
{{blog.address}}
here
In your BlogDetailView, there is no q parameter, so you can remove the get_queryset:
class BlogDetailView(DetailView):
context_object_name = 'blogs_detail'
model = models.Blog
template_name = 'homepage/blog_detail.html'
# no get_queryset
Furthermore perhaps you should consider renaming the DetailView from blog-list, to blog-detail, or something similar.
I have a list of departments I want to be shown in a select drop-down but its not shown?
It's a duty-log app and want the user to be able to select the department from the drop-down.
Here's my views.py
def index(request): # the index view
logs = Dutylog.objects.all() # querying all logs with the object manager
departments = Department.objects.all() # getting all departments with object manager
if request.method == "POST": # checking if the request method is a POST
if "taskAdd" in request.POST: # checking if there is a request to add a logo
title = request.POST["description"] # title
date = str(request.POST["date"]) # date
department = request.POST["department_select"] # department
content = title + " -- " + date + " " + department # content
Log = Dutylog(title=title, content=content, due_date=date, department=Department.objects.get(name=department))
Log.save() # saving the log
return redirect("/") # reloading the page
if "taskDelete" in request.POST: # checking if there is a request to delete a log
checkedlist = request.POST["checkedbox"] # checked logs to be deleted
for log_id in checkedlist:
Log = Dutylog.objects.get(id=int(log_id)) # getting log id
Log.delete() # deleting logo
return render(request, "index.html", {"logs": logs, "department": departments})
Here's my models.py
class Department(models.Model): # The Category table name that inherits models.Model
name = models.CharField(max_length=100) # Like a varchar
class Meta:
verbose_name = ("Department")
verbose_name_plural = ("Departments")
def __str__(self):
return self.name # name to be shown when called
class Dutylog(models.Model): # Dutylog able name that inherits models.Model
title = models.CharField(max_length=250) # a varchar
content = models.TextField(blank=True) # a text field
created = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) # a date
due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) # a date
department = models.ForeignKey(Department, default="general", on_delete=models.PROTECT) # a foreignkey
class Meta:
ordering = ["-created"] # ordering by the created field
def __str__(self):
return self.title # name to be shown when called
and the html template
<div class="inputContainer half last">
<i class="fa fa-caret-down selectArrow"></i>
<select id="department" class="taskCategory" name="department_select">
<option class="disabled" value="">Choose a Department</option>
{% for department in departments %}
<option class="" value="{{ department.name }}" name="{{ department.name }}">{{ department.name }}</option>
{% endfor %}
</select>
<label for="department">Department</label>
</div>
You are passing department as a key in your dictionary but you are iterating with departments in your template
so change this
return render(request, "index.html", {"logs": logs, "department": departments
to
return render(request, "index.html", {"logs": logs, "departments": departments
I have followed the guidelines from This answer in order to pass Parent pk to the child creation page. At the moment though it is not working and I am seeing the following log.
[14/Jul/2017 13:15:37] "POST /catalog/productstatus/2/create/ HTTP/1.1" 200 4001
I'm not sure what I'm doing wrong, here is the code I currently have.
Models
Models.py
class Product(models.Model):
serial_number = models.CharField(unique=True, max_length=15)
class ProductStatus(models.Model):
serial_number = models.ForeignKey('Product', on_delete=models.CASCADE, null=True)
status = models.CharField(max_length=20, blank=True, default='Stock', help_text='Products status')
date = models.DateTimeField(auto_now_add=True)
View
class ProductStatusCreate(CreateView):
model = ProductStatus
template_name = 'catalog/productstatus_create.html'
form_class = ProductStatusModelForm
def form_valid(self, form):
productstatus = form.save(commit=False)
product_id = form.data['product_id']
product = get_object_or_404(Product, id=product_id)
productstatus.product = product
return super(ProductStatusCreate, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(ProductStatusCreate, self).get_context_data(**kwargs)
context['s_id'] = self.kwargs['product_id']
return context
def get_success_url(self):
if 'product_id' in self.kwargs:
product = self.kwargs['product_id']
else:
product = self.object.product.pk
return reverse_lazy('product_detail', kwargs={'pk': product})
Forms
class ProductStatusModelForm(forms.ModelForm):
class Meta:
model = ProductStatus
fields = ['status',]
def __init__(self, *args, **kwargs):
self.fields["product"] = forms.CharField(widget=forms.HiddenInput())
super(ProductStatusModelForm, self).__init__( *args, **kwargs)
templates/myapp/product_detail.html
New
urls.py
urlpatterns += [
url(r'^productstatus/(?P<product_id>\d+)/create/$', views.ProductStatusCreate.as_view(), name='productstatus_create'),
]
productstatus_create.html
{% extends "base_generic.html" %}
{% block content %}
<h2>New Product Status</h2>
</br>
<form action="" method="post">
{% csrf_token %}
<table>
<input type=hidden id="id_product" name="product" value="{{ s_id }}">
{{ form }}
</table>
<input type="submit" value="Submit" />
</form>
</br>
{% endblock %}
When looking at the page's source the value does get populated but when I submit the form nothing happens.
Why do you have views.ProductInstanceCreate.as_view() in your urls.py but the view you show is called ProductStatusCreate? Are you sure you are using the right view?
You are creating a 'product' hidden field in your form, but not providing a value for it anywhere. Your template output then has two product fields, and the latter (blank) is taken, so returns an error saying it is required.
None of this outputting the product ID to the template in order to read it back in is necessary - you always have the ID available to you in the URL kwargs.
You can get rid of your get_context_data, and the extra field code in the Form and template. Your form_valid can be something like:
def form_valid(self, form):
product = get_object_or_404(Product, id=self.kwargs['product_id'])
form.instance.product = product
return super().form_valid(form)
And product_id will always be in self.kwargs, so your get_success_url can be shorter too:
def get_success_url(self):
product = self.kwargs['product_id']
return reverse('product_detail', kwargs={'pk': product})
Update #4:
The for loop in slider.html is currently not pulling content after the last update. Slider.html was randomized; however, I'm getting four of the same story and the urls are not going to their appropriate detailed view page anymore.
List.html has been fixed and is now random.
slider.html - This section is still wonky, (updated - 4:19 p.m.)
{% for random_article in random_articles %}
<div class="slider">
<div class="group visible">
<div class="sliderItem">
<img src="{{random_article.relatedImage}}" alt="" class="sliderPicture">
<p class="related">{{random_article.title}}</p>
</div><!-- /.sliderItem -->
</div><!-- /.group -->
</div><!-- /.slider -->
{% endfor %}
Here is the URL error when I click to detailed view:
NoReverseMatch at /last-us
Reverse for 'detailed' with arguments '()' and keyword arguments '{u'slug': ''}' not found. 1 pattern(s) tried: ['(?P<slug>\\S+)']
New culprits (for why slider.html isn't working)
urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.BlogIndex.as_view(), name="list"),
url(r'^(?P<slug>\S+)', views.BlogDetail.as_view(), name="detailed"),
)
views.py (updated - 4:19 p.m.)
Added context['random_slider'] = FullArticle.objects.order_by('?')[:4] but I don't think this is the right approach. So that I can get four different articles vs. four of the same article randomized.
from django.views import generic
from . import models
from .models import FullArticle
# Create your views here.
class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"
def get_context_data(self, **kwargs):
context = super(BlogIndex, self).get_context_data(**kwargs)
context['random_article'] = FullArticle.objects.order_by('?').first()
return context
class BlogDetail(generic.DetailView):
model = models.FullArticle
template_name = "detailed.html"
def get_context_data(self, **kwargs):
context = super(BlogDetail, self).get_context_data(**kwargs)
context['object_list'] = models.FullArticle.objects.published()
return context
def get_context_data(self, **kwargs):
context = super(BlogDetail, self).get_context_data(**kwargs)
context['random_articles'] = FullArticle.objects.exclude(
pk=self.get_object().pk
).order_by('?')[:4]
return context
Original Problem
I'm using FullArticle.objects.order_by('?').first() to get a random article from my database, but it's currently giving the same article when I refresh the page. There is probably something missing from my models, view or how I'm calling it (using slice) in list.html or slider.html that is causing the problem.
The two parts I'm looking to make random on page load:
list.html (changed so that it's {{random_article.}} ) - This section of the problem is fixed.
<div class="mainContent clearfix">
<div class="wrapper">
<h1>Top 10 Video Games</h1>
{% for article in object_list|slice:":1" %}
<p class="date">{{article.pubDate|date:"l, F j, Y" }}</p> | <p class="author">{{article.author}}</p>
<img src="{{article.heroImage}}" alt="" class="mediumImage">
<p class="caption">{{article.body|truncatewords:"80"}}</p>
{% endfor %}
models.py
from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
class FullArticleQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class FullArticle(models.Model):
title = models.CharField(max_length=150)
author = models.CharField(max_length=150)
slug = models.SlugField(max_length=200, unique=True)
pubDate = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
category = models.CharField(max_length=150)
heroImage = models.CharField(max_length=250, blank=True)
relatedImage = models.CharField(max_length=250, blank=True)
body = models.TextField()
publish = models.BooleanField(default=True)
gameRank = models.CharField(max_length=150, blank=True, null=True)
objects = FullArticleQuerySet.as_manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("FullArticle_detailed", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog entry"
verbose_name_plural = "Blog Entries"
ordering = ["-pubDate"]
The problem is that you are setting the value of a class attribute at "compile time" and not each time the view is called. Instead, you could do:
class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"
def random_article(self):
return = FullArticle.objects.order_by('?').first()
Or:
class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"
def get_context_data(self, **kwargs):
context = super(BlogIndex, self).get_context_data(**kwargs)
context['random_article'] = FullArticle.objects.order_by('?').first()
return context
[update]
In list html, I only need one random article. In slider.html, I need four random articles, would I just tack on FullArticle.objects.order_by('?')[:4] somewhere in that def get_context_data snippet?
Yes. Make it plural in the view (don't forget to exclude the main article from the side list):
class BlogDetail(generic.DetailView):
model = models.FullArticle
template_name = "detailed.html"
def get_context_data(self, **kwargs):
context = super(BlogDetail, self).get_context_data(**kwargs)
context['random_articles'] = FullArticle.objects.exclude(
pk=self.get_object().pk
).order_by('?')[:4]
return context
At the template, do:
{% for random_article in random_articles %}
<div class="sliderItem">
<img src="{{random_article.relatedImage}}" alt="" class="sliderPicture">
<p class="related">{{random_article.title}}</p>
</div><!-- /.sliderItem -->
{% endfor %}
The generic listview just passes an object_list as context based on the queryset. In your case it means you have to either change the value of queryset in your view or override the get_context_data method and add your random item to it.
https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin.get_context_data