我不知道如何将 comments 链接到特定的产品(对象).也许这与鼻涕虫有关.

附注:所有 comments 都可以成功上传到数据库,但问题只是将它们链接到一个产品

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

推荐答案

您将其添加到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>

Django相关问答推荐

Django在保存时更新m2m对象

一次请求中更新整个Django模型

Django通用列表视图与多查询搜索

使用OuterRef过滤器获取Django记录的最大值

UpdateView 不会对 from 属性进行数据绑定

如何将数据(具体归档)从views.py 传递到models.py

如何将 select_related 应用于 Django 中的 m2m 关系的对象?

使用django提交后如何保留html表单数据?

在 django HTML 邮箱模板中使用字体

Django ORM:获取每个类别的月平均价格

Django - 使用在 URL 中传递的父类主键从子类中过滤对象

Django 表单有 Select 但也有自由文本选项?

什么时候在 django rest 框架序列化程序中调用创建和更新?

为什么 django 1.7 会为字段 Select 的变化创建迁移?

在 Django 中获取下一个和上一个对象

获取 Django 表单中的错误列表

如何在 Django 和 django-jsonfield 中将 JSONField 的默认值设置为空列表?

将 jQuery 脚本添加到 Django 管理界面

想要在 Django 测试中禁用信号

如何更改 django 模板中布尔值的打印方式?