Сравнение двух кодов в django

Я хочу добавить (добавить форму комментария), но столкнулся с проблемой в views.py Вы увидите коды ниже. В файле views.py есть 2 разных кода 1- этот код работает у меня 2- этот код не работает у меня и я хочу знать, почему код номер 2 не сработал со мной

# 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',]

и

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

и

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

теперь моя проблема в 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':
        if form.is_valid():
        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)```
Вернуться на верх