使用多个表单保存成功消息

时间:2011-06-07 17:24:22

标签: django django-forms

我有两种形式,用户可以更改其名称并更改密码。我很难根据保存的字段保存“成功消息”。这就是我目前所拥有的 -

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 has been changed.' ###
        return redirect('.')
    return render_to_response('userprofile/account.html',{'message': message,...})

如何根据填写的表单保存不同的消息?

2 个答案:

答案 0 :(得分:2)

您是否考虑过使用Django的内置消息传递框架?这对于这类东西很有用:

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)
    ...

<强>模板

{% if messages %}
{% for message in messages %}
    {{ message }}
{% endfor %}
{% endif %} 

答案 1 :(得分:1)

尝试删除重定向,并确保检查POST,通常只有在处理POST请求时才处理表单处理。确保将表单传递给模板。

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,...})