0

I have a form that can access by the boss account, the boss will use this form to create his employee accounts

def EmployeeForm(forms.Form):
    username = forms.CharField(max_length = 16)

    def clean_username(self):
        if User.objects.filter(username = self.cleaned_data.get('username')).exists():
            raise forms.ValidationError('A user with that user name already exists')
        return self.cleaned_data.get('username')

But the problem is I don't now how to validate this username field like UserCreationForm Does, and I am pretty sure making username unique isn't enough

  • In the form validation you can do something simple like: `if User.objects.filter(username=username).exists():` and return an error if True. – Ben Feb 06 '20 at 23:53
  • I did that actually but sill isn't sure if that is enough –  Feb 07 '20 at 09:39
  • Take a look at https://stackoverflow.com/questions/7948750/custom-form-validation/7948998 which is about unique email addresses, you can think of unique usernames in the same way, and use custom validation similar to that question. – Ben Feb 07 '20 at 17:07
  • I know how to clean and validate a specific field that isn't my problem my problem is how the validation should be I am pretty sure that making this filed unique isn't enough I need to use the exact same validation that UserCreationForm uses, ***I have edit the question and put the a simple validation for making the username field unique*** but as I mentioned earlier I don't think that is enough take for example the spaces how I know I should handle that in the clean_username validation but still don't know what is all the cases that I need to consider –  Feb 07 '20 at 21:57
  • Why don't you just subclass the UserCreationForm? No need to recreate it. https://github.com/django/django/blob/3.0.3/docs/topics/auth/customizing.txt#L838-L848 – Ben Feb 07 '20 at 22:19
  • Good idea but actually the form is mush more complicated and much more fields in it but I show just the username field to make it simple –  Feb 07 '20 at 22:27
  • Sure, but you could and should subclass it and just use what you need for validation, etc. `def EmployeeForm(forms.UserCreationForm):` Otherwise, you'll be reimplementing code that already exists. – Ben Feb 07 '20 at 22:41

0 Answers0