Unicode问题使用自定义表单更新用户模型

时间:2014-11-18 04:13:40

标签: django django-forms django-views django-users

尝试更新用户模型和UserProfile模型我痴迷于生成具有User和UserProfile模型属性的表单,以使用相同的表单更新两者。但是当我将表单提交给视图时,Users模型正在更新而没有unicode渲染,例如:(u' username' ),(你的名字')。我不明白为什么会这样,我检查两个文件中的utf-8标签。

forms.py

# -*- encoding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User

class UserProfileForm(forms.Form):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(UserProfileForm, self).__init__(*args, **kwargs)

    username = forms.CharField(required=True,
        widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))

    name = forms.CharField(required=True,
        widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))

    lastname = forms.CharField(required=True,
        widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))

    email = forms.CharField(required=True,
        widget = forms.EmailInput(attrs={'class':'input', 'autocomplete':'off'}))

    change_password = forms.BooleanField(required=False,widget = forms.CheckboxInput())

    password1 = forms.CharField(required=False, min_length = 8,
        widget = forms.PasswordInput(render_value=False, attrs={'class':'input hidden'}))

    password2 = forms.CharField(required=False, min_length = 8,
        widget = forms.PasswordInput(render_value=False, attrs={'class':'input hidden'}))

    institution = forms.CharField(required=False,
        widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))

    logo = forms.ImageField(required=False)

    def clean_username(self):
        username = self.cleaned_data.get('username').lower()
        print username
        try:
            u = User.objects.exclude(pk=self.request.user.id).get(username__iexact=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(u'Este nombre de usuario ya existe.')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        try:
            e = User.objects.exclude(pk=self.request.user.id).get(email__iexact=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(u'ya existe un usuario asociado a este correo electrónico.')

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if not(password1 and password2):
            pass
        elif not password2:
            raise forms.ValidationError("Debes confirmar la contraseña")
        if password1 != password2:
            raise forms.ValidationError("Las contraseñas no coinciden")
        return password2

目前该视图仅更新用户模型:

class UpdateProfile(FormView):
    model = User
    template_name = 'general/perfil.html'
    form_class = UserProfileForm

    def get_initial(self):
        initial = super(UpdateProfile, self).get_initial()
        initial['username'] = self.request.user.username
        initial['name'] = self.request.user.first_name
        initial['lastname'] = self.request.user.last_name
        initial['email'] = self.request.user.email
        try:
            profile = UserProfile.objects.get(user=self.request.user)
        except UserProfile.DoesNotExist:
            profile = None
        if profile:
            initial['institution'] = profile.institution    
        return initial

    def get_form_kwargs(self):
         kwargs = super(UpdateProfile, self).get_form_kwargs()
         kwargs.update({'request' : self.request})
         return kwargs

    def form_valid(self, form):
        user = get_object_or_404(User, pk= self.request.user.id)
        user.username = form.cleaned_data['username'],
        user.first_name = form.cleaned_data['name'],
        user.last_name = form.cleaned_data['lastname'],
        user.email = form.cleaned_data['email']
        if form.cleaned_data['change_password']:
            user.password = form.cleaned_data['password1']
        user.save()
        return HttpResponseRedirect('/profile')

可能是form.cleaned_data方法的问题? 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在以下几行中密切关注 veeery

user.username = form.cleaned_data['username'],
user.first_name = form.cleaned_data['name'],
user.last_name = form.cleaned_data['lastname'],
你知道吗?

是的,最后是逗号。它创造了一个元组。停止这样做。