R
R
Razer15112020-10-16 19:57:42
Django
Razer1511, 2020-10-16 19:57:42

Creating a form from two models in Django?

Hello. I'm starting to actively learn Django. I ran into a problem and couldn't find an answer. How to create a form from two related models in Django?

models.py

class ClassName(models.Model):
    class_number = models.PositiveSmallIntegerField('Класс')
    class_name = models.CharField('Буква', max_length=1)

class Student(models.Model):
    classes = models.OneToOneField(ClassName, on_delete=models.CASCADE, primary_key=True)
    first_name = models.CharField('Имя', max_length=30)
    last_name = models.CharField('Фамилия', max_length=30)
    email = models.EmailField('Электронная почта')
    password = models.CharField('Пароль', max_length=30)


forms.py
class Registration(ModelForm):
    class Meta:
        model = Student
        fields = ['first_name', 'last_name', 'email', 'password']

class Classes(ModelForm):
    class Meta:
        model = ClassName
        fields = ['class_number', 'class_name']


The question seems to be simple. What to write in the views.py file ( validation and collaboration ) ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2020-10-16
@sergey-gornostaev

Keep learning actively. By the time you've read the Django documentation in its entirety, there should be no more questions.

I
IDzone-x, 2020-10-17
@IDzone-x

Well, in the book "Django2 by Examples" there was something similar, you can search. Somewhere from page 110 :)
PS if you want I can throw it off

N
Nikita, 2020-10-20
@buslay

You can slightly modify FormView from django.views.generic.edit, and in View inherit from the new class.
The main idea is to process (create a context, do validation) for an arbitrary number of forms in one view:
An example of using views.py:

class CompanyCreatePrivateView(MultiFormCreate):
    template_name = 'company/company_create_private.html'
    formconf = {
        'company': {'formclass': CompanyCreatePrivateForm},
        'person': {'formclass': PersonCompanyCreateForm},
        'phone': {'formclass': PhoneNumberMaskedCreateForm},
        'companycontact': {'formclass': CompanyContactForm},
    }

In the template, the context of each form will not be in form, but in forms.{form name}
If the creation of the objects of the next form depends on the creation of the object of the previous one, the view will have to override the forms_valid () method and save the objects "manually".
PS I didn't post the finished mixin MultiFormCreate, a lot of text..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question