Saving a success message with multiple forms
I have two forms, where a user can change his name and change his password. I am having difficulty of saving a 'success message' based upon which field is saved. This is what I currently have --
def account(request):
message = '' ###
change_name_form = ChangeNameForm(data=request.POST or None, instance=request.user)
change_password_form = PasswordChangeForm(data=request.POST or None, user = request.user)
if "change_name" in request.POST and change_name_form.is_valid():
change_name_form.save()
message = 'Your name has been changed.' ###
return redirect('.')
if "change_password" in request.POST and change_password_form.is_valid():
change_password_form.save()
message = 'Your password开发者_如何学JAVA has been changed.' ###
return redirect('.')
return render_to_response('userprofile/account.html',{'message': message,...})
How would I go about saving a different message based upon which form is filled out?
Have you looked at using Django's built in messaging framework. It's useful for exactly this sort of stuff:
https://docs.djangoproject.com/en/dev/ref/contrib/messages/
from django.contrib import messages
def account(request):
if request.method == "POST":
cnf = ChangeNameForm(data=request.POST, instance=request.user)
cpf = ChangePasswordForm(data=request.POST, instance=request.user)
if cnf.is_valid() and (request.user.username != cnf.cleaned_data['username']):
cnf.save()
messages.info(request, "Username Changed")
if cpf.is_valid() and (request.user.password != cpf.cleaned_data['username']):
cpf.save()
messages.info(request, "Password Changed")
else:
cnf = ChangeNameForm(instance=request.user)
cpf = ChangePasswordForm(instance=request.user)
...
template
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
Try removing the redirects, and make sure to check for POST, generally you only handle the form processing if it's a POST request. Make sure the pass the forms to the template.
def account(request):
message = ''
change_name_form = ChangeNameForm(data=request.POST or None, instance=request.user)
change_password_form = PasswordChangeForm(data=request.POST or None, user = request.user)
if request.method == "POST":
if "change_name" in request.POST and change_name_form.is_valid():
change_name_form.save()
message = 'Your name has been changed.' ###
if "change_password" in request.POST and change_password_form.is_valid():
change_password_form.save()
message = 'Your password has been changed.' ###
return render_to_response('userprofile/account.html',{'message': message,...})
精彩评论