PacktPublishing / Django-5-By-Example

Django 5 By Example (5th Edition) published by Packt
https://djangobyexample.com/
MIT License
180 stars 81 forks source link

Chapter 6 -- "User" is not defined #16

Open JordanBarnartt opened 3 months ago

JordanBarnartt commented 3 months ago

Chapter 6 adds validation to ensure that email addresses are not reused when a user is registering or editing their profile.

However, the User object at https://github.com/PacktPublishing/Django-5-By-Example/blob/a4c1e4e917c7f68472bf575ef7bf3cf096e7e8e1/Chapter06/bookmarks/account/forms.py#L34 and https://github.com/PacktPublishing/Django-5-By-Example/blob/a4c1e4e917c7f68472bf575ef7bf3cf096e7e8e1/Chapter06/bookmarks/account/forms.py#L46 is not actually defined anywhere.

Comparing to https://github.com/PacktPublishing/Django-4-by-example/blob/main/Chapter05/bookmarks/account/forms.py, it looks like the import of User was replaced with get_user_model without fixing these two instances.

Doing something like the following solves the issue:

def clean_email(self):
        data = self.cleaned_data["email"]
        user = get_user_model()
        if user.objects.filter(email=data).exists():
            raise forms.ValidationError("Email already in use.")
        return data

...

def clean_email(self):
        data = self.cleaned_data["email"]
        user = get_user_model()
        qs = user.objects.exclude(id=self.instance.id).filter(email=data)
        if qs.exists():
            raise forms.ValidationError("Email already in use.")
        return data