Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 210
Inforian Avatar asked Oct 01 '22 16:10

Inforian


1 Answers

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

products = forms.ModelMultipleChoiceField(queryset=Product.objects.all())
like image 197
Daniel Qiu Avatar answered Oct 13 '22 10:10

Daniel Qiu