Reputation: 3
I've created a user registration form, and for some reason the first_name and last_name fields are stored within (u'',). How do I prevent this?
views.py (unrelated stuff omitted):
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
email=form.cleaned_data['email'],
password=form.cleaned_data['password']
)
user.first_name=form.cleaned_data['first_name'],
user.last_name=form.cleaned_data['last_name'],
user.save()
userprofile, created = UserProfile.objects.get_or_create(user = user)
return HttpResponse("you have been successfully registered!")
models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
For instance, I register a user with the name Joe Bruin. The name is stored as (u'Joe',) (u'Bruin',). I figure something has gone wrong with form.cleaned_data, but I'm not sure how.
Upvotes: 0
Views: 1142
Reputation: 616
first_name
and last_name
are not stored within u''
. The u''
just means that the returned string is in unicode format. The default encoding in django is unicode. Take a look at what is actually stored in your database.
From Django Docs General String Handling:
# Python 2 legacy:
my_string = "This is a bytestring"
my_unicode = u"This is an Unicode string"
# Python 3 or Python 2 with unicode literals
from __future__ import unicode_literals
my_string = b"This is a bytestring"
my_unicode = "This is an Unicode string"
Notice how in Python 3 the default is unicode.
Upvotes: 1
Reputation: 129011
You have trailing commas:
user.first_name=form.cleaned_data['first_name'],
user.last_name=form.cleaned_data['last_name'],
That makes them into tuples. You don't want that. Remove the trailing commas.
Upvotes: 3