在这个视图中,我需要两个模型Book和UserFav,所以我为此使用了上下文:
class BookDetailView(LoginRequiredMixin, generic.DetailView):
model = Book
template_name = 'book_detail.html'
def get_context_data(self, **kwargs):
context = super(BookDetailView, self).get_context_data(**kwargs)
context.update({
'fav_list': UserFav.objects.filter(user=self.request.user)
})
return context
和另一个视图功能
def favorite(request, pk):
book = get_object_or_404(Book, pk=pk)
fav, created = UserFav.objects.get_or_create(user=request.user)
fav.favorites.add(book)
return render(request, 'book_detail.html', {'book': book})
收藏夹功能表
<form action="{% url 'favorite' book.id %}" method="post" style="display: inline;">
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-xs">
<span class="glyphicon glyphicon-remove"></span> add this book to favourite
</button>
我的网址
url(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
url(r'^book/(?P<pk>\d+)/f/$', views.favorite, name='favorite'),
我需要收藏夹的地方
{% if fav_list %}
{% for fav in fav_list %}
{% if book in fav.favorites.all %}Favorited
{% else %}
<form action="{% url 'favorite' book.id %}" method="post" style="display:inline;">
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-xs">
<span class="glyphicon glyphicon-remove"></span> add this book to favourite
</button>
</form>
{% endif %}
{% endfor %}
{% else %}
<form action="{% url 'favorite' book.id %}" method="post" style="display: inline;">
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-xs">
<span class="glyphicon glyphicon-remove"></span> add this book to favourite
</button>
</form>
{% endif %}
现在的问题是,当我重定向到book_detail.html时,没有得到模板所需的fav_list 如何正确重定向或使用其他方式定义视图?
答案 0 :(得分:0)
您没有从favorite
视图进行重定向。提交表单后,被认为是重定向的好习惯。
尝试
from django.shortcuts import redirect
from django.urls import reverse
def favorite(request, pk):
book = get_object_or_404(Book, pk=pk)
fav, created = UserFav.objects.get_or_create(user=request.user)
fav.favorites.add(book)
# if you have an app_name in urls.py file try this
# return redirect(reverse('YOUR_APP_NAME:book-detail', args=(pk,)))
return redirect(reverse('book-detail', args=(pk,)))
我希望这会有所帮助。