[Django]-Django Registration – Need a simple way to default username to a randomly generated string

2πŸ‘

βœ…

You can subclass RegistrationForm and make username field as readonly by adding readonly widget attribute :

from registration.forms import RegistrationForm

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

In your RegistrationView subclass change form_class to your form class and override get_initial function (your generation random password code can be placed here to):

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
πŸ‘€ndpu

1πŸ‘

You can create a new 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

And in your urls.py add something like

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

This isn’t tested but it should get you close. I think you might need to create a new RegistrationForm and supply it in urls.py with

RandomRegistrationView.as_view(form_class=RandomRegistrationForm) 

Or you may simply be able to make the necessary changes in the template. I’m not 100% sure without actually implementing it.

πŸ‘€bnjmn

1πŸ‘

You can subclass RegistrationForm to set initial value and readonly attribute, like this:

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'})

and of course set the above form class as your registration form.

πŸ‘€mariodev

Leave a comment