如何从表单中获取用户名?

时间:2012-06-18 22:18:34

标签: python django forms

我今天跑到了一个特殊的境地。以前我在view.py

中有以下内容
def register_page(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password2'],
                email=form.cleaned_data['email']
            )
            return HttpResponseRedirect('/register/success/')
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {'form':form})
    return render_to_response('registration/register.html', variables)

在注册后,检索用户名,电子邮件和密码以创建新用户非常简单。但现在我已经重构它使用哈希码作为用户名并单独使用电子邮件注册和登录。

缩短的RegistrationForm如下所示:

class RegistrationForm(forms.ModelForm):
   email = forms.EmailField(label=_("Email"))
   password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
   password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput))

   class Meta:
        model = User
        fields = ("email",)

   def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        email = self.cleaned_data['email']
        user.username = md5(email).digest().encode('base64')[:-1]
        if commit:
            user.save()
        return user

新表单不再具有用户名,因为它是计算的,不再由用户输入。但是如何从视图中检索用户名?新代码不是来自我,而是来自博客。也许关键在Meta类中?从文档中我无法完全理解他在这里尝试使用Meta类...

非常感谢,

修改

好的,我想我现在明白了子类化应该如何工作。我试图像这样继承User类:

class cb_user_model_backend(ModelBackend):

    def create_user(self, email=None, password=None):
        """
        Creates and saves a User with the given email and password only.
        """
        now = timezone.now()
        username = md5(email).digest().encode('base64')[:-1]
        email = UserManager.normalize_email(email)
        user = self.model(username=username, email=email,
            is_staff=False, is_active=True, is_superuser=False,
            last_login=now, date_joined=now)

        user.set_password(password)
        user.save(using=self._db)
        return user

我现在面临的问题是两个错误,self._db和self.model,意味着在基本用户类上。怎么从这里找到他们?

编辑2:

PyCharm抱怨两个self._db和seld.model不会退出当前的cb_user_model_backend。

请注意,视图被重构为采用两个参数:

user = User.objects.create_user(
                password=form.cleaned_data['password2'],
                email=form.cleaned_data['email']
            )

运行时,堆栈跟踪为:

Exception Type: TypeError
Exception Value:    
create_user() takes at least 2 arguments (3 given)

1 个答案:

答案 0 :(得分:0)

尝试在models.py中继承您的保存方法:

def save(self, *args, **kwargs):
    if not self.id:
        self.username = md5(self.email).digest().encode('base64')[:-1]
    super(ModelName, self).save(*args, **kwargs)

调用user.save()后,user.username应在视图中生成生成的用户名。希望这会有所帮助。

编辑: 如果要调用create_user(** kwargs),可以在views.py中执行以下操作:

email = self.cleaned_data['email']
username = md5(email).digest().encode('base64')[:-1]
u = User.objects.create_user(username = username, email = email, password = password)