I'm having trouble with adding comments to class based views, forms.py:
(我在向基于类的视图forms.py添加注释时遇到麻烦:)
class RequestForm(ModelForm):
class Meta:
model = Request
exclude = ('slug',)
class RequestCommentForm(ModelForm):
class Meta:
model = RequestComment
fields = ['body' ]
models.py:
(models.py:)
class Request(models.Model):
title = models.CharField(max_length=250 )
date = models.DateTimeField('Request date', default=timezone.now, editable=False )
department = models.CharField(max_length=2, choices=DEPARTMENT)
support_request = models.TextField('Request', max_length=2500, blank=True)
owner = models.ForeignKey(User,)
slug = models.SlugField(blank=True, editable=False)
def __unicode__(self):
return self.title
views.py:
(views.py:)
class RequestDetailView(ModelFormMixin, DetailView):
model = Request
form_class = RequestCommentForm
def get_success_url(self):
return reverse('request-detail', kwargs={'pk': self.object.pk})
def get_context_data(self, **kwargs):
context = super(RequestDetailView, self).get_context_data(**kwargs)
context['form'] = self.get_form()
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.request = Request.objects.get(pk=self.object.pk)
form.instance.created = timezone.now
form.save()
Also tried this part with:
self.object = form.save(commit=False)
self.object.author = self.request.user
self.object.request = Request.objects.get(pk=self.object.pk)
self.object.created = timezone.now
self.object.save()
return super(RequestDetailView, self).form_valid(form)
template: request_detail.html comments section .....
(模板:request_detail.html评论部分.....)
{% load bootstrap %}
<form action="{% url 'request-detail' object.id %}" method="post"> {% csrf_token %}
<ul class="form-group">
{{ form|bootstrap }}
</ul>
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
.....
(.....)
Page renders correctly, but when I submit, no-go with saving comment.
(页面正确呈现,但是当我提交时,保存评论无法进行。)
Debug toolbar shows that sql queries are updating the request model, instead of request comment.
(调试工具栏显示sql查询正在更新请求模型,而不是请求注释。)
Can't figure out how to add simple comment form from different model to detail page.
(无法弄清楚如何从不同的模型向详细信息页面添加简单的注释表单。)
Any help would be appreciated. (任何帮助,将不胜感激。)
Also, if there is more elegant way off adding comments form to class based view, would love to see it.
(另外,如果有更优雅的方法可以将注释表单添加到基于类的视图中,则希望看到它。)
My google-fu didn't help me to find anything. (我的Google Fu没帮助我找到任何东西。)
ask by Max translate from so