Okay so you want to show up two different forms in template and save them individually to database.
For me I usually stick to the simplest way and best way for me so far.
Here's it, take this one as an example
def update_profile(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
# redirect to somewhere else
else:
# message.error
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'profiles/profile.html', {
'user_form': user_form,
'profile_form': profile_form
})
Django is very smart handling ModelForms, after performing a number of behind the scene validation when
form.is_valid()
Is called.
It'll will save fields that were changed and leave out those with no changes.
Here's template render of the forms
<form method="post">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<button type="submit">Save changes</button>
</form>
And here's the forms.oh
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('url', 'location', 'company')
Like I mentioned earlier, Django is smart enough to handle your ModelForms as long as you call it's form.is_valid() it'll will do the lifting for you.
This has been an easier approach for me
If you want something more controlled
Check out Django Formset