Opened 7 years ago

Closed 7 years ago

#29397 closed Bug (invalid)

Username validation should be handled at the model level on object creation.

Reported by: Andrew Carl Owned by: nobody
Component: contrib.admin Version: 1.11
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have a rather large django system that conglomerates users from a bunch of systems into a single platform. In order to prevent duplicate usernames, I am constructing usernames like: <username>|<previous_system_id>. I am able to successfully create and modify the user object with direct calls to the database. However, attempting to modify another username field in the admin site returns a validation error. I have attempted to overwrite this form-level validation like so:

admin.site.unregister(User)
username_field = forms.RegexField(label="Username", max_length=150,
    regex=r'^.+$',
    help_text = "Required. 30 characters or fewer. Letters, digits and "
                      "@/./+/-/_/| only.",
    error_messages = {
            'invalid': "This value may contain only letters, numbers and "
                         "@/./+/-/_/| characters."})

class MyUserCreationForm(UserCreationForm):
    username = username_field

class MyUserChangeForm(UserChangeForm):
    username = username_field

@admin.register(User)
class MyUserAdmin(UserAdmin):
    add_form = MyUserCreationForm
    form = MyUserChangeForm

This, however will return the error:

This value may contain only letters, numbers and @/./+/-/_/| characters.

This leads me to believe that my user admin form is correctly being overridden, as my custom error message is displayed. I am currently able to modify and save my user model by setting the 'username' field to be read only.

The fact that I am able to save on the out of the box user model with an "invalid" character, but then have the stock admin site break I would consider unexpected behavior. This would be acceptable if the form validator was able to be overridden or if I was thrown an exception on object creation.

Change History (2)

comment:1 by Tim Graham, 7 years ago

It's not clear to me where the problem is and why Django is at fault. Can you investigate a bit further or explain what change is required?

comment:2 by Claude Paroz, 7 years ago

Resolution: invalid
Status: newclosed

As I understand your description, your are surprised that model validation is not called at the model.save() stage. This is by design and you should call full_clean() in your code, as described in https://docs.djangoproject.com/en/2.0/ref/models/instances/#validating-objects.

Note: See TracTickets for help on using tickets.
Back to Top