The World’s Largest Online Community for Developers

'; python - how to generate random User username and insert into the datebase in django - LavOzs.Com

I am trying to generate username randomly and save to the User model. Currently I can able to generate the username, But I can't able to save that into the User Model and I don't know how can I do it. Please help to done it. my forms process without the random username generator function. When i adding these function to generate custom and random username I'm facing lots of error like, attibute error, unbound error and so on

# random username generator
def userdate(dt_time):
    return str(10000*dt_time.year+100*

def usernameGen(names):
    names = names.split(" ") 
    for i in range(1,1000):
        first_letter = names[0][0]
        three_letter = names[-1][:3]
        number = '{:03d}'.format(random.randrange(1,1000))
        dateuser = userdate(
        username =(first_letter+three_letter+dateuser+number)

            User.objects.get(username = username)
            return usernameGen("PMK GAC")
        except User.DoesNotExist:
            return username

# registration view

def register(request, *args, **kwargs):

    if request.method == 'POST':
        username = usernameGen("PMK GAC") #calling usernameGen function
        form = CustomUserCreationForm(request.POST) #user form
        profile = ProfileForm(request.POST, request.FILES) #profile form
        if form.is_valid() and profile.is_valid():
            # messages.success(request, 'new user is create. ')

            return render(request,'info.html')

    form = CustomUserCreationForm()
    profile = ProfileForm()

    context = {'form':form, 'profile':profile}
    return render(request, 'register.html', context)

#this models is not User model. it is additional model with One to one relationship of current user
class Profile(models.Model):
    # specified choices
    ("Department of Computer Science", "Department of Computer Science" ),
    ("Department of Electronics", "Department of Electronics" ),
    ("Department of Bio-Chemistry", "Department of Bio-Chemistry" ),
    ("Department of Chemistry", "Department of Chemistry" ),
    ("Department of Tamil", "Department of Tamil" ),
    ("Department of English", "Department of English" ),
    ("Department of Mathematics", "Department of Mathematics" ),
    ("Department of Physics", "Department of Physics" ),
    ("Department of Commerce", "Department of Commerce" ),
    ("Department of Business Administration", "Department of Business Administration" ),
    ("Department of Histroy", "Department of Histroy" ),
    ("Department of Economics", "Department of Economics" ),

        ('Male', 'Male'),
        ('Female', 'Female')

    user = models.OneToOneField(User, on_delete = models.CASCADE) 
    Date_Of_Birth = models.DateField(null=True)
    Department = models.CharField(null=True, max_length = 50, choices= DEPARTMENT_CHOICES, default=None)
    Phone_number = models.CharField(unique=True, null=True,max_length=10)
    Age = models.CharField(null=True, max_length = 3)
    University_Exam_No = models.CharField(null=True, max_length=10)
    Aadhar = models.CharField(null = True, max_length=12)
    Gender = models.CharField(null=True, max_length = 50, choices= GENDER_CHOICES, default=None)

    Permanent_Address = models.TextField(null=True)
    Per_Taluk = models.CharField(null=True, max_length = 30)
    Per_Pin_Code = models.CharField(null=True, max_length=6)
    Per_State = models.CharField(null=True, max_length=30)
    Per_Dist = models.CharField(null=True, max_length = 30)

    Address = models.TextField(null = True)
    Dist = models.CharField(null=True, max_length = 30)
    Taluk = models.CharField(null=True, max_length = 30)
    Pin_Code = models.CharField(null=True, max_length=6)
    State = models.CharField(null=True, max_length=30)

    Image = models.ImageField(upload_to='profiles', null = True)
    Sign = models.ImageField(upload_to='Signs', null=True)

    def __str__(self):
        return self.user.first_name

# Here I directly created the form without creating a custom User model
# user registration form
class CustomUserCreationForm(forms.Form):

    firstname = forms.CharField(label='First Name', max_length=50, widget=forms.TextInput(attrs={'class':'form-control'}))
    lastname = forms.CharField(label='Last Name', max_length=50,widget=forms.TextInput(attrs={'class':'form-control'}))
    username = forms.CharField(label = 'Username', min_length=4, max_length=150,widget=forms.TextInput(attrs={'class':'form-control'}))
    email = forms.EmailField(label='Email id', widget=forms.EmailInput(attrs={'class':'form-control'}))
    password1 = forms.CharField(label = 'Password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
    password2 = forms.CharField(label = 'Conform Password', widget=forms.PasswordInput(attrs={'class':'form-control'}))

    def clean_firstname(self):
        firstname = self.cleaned_data['firstname']
        return firstname

    def clean_lastname(self):
        lastname = self.cleaned_data['lastname']
        return lastname

    def clean_username(self):
        username = self.cleaned_data['username']
        r = User.objects.filter(username = username)
        if r.count():
            raise ValidationError('username is already exists')
        return username

    def clean_email(self):
        email = self.cleaned_data['email']
        r = User.objects.filter(email = email)
        if r.count():
            raise ValidationError('Email id is already exists')
        return email

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

        if password1 and password2 and password1 != password2:
            raise ValidationError(' Passwords did not matching')
        return password2

    def save(self, commit = True):
        user = User.objects.create_user(

        return user

# profile model is model forms of Profile model
class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = '__all__'
        exclude = ['user']
        widgets = {
            'Date_Of_Birth':forms.DateInput(attrs={'class':'form-control', 'placeholder':'YYYY-MM-DD'}),
            'Department':forms.Select(attrs = {'class':'form-control'}),
            'Phone_number':forms.NumberInput(attrs = {'class':'form-control'}),
            'Gender':forms.Select(attrs = {'class':'form-control'}),

            'Permanent_Address':forms.Textarea(attrs = {'class':'form-control rounded', 'rows':3, 'cols':3}),
            'Per_Pin_Code':forms.NumberInput(attrs = {'class':'form-control'}),

            'Address':forms.Textarea(attrs = {'class':'form-control rounded','rows':3, 'cols':3}),
            'Pin_Code':forms.NumberInput(attrs = {'class':'form-control'}),


if you have a form to create new users, so they will fill the username field too. but anyway, for any new object of any model, you could override the save function, or at least before saving it to the database add some attribute to the object.

for example in your modelAdmin of the model in the add this(according to

classs MyCustomUserAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.username = Your_Username_Gen_Functio()
        super().save_model(request, obj, form, change)

its possible to do sth like this in too in

def register(request):
     username = random_str(15)
     new_user = User.objects.create(
         #other_fields = form.other_fields

give an integer N to get a randon string in length of N:

import random
random_string = lambda N: ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(N)
Extending the User model with custom fields in Django
How do I do a not equal in Django queryset filtering?
Random string generation with upper case letters and digits
Generate random integers between 0 and 9
custom user registration form in django
filter json data from Django model
How to serialize a queryset from an unrelated model as a nested serializer?
Auto-generating username when adding a user with django
Customer User Authentication error : AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user_management.CustomUser'
How to implement update_or_create inside create method of ModelSerializer