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

时间:2021-05-01 19:21:25

I ran today into a special situation. Previously I had the following in my view.py

我今天跑到了一个特殊的境地。以前我在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)

It was pretty straight forward retrieving the username, email and password to create a new user after she has registered. But now I have refactored it to use a hash code as the username and utilize the email alone to register and login.

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

The shortened RegistrationForm looks like this:

缩短的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

The new form doesn't have the username any longer, since it is calculated and not entered by the user any more. But how do I retrieve the username from the view ? The new code is not from me and I have it from a blog. Maybe the key is here in the Meta class? From the documentation I wasn't able to fully understood what he is trying to achieve with the Meta class here...

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

Many Thanks,

非常感谢,

EDIT:

编辑:

Ok I think I understand now how the subclassing should work. I tried to subclass the User class like this:

好的,我想我现在明白子类应该如何工作。我试图像这样继承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

The problem I am facing now are two errors, self._db and self.model, were meant to be on the base user class. How do get to them from here?

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

Edit 2:

编辑2:

PyCharm complains that the two self._db and seld.model don't exit on current cb_user_model_backend.

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

Note the View is refactored to take two parameters:

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

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

When running it stack trace is:

运行时,堆栈跟踪是:

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

1 个解决方案

#1


0  

Try subclassing your save method in your models.py:

尝试在models.py中继承save方法:

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

After calling user.save(), user.username should yield the generated username in your views. Hope this helps.

在调用user.save()之后,user.username应该在您的视图中生成生成的用户名。希望这可以帮助。

EDIT: If you want to call create_user(**kwargs), you could do the following in your views.py:

编辑:如果要调用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)

#1


0  

Try subclassing your save method in your models.py:

尝试在models.py中继承save方法:

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

After calling user.save(), user.username should yield the generated username in your views. Hope this helps.

在调用user.save()之后,user.username应该在您的视图中生成生成的用户名。希望这可以帮助。

EDIT: If you want to call create_user(**kwargs), you could do the following in your views.py:

编辑:如果要调用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)