Answer the question
In order to leave comments, you need to log in
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)
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']
Answer the question
In order to leave comments, you need to log in
Keep learning actively. By the time you've read the Django documentation in its entirety, there should be no more questions.
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
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},
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question