Django forms with Foreign keys

≡放荡痞女 提交于 2020-08-24 08:28:08

问题


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

回答1:


if you are creating a form for Prices, try putting this in your model form:

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



回答2:


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.



来源:https://stackoverflow.com/questions/21575078/django-forms-with-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!