简体   繁体   English

Django自定义注册表格

[英]Django custom registration form

I'm trying to create a custom form where the user can also enter his name for instance but I am facing an issue, when the registration is done the name is not saved and I can't show it on the template. 我正在尝试创建一个自定义表单,用户也可以在其中输入其名称,但是我遇到了一个问题,当完成注册时,该名称未保存且无法在模板上显示。

here is the code 这是代码

views.py views.py

def register_user(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/user/')
    else:
        if request.method == 'POST':
            form = MyRegistrationForm(request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/user/')

        context = {}
        context.update(csrf(request))
        context['form'] = MyRegistrationForm()

        return render(request, 'register.html', context)

forms.py forms.py

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    name = forms.CharField(required=True)

    class Meta:
        model = User
        fields = {'name', 'username', 'password1', 'password2', 'email'}

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.name = self.cleaned_data['name']

        if commit:
            user.save()

        return user

register.html register.html

<form action="/user/register/" method="post" id="register" autocomplete="off">
{% csrf_token %}
<div class="fieldWrapper">
  {{ form.name.errors }}
  {{ form.name.label_tag }}
  {{ form.name }}
</div>
[... other form fields ...]
</div>
<input type="submit" value="Register"/>
</form>

So when I submit the form, everything works but when I try to show {{ user.name }} in the template, nothing is shown, why is that? 因此,当我提交表单时,一切正常,但是当我尝试在模板中显示{{ user.name }}时,什么也没显示,为什么? (it works for the email field) (适用于电子邮件字段)

The default User object doesn't have a name field (so you are actually just saving the content of your name field to the object, and not the database). 默认的User对象没有name字段 (因此,实际上您只是将name字段的内容保存到对象而不是数据库中)。 It has a first_name and last_name so you can either use those fields instead or you can customize the User model to have a separate name field 它有一个first_namelast_name ,所以你可以使用这些字段来代替,也可以自定义User模型有一个单独的name字段

Edit 编辑

Also, just so you know, if you use the first_name and last_name fields instead, the User model has a get_full_name() method built-in which might be useful 另外,您知道,如果您改用first_namelast_name字段,则User模型具有内置的get_full_name()方法,这可能会很有用

The User does not have a "name" field. 用户没有“名称”字段。 Try: 尝试:

{{ user.username }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM