lovers of zero and one. How can I make a view have two forms with two different models but saving one form doesn't affect the other?
try to use a modelform use it in a single view. but I would like to know how to solve it or the best practice for these cases.
CodePudding user response:
You can use the name
attribute of the button on the form. For example;
<form>
...
<input type="submit" name="save-user" value="Save user" />
</form>
<form>
...
<input type="submit" name="save-category" value="Save category" />
</form>
Then in python you can detect which button was clicked like this;
if 'save-user' in request.POST:
# save the user
elif 'save-category' in request.POST:
# save the category
CodePudding user response:
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