Django将属性从网址获取到过滤器

时间:2019-05-09 19:28:24

标签: python django django-urls

嗨,我是django的新手,我正在尝试制作一个提供有关季节和情节的系列节目的网站。

我成功创建了意甲的CreateView。现在,我将为该季节创建CreateView。它看起来应该像这样。

季节:
[1] [2] [3] [添加]

如果单击添加,它将显示带有该季节形式的模式。我的代码如下:

models.py

class Serie(models.Model):
    title = models.CharField(max_length=120)
    thumbnail = models.ImageField(upload_to=serie_dir_path)
    ...


class Season(models.Model):
    order = models.IntegerField()
    serie = models.ForeignKey(Serie, on_delete=models.CASCADE)
    ...

class Episode(models.Model):
    title = models.CharField(max_length=120)
    order = models.IntegerField()
    episode = models.FileField(upload_to=episode_dir_path)
    season = models.ForeignKey(Season, on_delete=models.CASCADE)

urls.py

urlpatterns = [
    path('library', LibListView.as_view(), name='library'),
    path('series/<int:pk>/season/<int:order>', SeriesDetailView.as_view(), name='serie-detail'),
]

views.py

class SeasonCreateView(LoginRequiredMixin, CreateView):
    model = Season
    fields = ['order']

    def get_context_data(self, **kwargs):
        context = super(SeasonCreateView, self).get_context_data(**kwargs)
        context.update({
            'serie': Serie.objects.filter()
        })
        return context

season_form.html

{% for season in serie.season_set.all %}
...
{% endfor %}

我该写些什么从URL获得意向的filter()中?

3 个答案:

答案 0 :(得分:1)

从网址获取参数:

parameter = request.GET.get("parameter_name")

过滤:

'serie': Serie.objects.filter(model_field_name=parameter)

答案 1 :(得分:0)

好吧,我自己弄的。我使用了get_object_or_404

def get_context_data(self, **kwargs):
    s = get_object_or_404(Serie, id=self.kwargs.get('pk'))
    context = super(SeasonCreateView, self).get_context_data(**kwargs)
    context.update({
        'serie': s
    })
    return context

答案 2 :(得分:-1)

{% for season in serie.season_set.all %}

<p>{season}</p>
{% endfor %}

请尝试使用 all()而不是 all 进行循环定义。