Django forms with Foreign keys

14,920

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

products = forms.ModelMultipleChoiceField(queryset=Product.objects.all())
Share:
14,920
Inforian
Author by

Inforian

Updated on June 07, 2022

Comments

  • Inforian
    Inforian almost 2 years

    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