Django:不能把我的评论和一个特定的产品联系起来

6yjfywim  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(85)

我不知道如何将评论链接到特定的产品(对象)。也许这和鼻涕虫有关。
附注:所有的评论都可以成功上传到数据库,但问题只是将它们与一个产品链接

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

umuewwlo1#

将其添加到URL中,因此:

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')

在路径中,我们包含product_pk

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

我们在提交表单时在URL中包含以下内容:

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

相关问题