1

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()
        }
Shaxriyor
  • 11
  • 3
  • since there is no any product field in the comment form and your `save_comment` method does not add product to the comment created. I am surprised how does product is assigned to the comment posted? – Kiran Parajuli Jun 10 '23 at 17:11
  • through product(foreign key); – Shaxriyor Jun 10 '23 at 17:14
  • You mean at the models definition? that's only a table column declaration. As long as the foreign key allows `null` value, comments are allowed to be created without any product. – Kiran Parajuli Jun 10 '23 at 17:17

1 Answers1

1

You add it to the url, so:

from django.views.decorators.http import require_POST


@require_POST
def save_comment(request, product_pk):
    form = CommentForm(request.POST, request.FILES)
    if form.is_valid():
        form.instance.product_id = product_pk
        comment = form.save()
        comment.save()
        return redirect('index')

In the path, we include the product_pk:

path('<int:product_pk>/save_comment/', save_comment, name='save_comment'),

and we include this in the URL when we submit the form:

<div class="container">
  <form action="{% url 'save_comment' product.pk %}" method="POST">
    {% csrf_token %}
    {{ comment_form.as_p }}

    <button type="submit" class="btn btn-primary  btn-lg">Submit</button>
  </form>
</div>
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555