【问题标题】:Creating a user object in Django: why are first_name and last_name both stored as (u'Name',)?在 Django 中创建用户对象:为什么 first_name 和 last_name 都存储为 (u'Name',)?
【发布时间】:2013-04-01 02:36:46
【问题描述】:

我创建了一个用户注册表单,出于某种原因,first_name 和 last_name 字段存储在 (u'',) 中。如何防止这种情况发生?

views.py(不相关的东西省略了):

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)   

例如,我注册了一个名为 Joe Bruin 的用户。该名称存储为 (u'Joe',) (u'Bruin',)。我认为 form.cleaned_data 出了点问题,但我不确定是怎么回事。

【问题讨论】:

    标签: python django


    【解决方案1】:

    你有尾随逗号:

    user.first_name=form.cleaned_data['first_name'],
    user.last_name=form.cleaned_data['last_name'],
    

    这使它们成为元组。你不想要那个。删除结尾的逗号。

    【讨论】:

    • 谢谢!让那些试图将它们传递给create_user 的人留下来。希望我有足够的代表来支持你。
    【解决方案2】:

    first_namelast_name 不存储在 u'' 中。 u'' 只是表示返回的字符串是 unicode 格式。 django 中的默认编码是unicode。看看你的数据库中实际存储了什么。

    来自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"
    

    注意 Python 3 中的默认值是 unicode。

    【讨论】:

    • 谢谢。让我失望的是,它似乎只出现在名字上。如何让它在模板中正确格式化? {{ userprofile.user.first_name }} 保留 unicode 格式。
    • userprofile 是上下文的一部分,因为我使用的是自定义用户模型。
    • 您是否删除了这些行末尾的逗号?:user.first_name=form.cleaned_data['first_name'], user.last_name=form.cleaned_data['last_name'],
    • 是的,我做到了。这似乎已经解决了它。
    • 好的。逗号使您的 first_namelast_name 成为一个元组。当这些变量在模板中呈现时,您将获得元组的字符串表示形式。这就是你得到 (u'Joe',) 的原因。
    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 2017-10-12
    • 1970-01-01
    • 2012-07-18
    • 2016-03-19
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多