Django:使用网址给定的第二个参数

时间:2019-05-06 11:51:47

标签: python django django-models

我想创建一个Django网站,可以在其中上传带有季节和情节的系列。最后,它应该看起来像这样:

季节:

[1] [2] [3]

剧集:

[1] [2] [3] [4] [5] [6]  

情节属于URL给出的季节。

我的代码如下:

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)
    ...

views.py:

class SeriesDetailView(DetailView):
    model = Serie

    def get_context_data(self, **kwargs):
        context = super(SeriesDetailView, self).get_context_data(**kwargs)
        context.update({
            'seasons': Season.objects.all(),
            'episodes': Episode.objects.all()
        })
        return context

urls.py:

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

lib.html:

<a href="{% url 'serie-detail' serie.id 1 %}">

(1是因为我想要第一个赛季)

serie_detail.html:

<section class="section mt-5">
        <div class="container">
        <h1>{{ serie.title }}</h1>
        <img class="card-img-top mb-2" src="{{ serie.thumbnail.url }}" style="height: 319px; width: 220px;">
        <h6>Uploaded by: <h6 class="category text-warning"> {{serie.createdUser.username}}</h6></h6>
            <div class="row">
                <h4 class="mb-0">Seasons:</h4>
            </div>
            <div class="row">
            {% for season in serie.season_set.all %}
                <a href="" class="btn btn-default float-left">{{ season.order }}</a>
            {% endfor %}
            </div>
            <div class="row">
                <h4 class="mb-0">Episodes:</h3>
            </div>
            <div class="row">
            {% for season in serie.season_set.all %}
                {% for episode in season.episode_set.all %}
                    <a href="{% url 'episode-detail' episode.id %}" class="btn btn-default float-left btn-sm">{{ episode.order }}</a>
                {% endfor %}
            {% endfor %}
            </div>
        </div>
    </section>

使用上面的代码,结果如下:

季节:

[1] [2]  

剧集:

[1] [1] 

需要第二季的第一集,并显示出来。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我假设您只需要显示一个特定季节的所有季节情节(本例中为第1季)。您需要修改以下代码:

class SeriesDetailView(DetailView):
    model = Serie

    def get_context_data(self, **kwargs):
        order = kwargs.get("order")
        context = super(SeriesDetailView, self).get_context_data(**kwargs)
        context.update({
            'seasons': Season.objects.all(),
            'episodes': Episode.objects.filter(season=order)
        })
        return context