Django注册-需要一种简单的方法将用户名默认为随机生成的字符串



我正在使用Django注册。它提供了处理registration_form.html的视图,该视图当前包含用户名、密码1、密码2和电子邮件作为我的应用程序中的用户可输入字段。我有一个非常简单的随机用户名生成器,我想用它在registration_form.html中预填充用户名,并使其成为"只读"。我很难弄清楚在Django Registration中我应该在哪里进行调整。我相信它在这里的某个地方:

class RegistrationView(_RequestPassingFormView):
"""
Base class for user registration views.
"""
disallowed_url = 'registration_disallowed'
form_class = RegistrationForm
http_method_names = ['get', 'post', 'head', 'options', 'trace']
success_url = None
template_name = 'registration/registration_form.html'
def dispatch(self, request, *args, **kwargs):
"""
Check that user signup is allowed before even bothering to
dispatch or do other processing.
"""
if not self.registration_allowed(request):
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
def form_valid(self, request, form):
new_user = self.register(request, **form.cleaned_data)
success_url = self.get_success_url(request, new_user)
# success_url may be a simple string, or a tuple providing the
# full argument set for redirect(). Attempting to unpack it
# tells us which one it is.
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
def registration_allowed(self, request):
"""
Override this to enable/disable user registration, either
globally or on a per-request basis.
"""
return True
def register(self, request, **cleaned_data):
"""
Implement user-registration logic here. Access to both the
request and the full cleaned_data of the registration form is
available here.
"""
raise NotImplementedError

更新:

因此,根据最初的回应,我开始快速编辑现有的RegistrationView,如下所示:

class RegistrationForm(forms.Form):
required_css_class = 'required'
# username = forms.RegexField(regex=r'^[w.@+-]+$',
#                             max_length=30,
#                             label=_("Username"),
#                             error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})   
# My new username stuff here:                     
n = random.randint(1,9999999)
default_username = 'AnonMom%d' % (n,) 
username = forms.CharField(initial="default_username") 
email = forms.EmailField(label=_("E-mail"))
password1 = forms.CharField(widget=forms.PasswordInput,
label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput,
label=_("Password (again)"))

我希望看到我的默认用户名显示在registration.form.html中,定义如下:

<form method="post" action=".">{% csrf_token %}
<p><input id="id_username" maxlength="25" name="username" type="text" autocomplete="off"></p>
<p style="font-size:12px; color:#999">Make it anonymous but easy to remember. 25 chars max. No spaces.</p>  
<p><input id="id_password1" name="password1" type="password" placeholder="Password"/></p>
<p><input id="id_password2" name="password2" type="password" placeholder="Password (Confirm)"/></p>
<p><input id="id_email" name="email" type="email" placeholder="Email (Never displayed)" autocomplete="off"/></p>

但这块地是空的。如果我只是设置initial="xxx",它甚至是空的。我做错了什么?

更新2:

这一切都是使用上面的代码,对视图和表单进行了以下轻微的改动:

class RegistrationForm(forms.Form):                           
n = random.randint(1,9999999)
username = forms.CharField(initial='MomzAnon%d' % (n,) ) 
...
<form method="post" action=".">{% csrf_token %}
<p><input id="id_username" maxlength="25" name="username" type="text" 
value="{{ form.username.value }}" readonly autocomplete="off"></p>
...

最后一个问题:是否有任何理由将RegistrationForm子类化而只是编辑它?就代码行而言,我的方法似乎非常简单。

更新3:每次我调用这个表单时,我的随机用户名似乎都不是自动生成的。所以我在创建了一个用户后回到这个表单,发现自动生成的用户名与上次用户注册时没有变化。如何在每次向用户显示此表单时强制重新生成用户名?

更新4:通过将用户名逻辑移到这里,我解决了UPDATE3中概述的问题。这个代码还包括一个调整,以确保我随机生成的用户名也是唯一的:

def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
n = random.randint(1,999999) 
new_username = 'anon%d' % (n,) 
while User.objects.filter(username=new_username).exists():
n = random.randint(1,999999)
new_username = 'anon%d' % (n,) 
self.fields['username'] = forms.CharField(initial=new_username)

您可以将RegistrationForm子类化,并通过添加readonly小部件属性使username字段为只读:

from registration.forms import RegistrationForm
class MyForm(RegistrationForm):
username = forms.CharField(max_length=30, label=_("Username"),
widget=forms.TextInput(attrs={'readonly':'readonly'}))

在您的RegistrationView子类中,将form_class更改为表单类并覆盖get_initial函数(您的生成随机密码代码可以放在此处):

class MyReg(RegistrationView):
form_class = MyForm
def get_initial(self, *args, **kwargs):
self.initial = {'username': self.gen_randrom_username()}
return super(Myreg, self).get_initial(*args, **kwargs)
def gen_randrom_username(self):
# gen name
return random_username

您可以创建一个新的RegistrationView

from django.contrib.sites.models import RequestSite, Site
from registration import signals
from registration.models import RegistrationProfile
from registration.backends.default.views import RegistrationView
class RandomRegistrationView(RegistrationView):
def register(self, request, **cleaned_data):
email, password = cleaned_data['email'], cleaned_data['password1']
username = call_random_username_genator() # <- supply your RANDOM username here
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)                         
new_user = RegistrationProfile.objects.create_inactive_user(username, email,
password, site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user

urls.py中添加类似的内容

url(r'^accounts/register/$', RandomRegistrationView.as_view(),
name='registration_register'),

这没有经过测试,但它应该会让你接近。我认为您可能需要创建一个新的RegistrationForm,并在urls.py中提供

RandomRegistrationView.as_view(form_class=RandomRegistrationForm) 

或者,您可以简单地对模板进行必要的更改。如果没有实际实施,我不能100%确定。

您可以将RegistrationForm子类化以设置初始值和只读属性,如下所示:

class MyRegistrationForm(RegistrationForm):
def __init__(self, *args, **kwargs):
super(MyRegistrationForm, self).__init__(*args, **kwargs)
self.initial['username'] = random_username()
self.fields['username'].widget.attrs.update({'readonly': 'readonly'})

当然,还可以将上述表格类设置为您的注册表格。

最新更新