U
U
unixwz2017-07-21 17:54:20
Django
unixwz, 2017-07-21 17:54:20

What is the correct way to link two model forms in Django?

Hello, I am learning django and I need to do the following: I have two models Seller and Goods, they are linked using ForeignKey, here is the code:

class Seller(models.Model):
    title = models.CharField('Название магазина', max_length=255)
    url = models.URLField('Ссылка на магазин')
    internal_url = models.CharField('Внутренняя ссылка', max_length=255)
    description = models.TextField('Описание', max_length=5000)
    rate = models.IntegerField('Рейтинг', default=0)
    publish_date = models.DateField('Дата добавления', auto_now_add=True)
    display = models.BooleanField('Отображение на главной', default=False)
    email = models.EmailField('E-Mail администратора', default='')


class Goods(models.Model):
    seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
    name = models.CharField('Что вы продаёте?',  max_length=255)

Everything is great, there is a Seller model - a seller and a Goods model - these are the goods of the seller (for each seller there can be as many as you like).
I need to make a form on the site (not in the admin panel), to add a seller, for this I generate a form using ModelForm, with this code I generate a form:
class SellerForm(ModelForm):
    class Meta:
        model = Seller
        fields = ['title', 'url', 'description', 'email']


class GoodsForm(ModelForm):
    class Meta:
        model = Goods
        fields = ['name']

Or rather, one form is generated, but it includes input fields for Seller and an input field (name) for Goods. I'm having difficulty in how do I properly implement this form? As I understand it, I need to somehow connect these two forms, because the models are interconnected, it is probably possible to connect the forms for these models, so that in the form adding a seller there would be a field for entering goods (products are filled in the form of a hash tag, like on Toster i.e. at the output we have an array of strings - goods) and then I need to add these goods to the database, each product separately.
How is it correct and most convenient to implement?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom Belousov, 2017-07-23
@unixwz

Since these are just tags, it can be implemented using the django-taggit battery. Instead of the Goods model, add a TaggableManager to the Seller, and add a TagField from the same library to the form.
PS
Here is a small manual ilnurgi1.ru/docs/django/contrib/django-taggit.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question