我不知道如何将评论链接到特定的产品(对象)。也许这和鼻涕虫有关。
附注:所有的评论都可以成功上传到数据库,但问题只是将它们与一个产品链接
views.py
class ProductDetail(DetailView):
model = Product
template_name = 'store/product-single.html'
context_object_name = 'product'
def get_context_data(self, **kwargs):
context = super().get_context_data()
products = Product.objects.all()[:4]
context['products'] = products
product = Product.objects.get(slug=self.kwargs['slug'])
context['title'] = product.title
context['comment_form'] = CommentForm()
context['comments'] = Comment.objects.all()
return context
def save_comment(request):
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
# comment.product = Product.objects.filter()
comment.save()
return redirect('index')
urls.py
path('save_comment/', save_comment, name='save_comment')
product-single.html
<div class="container">
<form action="{% url 'save_comment' %}" method="POST">
{% csrf_token %}
{{ comment_form.as_p }}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
</div>
models.py
class Comment(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
user = models.CharField(default='', max_length=255)
text = models.TextField(default='')
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['user', 'text']
widgets = {
'user': forms.TextInput(),
'text': forms.Textarea()
}
1条答案
按热度按时间umuewwlo1#
将其添加到URL中,因此:
在路径中,我们包含
product_pk
:我们在提交表单时在URL中包含以下内容: