Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django one form multiple tables

A form collects first name, email, password and grade.

Can I save this information in two tables using something like this?

 def save(self):
    new_user = User.objects.create_user(first=self.cleaned_data['first'], email=self.cleaned_data['email'], password=self.cleaned_data['password'])
    new_grade = Grade.objects.create_grade(grade=self.cleaned_data['grade'])
    return new_user, new_grade

Is this possible? What would be a better way of doing this?

like image 914
Eva611 Avatar asked Oct 26 '25 14:10

Eva611


1 Answers

It's absolutely possible and normal to do such a thing. A form doesn't have to resemble a model just because ModelForms do. Forms are simply a way of describing the input that is required for a particular use case. What you do with that data is entirely up to you. That includes saving it across a number of different models.

Note that it's not a requirement to return the new instances that you've created in a regular form. It is just convention. If you need access to the new instances after the save, then by all means, return them.

like image 120
Josh Smeaton Avatar answered Oct 29 '25 03:10

Josh Smeaton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!