My model.py:
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.urls import reverse
from django.utils.text import slugify
# Create your models here.
class Stocks(models.Model):
title = models.ForeignKey('Product', verbose_name="Ürün", on_delete=models.CASCADE)
stock = models.DecimalField(max_digits=3,decimal_places=0,default=0,verbose_name="Stok")
seller = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
price = models.DecimalField(max_digits=100,decimal_places=2,default=0.00,verbose_name="Fiyat")
def __str__(self):
return str(self.title)
class Meta:
verbose_name = "Stok"
verbose_name_plural = "Stoklar"
def upload_image_location(instance, filename):
return "%s/%s" %(instance.id, filename)
class Product(models.Model):
title = models.CharField(max_length=100,verbose_name="Başlık")
slug = models.SlugField(blank=True, unique=True)
category = models.ForeignKey('Category', null=True, blank=True, verbose_name="Kategori",on_delete=models.CASCADE)
description = models.TextField(null=True,blank=True,verbose_name="Ürün Açıklaması")
price = models.DecimalField(max_digits=100,decimal_places=2,default=0.00,verbose_name="Fiyat")
sale_price = models.DecimalField(max_digits=100,decimal_places=2,default=0.00,null=True,blank=True,verbose_name="İndirimli Fiyat")
tax = models.DecimalField(max_digits=3,default=18,decimal_places=0,verbose_name="KDV")
status = models.BooleanField(default=True,verbose_name="Aktif/Pasif")
image1 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Vitrin Fotoğrafı")
image2 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Galeri Fotoğrafı 1")
image3 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Galeri Fotoğrafı 2")
image4 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Galeri Fotoğrafı 3")
image5 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Galeri Fotoğrafı 4")
def get_absolute_url(self):
view_name = "detail_slug"
return reverse(view_name, kwargs={"slug": self.slug})
def __str__(self):
return self.title
class Meta:
verbose_name = 'Ürün'
verbose_name_plural = 'Ürünler'
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Product.objects.filter(slug=slug)
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def product_pre_save_reciever(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(product_pre_save_reciever, sender=Product)
My views.py
class ProductDetailView(LoginRequiredMixin, MultiSlugMixin, DetailView):
model = Product
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
product_name = self.object.title
data = Stocks.objects.filter(title__icontains=product_name).order_by('price')
context['stocks'] = data
return context
urls.py
from django.urls import path
from products import views
from products.views import (
CategoryCreateView,
CategoryUpdateView,
ProductCreateView,
ProductListView,
ProductDetailView,
ProductUpdateView,
)
urlpatterns = [
path('urunler/', ProductListView.as_view(), name='list'),
path('urunler/ekle/', ProductCreateView.as_view(), name='create'),
path('urunler/duzenle/<int:pk>/', ProductUpdateView.as_view(), name='update'),
path('urunler/duzenle/<slug>/', ProductUpdateView.as_view(), name='update_slug'),
path('urunler/<int:pk>/', ProductDetailView.as_view(), name='detail'),
path('urunler/<slug>/', ProductDetailView.as_view(), name='detail_slug'),
path('kategori/ekle/', CategoryCreateView.as_view(), name='add_category'),
path('kategori/duzenle/<int:pk>/', CategoryUpdateView.as_view(), name='update_category'),
path('kategori/duzenle/<slug>/', CategoryUpdateView.as_view(), name='update_slug_category'),
]
I'm trying to show related Stocks records on product detail page.
When I visit product detail page I get this error."Related Field got invalid lookup: icontains"
domain.com:8000/urunler/16 (for example)
I need to correct ProductDetailView class and get_context_data function but how :)
Any help?
You've called your fields strange names, which is confusing you. title is not a title, but a ForeignKey to the Product model, which itself has a title attribute.
This would work:
data = Stocks.objects.filter(title__title__icontains=product_name).order_by('price')
but really you should rename that field to something sensible, eg product, so that you would do product__title__icontains.
Related
I have problem with Django model get_absolute_url reverse methods.
I have a url pattern that works perfectly but the problem for example
when I visit example.com/blog/python/first-post the path works perfectly, but
when I try a random path like, example.com/blog/python-randomr9353/first-post
it still works correctly even though it shouldn't because, python-randomr9353 is not
a valid path and it should return a page not found error.
Here is my code.
Models
class ArticleSeries(models.Model):
title = models.CharField(max_length=200)
series_slug = AutoSlugField(populate_from='title')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:article_list', kwargs={'series_slug': self.series_slug})
class Tag(models.Model):
title = models.CharField(max_length=50)
def __str__(self):
return self.title
class Article(models.Model):
title = models.CharField(max_length=200)
article_slug = AutoSlugField(populate_from='title')
tag = models.ManyToManyField(Tag, default=1, verbose_name='Tag')
series = models.ForeignKey(ArticleSeries, default=1, verbose_name='Series', on_delete=models.SET_DEFAULT)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:article_detail', args=(self.series.series_slug, self.article_slug))
url patterns
app_name = 'blog'
urlpatterns = [
path('', views.IndexView.as_view(), name='index_view'),
path('blog', views.BlogView.as_view(), name='blog_view'),
path('blog/<slug:series_slug>', views.ArticleListView.as_view(), name='article_list'),
path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail'),
]
Views
class IndexView(TemplateView):
template_name = 'blog/index.html'
extra_context = {}
class BlogView(ListView):
model = ArticleSeries
template_name = 'blog/blog_view.html'
context_object_name = 'series_list'
def get_queryset(self):
series = ArticleSeries.objects.all()
return get_list_or_404(series)
class ArticleListView(ListView):
model = Article
template_name = 'blog/article_list.html'
context_object_name = 'article_list'
def get_queryset(self):
slug = self.kwargs['series_slug']
articles = Article.objects.filter(series__series_slug=slug)
return get_list_or_404(articles)
class ArticleDetailView(DetailView):
model = Article
template_name = 'blog/article_detail.html'
context_object_name = 'article'
slug_field = 'article_slug'
slug_url_kwarg = 'article_slug'
def get_object(self, queryset=None):
slug = self.kwargs.get('article_slug')
return get_object_or_404(Article, article_slug=slug)
Try using path('blog/python/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail') in the urls.py instead of path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail').
EDIT:
At the point where you obtain the value of series_slug, validate this there itself.
...
validSeries = ['python', 'c', 'cpp', 'js'] # etc
if series_slug not in validSeries:
# Raise a page not found error
I designed a database for my django ecommerce project but it have some problems, the goal of
the this design is to have products with different specifications for example a mobile cell has it's own properties and a television too,
it is my models.py:
'''
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from django.shortcuts import reverse
from model_utils import FieldTracker
from . import uploaders
class Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,
related_name='children')
slug = models.SlugField(max_length=75, unique=True)
tracker = FieldTracker(fields=['name'])
class MPTTMeta:
order_insertion_by = ['name']
def __str__(self):
category_names = [self.name]
node = self
while node.parent:
node = node.parent
category_names.append(node.name)
return ' / '.join(category_names[::-1])
def get_absolute_url(self):
return reverse('product_by_category', args=(self.slug,))
class ProductType(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class ProductSpecifications(models.Model):
name = models.CharField(max_length=50)
product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE,
related_name='specifications')
class Meta:
unique_together = ('name', 'product_type')
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100, unique=True)
product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE,
related_name='products')
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name='products')
price = models.PositiveBigIntegerField()
discount_price = models.PositiveBigIntegerField(null=True, blank=True)
description = models.TextField(null=True, blank=True)
image = models.ImageField(upload_to=uploaders.product_img_uploader)
slug = models.SlugField(max_length=150, unique=True)
tracker = FieldTracker(fields=['slug', 'name', 'product_type'])
def __str__(self):
return self.name
def set_discount(self, percentage):
self.discount_price = self.price * (1 - percentage)
self.save()
#property
def is_discounted(self):
return bool(self.discount_price)
def remove_discount(self):
self.discount_price = None
self.save()
class ProductSpecificationValue(models.Model):
specification = models.ForeignKey(ProductSpecifications, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE,
related_name='specifications')
value = models.CharField(max_length=75, null=True, blank=True)
def __str__(self):
return ''
class Meta:
unique_together = ('specification', 'product')
'''
And admin.py:
'''
from django.contrib import admin
from django.http import HttpResponseRedirect
from mptt.admin import MPTTModelAdmin
from .models import *
from .forms import ProductSpecForm
#admin.register(Category)
class CategoryAdmin(MPTTModelAdmin):
readonly_fields = ('slug',)
class SpecificationInline(admin.TabularInline):
model = ProductSpecifications
extra = 2
#admin.register(ProductType)
class ProductTypeAdmin(admin.ModelAdmin):
inlines = (SpecificationInline,)
class SpecificationValueInline(admin.TabularInline):
model = ProductSpecificationValue
# form = ProductSpecForm
# fields = ('specification', 'value')
# readonly_fields = ('specification',)
#
# def has_add_permission(self, request, obj):
# return False
#
# def has_delete_permission(self, request, obj=None):
# return False
#admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
inlines = (SpecificationValueInline,)
readonly_fields = ('slug',)
# def response_post_save_add(self, request, obj):
# return HttpResponseRedirect(
# reverse("admin:%s_%s_change" % (self.model._meta.app_label,
# self.model._meta.model_name), args=(obj.id,)))
'''
the problem is in product admin panel when you want to add or change a product, I want the select box for specification in SpecificationValueInline form show me only specifications related to the product type not all specifications in db, the lines that I commented in admin.py with some signals and a form was my approach to solve this issue i dont know if it was the best help me please!
signals.py:
'''
from django.dispatch import receiver
from django.db.models.signals import pre_save, post_save
from .models import Category, Product, ProductSpecificationValue, ProductSpecifications
#receiver(pre_save, sender=Product)
#receiver(pre_save, sender=Category)
def initialize_slug(sender, instance, *args, **kwargs):
if (not instance.slug) or (instance.tracker.has_changed('name')):
instance.slug = instance.name.replace(' ', '_')
#receiver(post_save, sender=Product)
def initialize_specifications(sender, instance, created, **kwargs):
if created:
product_type = instance.product_type
for specification in product_type.specifications.all():
ProductSpecificationValue.objects.create(product=instance,
specification=specification)
elif instance.tracker.has_changed('product_type'):
ProductSpecificationValue.objects.filter(product=instance).delete()
product_type = instance.product_type
for specification in product_type.specifications.all():
ProductSpecificationValue.objects.create(product=instance,
specification=specification)
#receiver(post_save, sender=ProductSpecifications)
def add_new_specs_to_related_products(sender, instance, created, **kwargs):
if created:
product_type = instance.product_type
for product in product_type.products.all():
ProductSpecificationValue.objects.create(specification=instance,
product=product)
'''
forms.py:
'''
from django import forms
from django.forms import ModelChoiceField
from .models import ProductSpecificationValue, Product
class ProductSpecForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if hasattr(self.instance, 'product'):
self.fields['specification'] = ModelChoiceField(
queryset=self.instance.product.product_type.specifications.all())
class Meta:
model = ProductSpecificationValue
fields = ('specification', 'value')
'''
you can use formfield_for_foreignkey in SpecificationValueInline
class SpecificationValueInline(admin.TabularInline):
model = ProductSpecificationValue
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "specification":
product_id = request.resolver_match.kwargs.get('object_id')
productType = Product.objects.get(id = product_id).product_type
kwargs["queryset"] = ProductSpecification.objects.filter(product_type=productType)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
mohsen ma answer was usefull I made some changes and it got better but I still doubt it it is enough or best practice, if user changes the product type he/she should stay on change page to fill the specification idk how:
'''
#receiver(post_save, sender=Product)
def sync_specs_with_type(sender, instance, created, **kwargs):
if created or instance.tracker.has_changed('product_type'):
if not created:
instance.specifications.all().delete()
for spec in instance.product_type.specifications.all():
ProductSpecificationValue.objects.create(product=instance, specification=spec)
class SpecificationValueInline(admin.TabularInline):
model = ProductSpecificationValue
extra = 0
def formfield_for_foreignkey(self, db_field, request, **kwargs):
product_id = request.resolver_match.kwargs.get('object_id')
if product_id and db_field.name == "specification":
product_type = Product.objects.get(id=product_id).product_type
kwargs["queryset"] = ProductSpecifications.objects.filter(product_type=product_type)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
#admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
readonly_fields = ('slug',)
inlines = (SpecificationValueInline,)
def response_post_save_add(self, request, obj):
messages.add_message(request, messages.INFO, 'set you product specifications')
return HttpResponseRedirect(
reverse("admin:%s_%s_change" % (self.model._meta.app_label, self.model._meta.model_name), args=(obj.id,)))
def get_inlines(self, request, obj):
if obj:
return super().get_inlines(request, obj)
return ()
'''
I want to know how to make category page view using class based view I know how to make this in function based view by using get_object_or_404(category, slug=None) But I am confused how to do this it in class based views. I tried to google this but I am unable to find anything related to this in class view.
I know I could have used function based view but I have used class based view in whole project so I thought to use them here as well
my code
models.py
from django.db import models
from django.utils import timezone
from slugger import AutoSlugField
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Category(models.Model):
title = models.CharField(max_length= 60)
slug = AutoSlugField(populate_from='title')
parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
class Meta:
verbose_name_plural = 'categories'
def __unicode__(self):
return self.title
def __str__(self):
return self.title
def get_absolute_url(self, slug=None):
return reverse("posts-detail", kwargs={"slug": self.slug})
class Post(models.Model):
title = models.CharField(max_length=120)
slug = AutoSlugField(populate_from='title')
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='postcategory')
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date_posted']
def __str__(self):
return self.title
def get_absolute_url(self, slug=None):
return reverse("posts-detail", kwargs={"slug": self.slug})
urls.py
from django.urls import path
from django.urls import path, include
from .views import PostView, PostDetailView,LatestPostView, CategoryPostListView
urlpatterns = [
path('', PostView.as_view(), name='posts-home'),
path('latest/', LatestPostView.as_view(), name='posts-latest'),
path('<slug>', PostDetailView.as_view(), name='posts-detail'),
path('category/<slug>', CategoryPostListView.as_view(), name='category-detail'),
]
views.py
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.shortcuts import redirect, render,get_object_or_404
#class based view
from django.views.generic import ListView, DetailView
from .models import Post, Category
class PostView(ListView):
template_name = 'posts/home.html'
model = Category
context_object_name = 'all_categs'
def get_queryset(self):
if self.request.user.is_authenticated:
return Category.objects.all()
else:
return Category.objects.all().exclude(title__iexact = 'Featured')[:6]
def get_context_data(self):
if not self.request.user.is_authenticated:
fcategory = Category.objects.get(title__iexact = 'Featured')
context = super(PostView, self).get_context_data()
context['latest_posts'] = Post.objects.exclude(category= fcategory).order_by('-date_posted')[0:6]
context['featured_posts'] = Post.objects.all().filter(category= fcategory).order_by('-date_posted')[0:6]
return context
else:
fcategory = Category.objects.get(title__iexact = 'Featured')
context = super(PostView, self).get_context_data()
context['latest_posts'] = Post.objects.order_by('-date_posted')
context['featured_posts'] = Post.objects.all().filter(category= fcategory).order_by('-date_posted')[0:6]
return context
# def get_success_url(self):
# return reverse('home') #add your path
class LatestPostView(LoginRequiredMixin, ListView):
template_name = 'posts/post_latest.html'
model = Post
context_object_name = 'Posts'
ordering = ['-date_posted']
paginate_by = 6
class PostDetailView(LoginRequiredMixin,DetailView):
model = Post
template_name = 'posts/post_detail.html'
class CategoryPostListView(LoginRequiredMixin, ListView):
model = Category
template_name = 'posts/category_detail.html'
# def get_queryset(self):
# category = get_object_or_404(Category, )
I thought of defining get_queryset inside CategoryPostListView. But I am not sure if it will work or not.
Firstly, if you are using ListView and want to display a list of posts, then you need model = Post.
Next, you can call get_object_or_404 in the get_queryset method. You can access slug from the URL with `self.kwargs['slug'].
Finally, you can filter the queryset to only return posts in that category.
class CategoryPostListView(LoginRequiredMixin, ListView):
model = Post
template_name = 'posts/category_detail.html'
def get_queryset(self):
category = get_object_or_404(Category, slug=self.kwargs['slug'])
return super(CategoryPostListView, self).get_queryset().filter(category=category)
Note that your problem is very similar to the dynamic filtering section in the docs.
Yes. you can use get_object_or_404 in class-based views. just add this to your CategoryPostListView:
class CategoryPostListView(LoginRequiredMixin, ListView):
model = Post
template_name = 'posts/category_detail.html'
def get_queryset(self):
category = get_object_or_404(Category, slug=self.kwargs['slug'])
# do another stuffs here
return Post.objects.filter(category=category)
for more information you can read dynamic filtering in class-based views in django official site
class PostForm(forms.ModelForm):
description = forms.CharField(widget=PagedownWidget(show_preview=False))
class Meta:
model = Post
fields = [
'title',
'image',
'video',
'description',
'public',
'tags',
]
I am trying to bypass the required field for 'video' but having difficulty doing so. Any suggestions would be appreciated.
this is my models.py, hopefully is should help with knowing how to go on this.
from django.db import models
from django.db.models import Count, QuerySet, F
from django.utils import timezone
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
from markdown_deux import markdown
from django.utils.safestring import mark_safe
from embed_video.fields import EmbedVideoField
from taggit.managers import TaggableManager
from comments.models import Comment
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 )
title = models.CharField(max_length=75)
slug = models.SlugField(unique=True)
video = EmbedVideoField()
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
description = models.TextField()
tags = TaggableManager()
public = models.BooleanField(default=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
class Meta:
ordering = ["-created", "-updated" ]
def get_markdown(self):
description = self.description
markdown_text = markdown(description)
return mark_safe(markdown_text)
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
from the docs it looks like it should support empty now since version 0.3, i would suggest trying
video = EmbedVideoField(null=True,blank=True)
the docs say it should function like a URL field, so just the standard notation should be all you need.
good luck!
I have a model using Django-MPTT that also has a field for using a specific template via the template_name_field. I'd like to be able to use a generic TemplateView, but pass in the mixin for using the template_name_field.
Here's the model:
from django.db import models
from mptt.models import MPTTModel
from mptt.fields import TreeForeignKey
class CategoryManager(models.Manager):
def get(self, **kwargs):
defaults = {}
defaults.update(kwargs)
if 'full_slug' in defaults:
if defaults['full_slug'] and defaults['full_slug'][-1] != "/":
defaults['full_slug'] += "/"
return super(CategoryManager, self).get(**defaults)
class Category(MPTTModel):
title = models.CharField(max_length=255)
description = models.TextField(blank=True, help_text='A brief description of the category. No HTML allowed.')
slug = models.SlugField(help_text='Prepopulates from title field.')
full_slug = models.CharField(max_length=255, blank=True)
template_name = models.CharField(max_length=70, blank=True, help_text="Example: 'categories/category_parent.html'. If this isn't provided, the system will use 'categories/category_detail.html'.")
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
objects = CategoryManager()
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
def save(self, *args, **kwargs):
orig_full_slug = self.full_slug
if self.parent:
self.full_slug = "%s%s/" % (self.parent.full_slug, self.slug)
else:
self.full_slug = "%s/" % self.slug
obj = super(Category, self).save(*args, **kwargs)
if orig_full_slug != self.full_slug:
for child in self.get_children():
child.save()
return obj
def __unicode__(self):
return "%s (%s)" % (self.title, self.full_slug)
Here's the view:
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView, DetailView
from django.views.generic.detail import SingleObjectTemplateResponseMixin
from django.utils.translation import ugettext as _
from django.contrib.syndication.views import Feed
from storefront.categories.models import Category
class SimpleCategoryView(TemplateView):
def get_category(self):
return Category.objects.get(full_slug=self.kwargs['full_slug'])
def get_context_data(self, **kwargs):
context = super(SimpleCategoryView, self).get_context_data(**kwargs)
context["category"] = self.get_category()
return context
And here's my URLS:
from django.conf.urls.defaults import patterns, include, url
from storefront.categories.models import Category
from storefront.categories.views import CategoryView
urlpatterns = patterns('',
url(r'^(?P<full_slug>[-\w/]+)', SimpleCategoryView.as_view(template_name='categories/category_detail.html'), name='category_view'),
),
How would I go about adding the mixin for using the template_name_field to my view?
You don't need a separate mixin. TemplateView already has the TemplateResponseMixin, so you can simply override get_template_names in your SimpleCategoryView subclass.
class SimpleCategoryView(TemplateView):
...
def get_template_names(self):
return [self.get_category().template_name]
DetailView should have everything you need. You just need to tell DetailView.get_template_names() which field can contain a template name using the template_name_field attribute. Below is a full view definition that gets the Category based on the slug in the url. Note that the Category will be available in the template as both object and category.
class SimpleCategoryView(DetailView):
model = Category
slug_url_kwarg = 'full_slug'
slug_field = 'full_slug'
template_name_field = 'template_name'