在Django中编辑用户

时间:2013-05-10 07:26:14

标签: django forms

我试图使用我用来创建用户的表单来编辑用户, 我不知道为什么我收到错误用户名已存在。

以下是我的观点:

def registration_edit(request):
    """ Registration Step2:
                               The user should be authenticated to reach this step.
                               Authentication is provided by first step or user login.
    """
    if request.user.is_authenticated():
        if request.POST:
            form = RegistrationForm(request.POST or None, instance=request.user)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('reg_step_2'))
        else:
            form = RegistrationForm(instance=request.user)
        page = 'account'  
        title = 'Editing User Registration'
        context = {'title': title, 'form': form, 'page': page}
        template = 'customer/registration.djhtml'
        return render_to_response(template, context, context_instance=RequestContext(request))        
    else:
        messages.info(request, '<strong>Note</strong>: You must logged in to edit your account.')
        return HttpResponseRedirect('/')

forms.py我这样做了,因为我想在注册时加入firstname和lastname字段。

    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm

    class RegistrationForm(UserCreationForm):
        class Meta:
            model = User
            exclude = ('is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'groups', 'user_permissions', 'password')

这是我的模板

<form class="form-horizontal" action='.' method="POST">
    {% csrf_token %}
    <fieldset>
        <div id="legend">
            <legend class="">
                {{ title|title }}
            </legend>
        </div>
        {% for f in form %}
        <div class="control-group">
            <label class="control-label"  for="username">{{ f.label }}</label>
            <div class="controls">
                {{ f }}&nbsp;<i style="color: orange">{{ f.errors|striptags }}</i>
            </div>
        </div>
        {% endfor %}
        <div class="controls">
            <button class="btn btn-success">
                Continue
            </button>
        </div>
    </fieldset>
</form>

有人告诉我我在哪里乱搞? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的继承自UserCreationForm cleans the username field

在这种情况下,请参阅UserChangeForm