简体   繁体   中英

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

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

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

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

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

The User does not have a "name" field. Try:

{{ user.username }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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