带有外键的Django表单 [英] Django forms with Foreign keys
问题描述
我有一个用户可以拥有多本书的场景。我可以为用户和书籍创建两个不同的模型,并使用外键关联它们(或者一对多是正确的方法?)。
我已经为用户模型创建了一个django表单,但是当我在模板中这样做 {{form.as_p}} 时,只会显示用户模型字段,而不会显示book字段。
I have scenario in which a user can have multiple books. I can create two different models for user and books and relate them using foreign keys (or one-to-many will be right way ?). I have created a django forms for User model but when i do like this {{form.as_p}} in templates only user model fields is shown not books field.
我也希望该带有我的图书模型归档的用户字段(像书名字段一样多,因为他可以拥有多本图书,所以再显示一次),请让我知道可以使用Django表单/模型,或者我必须使用带有jQuery的简单html表单,然后将数据保存在模型中。
I want that with user fields my books model filed also displayed (like book names field more then once because he can have multiple books) , Please let me know if it is possible using django forms/models or I have to user simple html forms with jquery and then save data in models.
谢谢
编辑:
我的模型:
my models :
class Product(models.Model):
categories = models.CharField(max_length=5, choices = settings.CATEGORIES)
name = models.CharField(max_length=100)
description = models.TextField()
currency = models.CharField(max_length=5, choices = settings.CURRENCY)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.name
class Prices(models.Model):
products = models.ForeignKey(Product)
prices = models.IntegerField()
def __unicode__(self):
return self.id
推荐答案
价格表格,请尝试将其放入模型表格中:
if you are creating a form for Prices, try putting this in your model form:
products = forms.ModelMultipleChoiceField(queryset=Product.objects.all())
这篇关于带有外键的Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!