如何将ListView slug限制为Django中的多个选项?

时间:2014-10-01 06:19:05

标签: django listview

这是代码

models.py

class Submission(models.Model):

    CAR = 'car'
    TRUCK = 'truck'
    VAN = 'van'
    SUV = 'suv'
    CAR_TYPES = (
        (CAR, 'Car'),
        (TRUCK, 'Truck'),
        (VAN, 'Van'),
        (SUV, 'SUV'),
    )

    submission_type = models.CharField(_('Submission Type'), max_length=20, choices=MEDIA_TYPES, default=CAR)
    title = models.CharField(_('Title'),  max_length=100, blank=False)
    description = models.TextField(_('Description'))
    user = models.ForeignKey(User, related_name='user_submission')
    thumbnail = models.ImageField()
    date_submitted = models.DateTimeField(default=timezone.now)

views.py

class SubmissionCategoryList(ListView):
    model = Submission
    template_name = 'submission/submit_cat.html'

    def get_queryset(self):
        queryset = super(SubmissionCategoryList, self).get_queryset()
        return queryset.filter(submission_type=self.kwargs['slug']).order_by('-date_submitted')

    def get_context_data(self, **kwargs):
        context = super(SubmissionCategoryList, self).get_context_data(**kwargs)
        return context

urls.py

url(r'^(?P<slug>[\w-]+)/$', SubmissionCategoryList.as_view(), name='submit_category'),

代码工作正常。当我转到localhost:8000/car/时,它仅显示CARS submission_type等的列表视图。但是,当我输入的网址不是CAR_TYPES中选项的一部分时,例如,localhost:8000/boat/,django仍显示此视图的模板。我的问题是:我如何限制slug应该接受的选择数量?并且,如果它不是CAR_TYPES选项的一部分,我如何让它忽略此视图?

2 个答案:

答案 0 :(得分:0)

您是否尝试在视图中验证“slug”?

views.py
def get_queryset(self):
    if self.kwargs['slug'] is not None and self.kways['slug'].lower() in project.settings.CAR_TYPE:
        # return your queryset.filter ...
    else:
        # return other template or redirect to other views.

project.settings.py
CAR_TYPE = ['car', 'truck', 'van', 'suv']

或者,只需编辑url regex:

(?P<slug>car|truck|van|suv)

不是最好的方法,但绝对可以解决您的问题。

答案 1 :(得分:0)

好的,谢谢Anzel我找到了解决这个问题的好方法。我把它放在任何需要这个的人身上。

我创建了一个看起来像这样的reference.py文件。你可以随意调用它,我只是称它为引用,因为它就是它的作用。

from enum import Enum


class CarTypes(Enum):
    CAR = 'car'
    TRUCK = 'truck'
    VAN = 'van'
    SUV = 'suv'

我将models.py更改为导入reference.py 我将choices中的submission_type更改为choices=tuple([(auto.name, auto.value) for auto in CarTypes])

from .reference import CarTypes


class Submission(models.Model):

    submission_type = models.CharField(_('Submission Type'), max_length=20, choices=tuple([(auto.name, auto.value) for auto in CarTypes]), default=CarTypes.CAR)
    title = models.CharField(_('Title'),  max_length=100, blank=False)
    description = models.TextField(_('Description'))
    user = models.ForeignKey(User, related_name='user_submissions')
    thumbnail = models.ImageField()
    date_submitted = models.DateTimeField(default=timezone.now)

以下是类别

的最终工作views.py
from .reference import CarTypes


class SubmissionCategoryList(ListView):
    model = Submission
    template_name = 'submission/submit_cat.html'
    CAR_TYPES = [auto.value for auto in CarTypes]

    def get_queryset(self):
        if self.kwargs['slug'] in self.CAR_TYPES:
            queryset = super(SubmissionCategoryList, self).get_queryset()
            return queryset.filter(submission_type=self.kwargs['slug']).order_by('-date_submitted')
        else:
            return Http404

    def get_context_data(self, **kwargs):
        context = super(SubmissionCategoryList, self).get_context_data(**kwargs)
        context['submission_type'] = self.kwargs['slug']
        return context

您可以将同一个queryset放在DetailView中,当用户搜索site.com/car/2或类似内容时,它应该有用