0

enter image description hereI 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
Febin Stephen
  • 71
  • 1
  • 10
  • The form's init is called twice. Once in the GET-request when the form is served, once in the POST-request when the initial username from the first request is presumably posted. The form then saves the value that was posted in `request.POST`, not the initial value of the field. THat saved value might be the initial value from the previous request if the user did not type in sth different. – user2390182 Jun 28 '18 at 13:00
  • i set this field to be disabled=True.but it still get changed after hitting save somehow – Febin Stephen Jun 28 '18 at 13:09
  • Gets changed from which state? From what what you see in the hidden input or what the initial value is during the post request? – user2390182 Jun 28 '18 at 13:14
  • @schwobaseggl Updated my question with the initial screen, the username that shown in the form is not the one that gets saved to the db after hitting save – Febin Stephen Jun 28 '18 at 13:19
  • Disabled inputs are not submitted at all [see here e.g.](https://stackoverflow.com/questions/1355728/values-of-disabled-inputs-will-not-be-submitted). Hence, the initial value of the next form instantiation is taken which makes another call to your random function. You can see this if you log/print the initial value in your form's init. – user2390182 Jun 28 '18 at 13:27
  • You are right, by changing disabled to false solved the issue, is there any workaround if I still want it to be readonly – Febin Stephen Jun 28 '18 at 16:50

0 Answers0