写我的第一个"真实" django项目我意识到我的观点非常巨大。我尝试将其转换为CBV(作为额外的django训练)。以下是我的fbv观点:
def index(request):
context = {}
categories = Category.objects.select_related()
subcategories = SubCategory.objects.all()
context['categories'] = categories
context['subcategories'] = subcategories
return render(request, 'mainapp/index.html', context)
def category(request, category_name_slug):
context = {}
try:
category = Category.objects.get(slug=category_name_slug)
subcategory = SubCategory.objects.filter(category=category)
context['subcategories'] = subcategory
context['category'] = category
except Category.DoesNotExist:
raise Http404("Category doesn't exist")
return render(request, 'mainapp/category.html', context)
def subcategory(request, category_name_slug, subcategory_name_slug):
context = {}
form = SiteAddForm(initial={'url': 'http://'})
context['form'] = form
try:
category = Category.objects.get(slug=category_name_slug)
subcategory = SubCategory.objects.filter(category=category
).get(slug=subcategory_name_slug)
sites = Site.objects.filter(subcategory=subcategory, is_active=True)
context['subcategory'] = subcategory
context['category'] = category
context['sites'] = sites
except (SubCategory.DoesNotExist, Category.DoesNotExist):
raise Http404("Nie ma takiej strony")
if request.method == 'POST':
form = SiteAddForm(request.POST)
if form.is_valid():
siteurl = form.cleaned_data['url']
context['siteurl'] = siteurl
try:
page = AddNewSite(siteurl)
except:
print('ERRROR')
context['Error'] = "URL is not responding"
return render(request, 'mainapp/subcategory.html', context)
title = page.title()
description = page.description()
keywords = page.keywords()
if page.check_url_in_database():
context['Error'] = "Site already in database"
return render(request, 'mainapp/subcategory.html', context)
else:
form_extended = SiteAddFormFull(initial={'url': siteurl, 'name':
title, 'description':
description, 'keywords':
keywords})
context['form_extended'] = form_extended
if request.method == 'POST':
form_extended = SiteAddFormFull(request.POST)
if form_extended.is_valid():
keywords = form_extended.cleaned_data['keywords']
name = form_extended.cleaned_data['name']
description = form_extended.cleaned_data['description']
page.add_site(category, subcategory, keywords,
description, name, siteurl)
context['added_site'] = 'Thank you - site was added'
messages.add_message(request, messages.SUCCESS, 'Dodano!!')
return render(request, 'mainapp/subcategory.html', context)
如何使用CBV简化编写基本视图(索引)。看起来应该是这样的: 类别: SUB1 分公司2 类别2: Sub2a Sub2b
我应该学习CBV还是继续使用FBV(它有效)?以下是我的类别,子类别模型:
class Category(models.Model):
name = models.CharField(max_length=30, unique=True,
verbose_name='Category name')
slug = models.SlugField()
image = models.ImageField(upload_to='category_images',
verbose_name="Category image",
blank=True)
description = models.TextField(default='Description',
verbose_name="Category description")
class Meta:
verbose_name_plural = "Categories"
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def image_thumb(self):
if self.image:
return '<img src="/media/%s" width="40" height="40" />' % (self.image)
else:
return('')
image_thumb.short_description = 'Thumb'
image_thumb.allow_tags = True
def __str__(self):
return self.name
class SubCategory(models.Model):
category = models.ForeignKey(
'Category',
related_name='subcategory',
on_delete=models.CASCADE,
blank=True,
null=True,
)
name = models.CharField(max_length=30)
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(SubCategory, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = "Subcategories"
def __str__(self):
return self.name
答案 0 :(得分:1)
我是CBV的拥护者,在尝试重用代码时,它可以让生活变得更轻松。还有大量预定义的通用视图,大多数情况下只需要进行小的调整。对于您的示例索引,您可以使用TemplateView:
class IndexView(TemplateView):
template_name = "mainapp/index.html"
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.select_related()
context['subcategories'] = SubCategory.objects.all()
return context