 I use a custom form inherited from django's UserCreationForm to add user. How ever i have to set different initial value for username field.It works perfectly but after hitting save button the user get saved with a different username than the initial value shown in the form.You can find the code below
I use a custom form inherited from django's UserCreationForm to add user. How ever i have to set different initial value for username field.It works perfectly but after hitting save button the user get saved with a different username than the initial value shown in the form.You can find the code below
from django.contrib.auth.forms import UserCreationForm
class AdminUserCreationForm(UserCreationForm):
    """
    AdminForm for creating an instance of custom USER_MODEL.
    """
    email = forms.EmailField(required=True)
    class Meta:
        model = User
        fields = ("username", "email")
        field_classes = {'username': UsernameField}
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.initial['username'] = random_username_generator()
        self.fields['username'].disabled = True
        self.fields['password1'].required = False
        self.fields['password2'].required = False
    def clean_username(self):
        username = self.cleaned_data['username'].lower()
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError('A user with username {} already exists'.format(username))
    def clean_email(self):
        email = self.cleaned_data['email'].lower()
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError('A user with email {} already exists'.format(email))
    def save(self, commit=True):
        import ipdb; ipdb.set_trace();
        user = super(AdminUserCreationForm, self).save(commit=False)
        # user = self.instance
        qb = QuickBlox()
        qb_password = reset_password_generator()
        user.qb_password = qb_password + 'vx'
        user.save()
        attempt = LoginAttempts()
        attempt.user = user
        attempt.save()
        send_invite_mail(user)
        return user
