Создайте ModelForm
для Comment
в файле forms.py
внутри приложения:
# your_app/forms.py
from django import forms
from .models import Comment
class CommentModelForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['post', 'text']
widgets = {
'post': forms.HiddenInput(),
'text': forms.Textarea(attrs={'placeholder': 'Write your comment here...'}),
}
После этого отредактируйте представление PostDetail
, чтобы вы могли передать CommentModelForm
с помощью post
экземпляр уже установлен в виде:
class PostDetail(DetailView):
model = Post
def get_context_data(self, **kwargs):
data = super(PostDetail, self).get_context_data(**kwargs)
vc = self.object.view_count
self.object.view_count = F('view_count') + 1
self.object.save()
self.object.view_count = vc + 1
initial_comment_data = {
'post': self.object,
}
data['comment_form'] = CommentModelForm(initial=initial_comment_data)
return data
Добавьте CommentModelForm
к вам CommentCreate
view:
class CommentCreate(LoginRequiredMixin,CreateView):
model = Comment
form_class = CommentModelForm
def form_valid(self,form):
form.instance.author = self.request.user
return super().form_valid(form)
И, наконец, шаблон вашего PostDetail
долженвыглядеть так:
# your_app/templates/your_app/post_detail.html
...
<form method="POST" action="{% url 'yourapp:comment-create' %}">
{% csrf_token %}
{{ comment_form }}
<button type="submit">Place a comment</button>
</form>
<div>
{% for comment in post.comments.all %}
<p>{{ comment.text }} - by {{ comment.author }} at {{ comment.created_date }}</p>
{% empty %}
<p>No comments yet. Be the first one!</p>
{% endfor %}
</div>