「我想要的是,如果用戶更改了配置文件更新表單上的任何數據並提交了帶有錯誤的密碼更改表單,那麼我應該看到密碼錶單上的錯誤以及用戶更新中更改的數據。形式「處理這類問題的
一種方法是兩種形式一起發送:
<form method="post">
{% csrf_token %}
<h2>Your User Update Form</h2>
{% user_update_form %}
<h2>Your Password Change Form</h2>
{% password_change_form %}
</form>
,然後在您的視圖:
def get(self, request, *args, **kwargs):
# initialize both forms with prefixes
user_update_form = UserUpdateForm(prefix='user_update')
password_change_form = UserPasswordForm(prefix='password_change')
return self._render_form(user_update_form, password_change_form)
def post(self, request, *args, **kwargs):
# read forms from POST
user_update_form = UserUpdateForm(request.POST, prefix='user_update')
password_change_form = UserPasswordForm(request.POST, prefix='password_change')
# validate password form
if password_change_form.is_valid():
# do something
else:
# password form has errors, so return both forms
return self._render_form(user_update_form , password_change_form)
def _render_form(self, user_update_form, password_change_form):
context = {'user_update_form': user_update_form, 'password_change_form': password_change_form}
return TemplateResponse(self.request, '**/your_template.html', context)
謝謝,但從長遠來看這不是一個好的選擇。假設如果我在模板中的其他地方使用第三個表單來處理不能合併的內容,那麼是什麼? –