Created
September 4, 2017 19:09
-
-
Save LowerDeez/74dabca0b5dd499f42f424de72ede9bf to your computer and use it in GitHub Desktop.
Django. How to process more than one form at once in CVB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EditProfileView(LoginRequiredMixin, SuccessMessageMixin, FormView): | |
model = User | |
template_name = 'accounts/settings/settings.html' | |
success_message = _('Your profile was successfully updated!') | |
form_class = UserForm | |
second_form_class = ProfileForm | |
def get_context_data(self, **kwargs): | |
context = super().get_context_data(**kwargs) | |
if 'user_form' not in context: | |
context['user_form'] = self.form_class(instance=self.request.user) | |
if 'profile_form' not in context: | |
context['profile_form'] = self.second_form_class(instance=self.request.user.userprofile) | |
return context | |
def post(self, request, *args, **kwargs): | |
user_form = self.form_class(request.POST, instance=request.user) | |
profile_form = self.second_form_class(request.POST, instance=request.user.userprofile) | |
if user_form.is_valid() and profile_form.is_valid(): | |
return self.form_valid(user_form, profile_form) | |
else: | |
return self.form_invalid(user_form, profile_form) | |
def form_valid(self, user_form, profile_form): | |
with transaction.atomic(): | |
profile_form.save() | |
user_form.save() | |
return super().form_valid(user_form) | |
def form_invalid(self, **kwargs): | |
return self.render_to_response(self.get_context_data(**kwargs)) | |
def get_success_url(self): | |
return reverse_lazy('accounts:profile', kwargs={'username': self.request.user.username}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment