[英]Django Create Comment View pass Subject pk
我正在學習 Django,並且一直在努力使評論表單正常工作。 基本上我正在構建的是一個食譜應用程序。 這只是練習,但想法是有人發布食譜,其他人可以對其發表評論。 我已經基本正常工作,但我無法弄清楚如何在提交評論后讓重定向返回到配方詳細信息視圖。
如果我在 pk 中硬編碼它可以工作,我只需要掌握那個 pk!
這是我的東西:
Portion of Recipes views.py:
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView, View
from django.views.generic.detail import SingleObjectMixin
from django.core.urlresolvers import reverse_lazy
#from comments.models import Comment
from .models import Recipe
from comments.models import Comment
from .forms import RecipeCreateForm
from comments.forms import CommentFormTrial
from comments.views import CommentCreateView
class PersonalRecipeListView(LoginRequiredMixin,ListView):
def get_queryset(self):
return Recipe.objects.filter(owner=self.request.user)
class RecipeDetailView(View):
def get(self, request, *args, **kwargs):
view = RecipeContent.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = CommentCreateView.as_view()
return view(request, *args, **kwargs)
class RecipeContent(DetailView):
model = Recipe
template_name = 'recipes/recipe_detail.html'
context_object_name = 'recipe_data'
def get_context_data(self, *args, **kwargs):
context = super(RecipeContent, self).get_context_data(*args, **kwargs)
print('-------------------')
print(self.kwargs.get('pk'))
qs= Comment.objects.filter(recipe=self.kwargs.get('pk'))
context['comments'] = qs
comment_form = CommentFormTrial
context['comment_form'] = comment_form
return context
我的評論 view.py:
from django.shortcuts import render, get_object_or_404
from .models import Comment
from django.http import HttpResponseForbidden
from django.views.generic import ListView, CreateView
from django.core.urlresolvers import reverse_lazy
from .forms import CommentFormTrial
# Create your views here.
class CommentListView(ListView):
model = Comment
context_object_name = 'comments'
template_name='comments/testcomment.html'
class CommentCreateView(CreateView):
model = Comment
form_class = CommentFormTrial
success_url = reverse_lazy('recipes:recipe-detail', kwargs = {'pk':10})
def form_valid(self, form):
form.instance.owner = self.request.user
return super(CommentCreateView, self).form_valid(form)
您可以看到我在 success_url 中為 PK 硬編碼為“10”。 完成后,它可以工作,但顯然只會重定向到那個食譜。
目前,我正在從評論模式的下拉菜單中選擇我想評論的食譜,這也不理想。
非常感謝任何幫助!
您的評論需要引用它們所鏈接的食譜。 我假設您的Comment
模型有一個ForeignKey
to Recipe
?
所以你的CommentCreateView
需要接收一個額外的屬性,它是Recipe
的pk
。 看起來您的kwargs
已經擁有該密鑰,該密鑰已傳遞給您的CommentCreateView
。 所以在你的CommentView
,你只需要覆蓋:
def get_success_url(self):
recipe = Recipe.objects.get(pk=self.kwargs.get('pk'))
return recipe.get_absolute_url()
並且不要在類級別定義success_url
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.