简体   繁体   中英

Django forms with Foreign keys

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.

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.

Thanks

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

如果您要为价格创建表单,请尝试将其放入模型表单中:

products = forms.ModelMultipleChoiceField(queryset=Product.objects.all())

I think you should add required fields in meta class such as

class ThreadForm(ModelForm):
    class Meta:
        model = Thread
        fields = ('Books', 'User')

Please understand the work flow to use foreign keys in model form here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM