我对每篇文章都有评论,我希望用户只需输入他们的评论并在同一页面上提交“IndexView”
这是我的views.py
def IndexView(request):
if request.user.is_authenticated():
base_template_name = 'blog/base.html'
else:
base_template_name = 'blog/visitor.html'
form = CommentForm()
posts = Post.objects.all()
return render(request, 'blog/index.html', {'form':form,'posts':posts,'base_template_name':base_template_name})
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
context = {'form':form}
return render(request,'blog/index.html', context)
else:
form = CommentForm()
return render(request, 'blog/index.html', {'form': form})
在index.html
我把它(它显示的字段放不能提交):
<form enctype="multipart/form-data" method="post" class="post-form">
{% csrf_token %}
{{ form.textc }}
<button type="submit" class="save btn btn-default">Send</button>
</form>
以下是CommentForm
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('textc',)
urls.py
和index
comment
url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),
url(r'^$', views.IndexView, name = 'index'),
[编辑]:这是我的models.py
class Post(models.Model):
user = models.ForeignKey(User, null=True)
title = models.CharField(max_length=200)
image = models.CharField(max_length=1000, blank=True)
#slug = models.SlugField(max_length=255, null=True, blank=True)
text = tinymce_models.HTMLField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def get_absolute_url (self):
return reverse('blog:index')
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.Post', null=True,related_name='comments')
user = models.ForeignKey(User, max_length=200, blank=True, null=True)
textc = models.TextField(null=True,max_length=200)
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
非常感谢你们!
答案 0 :(得分:0)
那是因为在IndexView
视图中(一个好的命名约定是使用snake_case,当它是一个函数 - index_view
时 - 和CamelCase当它是一个类 - IndexView
),您没有处理POST
数据。由于您未在action
内定义任何<form>
属性,因此此表单将发布到同一网址(相同视图)。
把它放在IndexView
视图中:
def IndexView(request):
form = CommentForm()
if request.user.is_authenticated():
base_template_name = 'blog/base.html'
else:
base_template_name = 'blog/visitor.html'
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
# handle here the form.cleaned_data.get('textc')
# and then redirect, if necessary
posts = Post.objects.all()
return render(request, 'blog/index.html', {'form': form, 'posts': posts, 'base_template_name': base_template_name})