'compare between 2 codes in django

I want to add (add comment form) but I face a problem in views.py you will see codes down below. in views.py there are 2 different codes 1- that code works for me 2- that code didn't work with me and I want to know why code num 2 didn't work with me

# in models.py

class Comment(models.Model):
    user = models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE)
    product = models.ForeignKey(Product, verbose_name="Product", on_delete=models.CASCADE, related_name="comments")
    is_active = models.BooleanField(verbose_name="Is Active?",default=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated Date")
    content = models.TextField(verbose_name="comment")
# in forms.py
class AddComment(forms.ModelForm):
    content = forms.CharField(label='التعليق', widget = forms.TextInput(attrs={'class': 'form-control', 'placeholder':'ما رأيك في المنتج؟'}))

    class Meta:
        model = Comment
        fields = ['content',]

and

# in urls.py
    path('product/<slug:slug>/', views.detail, name="product-detail"),

and

# in details.html
{% if request.user.is_authenticated %}
   <form action="" method="post">
     {% csrf_token %}
     {{AddComment}}
     <br>
     <input type="submit" value="إرسال">
   </form>
{% endif %}

now my problem in views.py

# in views.py
def detail(request, slug):
    product = get_object_or_404(Product, slug=slug)
    related_products = Product.objects.exclude(id=product.id).filter(is_active=True, category=product.category)
    comment = Comment.objects.filter(is_active=True,product=product)

    # start add comment system

    # that code work for me
    form = AddComment()
    if request.method == 'POST':
        content = request.POST.get('content', '')
        user = request.user
        c = Comment.objects.create(product= product, user= user, content=content, created_at = datetime.now(), updated_at = datetime.now(), is_active=True)
    # that code didn't work for me
    # if request.method == 'POST':
    #     form = AddComment(request.POST)
    #     if form.is_valid():
    #         user = request.user
    #         content = form.cleaned_data['content']

    #         c = Comment( product= product, user= user, content=content,created_at = datetime.now(),updated_at = datetime.now() ,is_active=True)
    #         c .save()
        return redirect('#/' , slug=slug)
    # end add comment system     

    context = {
        'product': product,
        'related_products': related_products,
        'comment': comment,
        'AddComment':form,

    }
    return render(request, 'store/detail.html', context)```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source