我正在学习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'硬编码。完成此操作后,它显然只能重定向到那个配方。
目前我正在从评论模式的下拉菜单中选择我要评论的食谱,这也是不理想的。
非常感谢任何帮助!
答案 0 :(得分:0)
您的评论需要引用他们所链接的食谱。我假设您的Comment
模型有ForeignKey
到Recipe
?
因此,您的CommentCreateView
需要获得额外的属性,即pk
的{{1}}。看来您的Recipe
已经拥有该密钥,该密钥会传递给您的kwargs
。因此,在CommentCreateView
中,您只需覆盖:
CommentView
并且不要在班级定义def get_success_url(self):
recipe = Recipe.objects.get(pk=self.kwargs.get('pk'))
return recipe.get_absolute_url()
。