[英]How to pass parameter in current url to an html template in Django 3
我有:
電影 Model
class Movie(models.Model):
title = models.CharField(max_length=255)
synopsis = models.TextField()
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('movie_detail', args=[str(self.id)])
討論 Model
class Discussion(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
movie = models.ForeignKey(
Movie,
on_delete=models.CASCADE,
related_name='discussion',
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('discussion_detail', args=[str(self.movie.id), str(self.id)])
討論列表視圖
class DiscussionListView(LoginRequiredMixin, ListView):
model = Discussion
template_name = 'discussion_list.html'
login_url = 'login'
我也有討論列表.html
這是我想要的:
/article/1/discussion/
中。 The integer 1
is a movie_pk
because the url is defined as /article/<int:movie_pk>/discussion/
which in this case refer to the priority key of a Movie Model, for example StarWars I. This is a page of list of discussion與這部電影相關的標題。 (這已經實現了) 但是:在 Discussion_list.html 中,我們需要/article/<int:movie_pk>/discussion/new
標簽{% url discussion_new %}
有一個參數,因為discussion_new
被定義為
因此:如何將movie_pk
從當前的url傳遞到 DiscussionListView,然后到模板discussion_list.html?
在詳細視圖的模板中,您可以發送object.id
作為 url 的參數:
#template
{% url "discussion_new" movie_pk=object.pk %}
如果您在列表視圖模板中,那么您可能通過所有 object_list 循環到 go。 在那里你可以像這樣實現:
{% for object in object_list %}
{% url "discussion_new" movie_pk=object.pk %}
{% endfor %}
{% url discussion_new %}
至
{% url "discussion_new" pk=movie_pk%}
並在列表中
{% for m in movie_list %}
{% url "discussion_new" movie_pk=m.pk %}
{% endfor %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.