Reputation: 803
So, I'm still a total noob at Django and I was wondering how to do the following:
So lets say that I have something like the below code:
class UserProfile(models.Model):
#Some fields
class UserProfileOther(models.Model):
#Some other fields that I want in another table for organization
user_profile = models.OneToOneField(UserProfile)
How do I now create a form that includes both of the above models?
Upvotes: 2
Views: 4436
Reputation: 2215
You can create two separate ModelForm classes. But in your view, you have to add a prefix to their instances.
def viewname(request):
if request.method == 'POST':
form1 = forms.YourForm(request.POST, prefix="form1")
form2 = forms.YourOtherForm(request.POST, prefix="form2")
if form1.is_valid() and form2.is_valid():
# process valid forms
else:
form1 = forms.YourForm(prefix="form1")
form2 = forms.YourOtherForm(prefix="form2")
....
Using a prefix ensures that fields with similar names are not mixed up.
Upvotes: 2
Reputation: 174718
This kind of problem is what inline formsets are designed for.
Upvotes: 3
Reputation: 2095
The way I did it was to create a form based on the first model, and then to create a form based on the second model that inherits the first form. Meaning:
class UserProfileForm(ModelForm): ...
class UserProfileOtherForm(UserProfileForm): ...
And pass the UserProfileOtherForm
to form template. It worked for me. Not sure if there is a simpler approach.
Upvotes: 0