【问题标题】:Django get data of object from ManyToManyField formDjango 从 ManyToManyField 表单中获取对象的数据
【发布时间】:2021-04-04 04:21:37
【问题描述】:

您好,我创建了这个表单:

class CartForm(ModelForm):
 class Meta:
     model = Cart
     fields =( 'products',)
    

来自这些模型:

class Product(models.Model):
 title = models.CharField("Titre", max_length=120)
 subtitle = models.CharField("Sous-titre", max_length=250)
 description = models.TextField("Description")
 picture = models.ImageField(upload_to='objects/')
 enabled = models.BooleanField("Activé")

class Cart(models.Model):
 products = models.ManyToManyField(Product)

我想在我的模板上显示一个包含他们数据的选择列表 所以我从视图发送表单,但我找不到任何方法来获取产品描述我只得到他们的名字!

这是我的看法:

def home(request):
 categories = Category.objects.annotate(test=Count('product')).filter(test__gt=0)
 # categories = Category.objects.order_by(
 #     'id')
 test = CartForm()
 return render(request, 'boutique.html', {"categories": categories, "test":test})

以及我在模板中尝试的内容:

    {% for ee in test.products %}
        {{ ee.description }}    
        <br />    
    {% endfor %}

请帮帮我 祝你有美好的一天

【问题讨论】:

  • 你能展示你的模板和视图吗?
  • @SLDem 是的,对不起,我刚刚更新了我的帖子
  • 我回答了,试试这个解决方案

标签: django django-models django-forms django-templates


【解决方案1】:

好的,这里有几个问题: 首先,您实际上需要定义提交表单时会发生什么,所以在您看来这样做:

views.py

def home(request):
 categories = Category.objects.annotate(test=Count('product')).filter(test__gt=0)
 if request.method == 'POST':
     test = CartForm(request.POST)
     if form.is_valid():
         cart = form.save(commit=False)
         for product in request.POST.getlist('products'):
             cart.add(product)
     else:
         pass
  else:
      form = CartForm()
 return render(request, 'boutique.html', {"categories": categories, "test": test})

然后在您的模板中,您实际上必须呈现表单(测试):

boutique.html

<form method="post">
    {% csrf_token %}
    {{ test.as_p }}
    <button type="submit"> Add Items </button>
</form>

现在您应该在模板中看到产品列表。

编辑

如果您想在表单中显示不同的模型字段,请重写其 __str__ 方法,如下所示:

def __str__(self):
    return self.description # to show description

【讨论】:

  • 感谢您的回答,显示表单不是问题,我想显示对象中的其他数据,如描述或字幕
  • 谢谢,但这只会改变字段的标题,我想获得多个数据,不仅仅是描述或标题,而是两个
  • 然后在方法中简单地做return str(self.title) + ' ' + str(self.description)
猜你喜欢
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-06-10
  • 2017-12-31
相关资源
最近更新 更多