djangodjango-comments

Django: cant relate my comment to a specific product


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()
        }

Solution

  • 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>