Django Forms with Foreign Keys

I have a scenario in which a user can have multiple books. I can create two different models for users and books and bind them using foreign keys (or will one-to-many be the right way?). I created django forms for the User model, but when I like this {{form.as_p}} , only the user model fields are displayed in the templates, not the book fields.

I want my user model with files to also be displayed with user fields (for example, the book name field more than once because it can have multiple books). Please let me know if possible using django forms / models, or should I just user an html form with jquery and then save the 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
+4
source share
2 answers

if you are creating a form for a price, try putting it in your model form:

products = forms.ModelMultipleChoiceField(queryset=Product.objects.all())
+4
source

I think you should add the required fields to the metaclass, e.g.

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

Please pay attention to the workflow for using foreign keys in the form of a model here .

0
source

Source: https://habr.com/ru/post/1525395/


All Articles