I dont know how to link comments to specific product(object). Maybe there is something to do with slugs.
P.S. All the comments can be successfully uploaded to the database, but the problem is only with linking them with one product
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()
}