![](/img/trans.png)
[英]Django: how can I save objects to the database using FormView and ajax?
[英]How can I implement FormView into DetailView, django
我使用基於Django的視圖。 我有一個顯示對象(DetailView)的類,現在我想將表單添加到同一頁面,就像在DetailView中一樣。
我的views.py:
class CommentFormView(FormView):
form_class = AddCommentForm
success_url = '/'
class BlogFullPostView(CommentFormView, DetailView):
model = Post
template_name = 'full_post.html'
pk_url_kwarg = 'post_id'
context_object_name = 'post'
def get_context_data(self, **kwargs):
context = super(BlogFullPostView, self).get_context_data(**kwargs)
context['comments'] = Comment.objects.filter(post=self.object)
return context
也許您了解-BlogFullPostView-顯示頁面,我想在其中添加表單。 CommentFormView-查看評論。
我的表格:
class AddCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content',)
widgets = {
'content': forms.TextInput(attrs={
'class': 'form-control'
})
}
labels = {
'content': 'Content'
}
def __init__(self, *args, **kwargs):
super(AddCommentForm, self).__init__(*args, **kwargs)
因此,在模板中,我嘗試添加表單:
<form method="post" action="" role="form">
{{ form }}
</form>
它不顯示任何內容:(
我該怎么辦?
我不會嘗試在單個視圖中混合兩個用例的邏輯。
class BlogFullPostView(DetailView):
model = Post
template_name = 'full_post.html'
pk_url_kwarg = 'post_id'
context_object_name = 'post'
def get_context_data(self, **kwargs):
context = super(BlogFullPostView, self).get_context_data(**kwargs)
context['comments'] = Comment.objects.filter(post=self.object)
context['form'] = AddCommentForm(initial={'post': self.object })
return context
class CommentFormView(FormView):
form_class = AddCommentForm
def get_success_url(self):
# logic here for post url
# full_post.html
<form method="post" action="{% url "comment_form_view_url" %}">
{{ form }}
</form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.