如何呈现这个Django表单?

2024-04-27 03:19:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表单,用户检查他们是否拥有某个特定品牌的商品。选中此框后,选中项下会显示一个文本框,以进行产品审阅。你知道吗

我的models.py看起来像:

class Brand(models.Model):
    owned_brand = BooleanField(default=False)
    brand_name = models.CharField(max_length=300)

class Product(models.Model):        
    brand = models.ForeignKey(Brand, unique=True)
    #Other fields that we'll ignore for this exercise go here...
    product_review = models.CharField(max_length=300)

我想要这样的伪代码:

for each brand in Brand.entry.all():
    display form for that brand

在Django我该怎么做?你知道吗


Tags: 用户表单formodelthatmodelslengthmax
1条回答
网友
1楼 · 发布于 2024-04-27 03:19:38

首先,我不明白你为什么有一把独一无二的外国钥匙。foreignkey的理念是建立多人关系(每个品牌可以有多个产品)。但是,出于某种原因,您添加了unique=True,这实际上迫使它成为一种OneToOne关系。现在,您可以使用功能的原因是,引用docs

Conceptually, this [one-to-one relationship] is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object.

但是,我不认为这就是你要找的,好像你确实想要一个普通的外键,所以去掉unique=True。你知道吗

如果我没听错的话,现在我们来谈谈手头的问题,你想把某个品牌的每种产品的所有表格都拿出来。我不完全明白你想让这些发生在哪里,所以我把它写成了一个视图函数:

def get_formes(request, brand_pk):
    products = Brand.objects.get(pk=brand_pk).product_set.all()
    forms = [ProductForm(instance=p) for p in products]

    return render_to_response('whateva.html', {'forms': forms})

假设您使用的是模型表单。如果不是,可以使用initial告诉表单从每个产品获取哪些数据(例如ProductForm(initial={'name':p.name})等等)。然后在模板中执行以下操作:

{% for form in forms %}
    <form>
    {{ form.as_p }}
    </form>
{% endfor %}

最后,我强烈建议您更改字段名。为什么brand需要一个名为brand\u name的字段?这已经是一张品牌表了,型号就叫品牌,光叫名字不是更有意义吗?同样的道理也适用于自有品牌,应该是自有品牌,产品审查应该是审查

相关问题 更多 >