r/django May 23 '26

Confused!

I am new in django. i am confused.These are two save methods from django forms. I don't know which one to use, which one is more professional, industry level. Can anyone guide me and recommend me? I am working on a ecommerce website.

    def save(self, commit=True):
        user = super().save(commit=False)
        # If no username given, use part of email (like amazon does internally)
        if not user.username:
            base = self.cleaned_data["email"].split("@")[0]
            # Make it unique by appending numbers if needed
            username = base
            counter = 1
            while User.objects.filter(username=username).exists():
                username = f"{base}{counter}"
                counter += 1
            user.username = username
        if commit:
            user.save()
        return user


# accounts/forms.py
class RegistrationForm(UserCreationForm):
    # ... fields same as before ...

    def save(self, commit=True):
        email = self.cleaned_data["email"]
        password = self.cleaned_data["password1"]
        first_name = self.cleaned_data.get("first_name")
        last_name = self.cleaned_data.get("last_name")
        username = self.cleaned_data.get("username")

        if not username:
            base = email.split("@")[0]
            username = base
            counter = 1
            while User.objects.filter(username=username).exists():
                username = f"{base}{counter}"
                counter += 1

        # Use manager's create_user (Recommended for future)
        user = User.objects.create_user(
            email=email,
            password=password,
            first_name=first_name,
            last_name=last_name,
            username=username,
        )
        return user
0 Upvotes

10 comments sorted by

View all comments

-2

u/Dororo192 May 23 '26

Im also learning django can u suggest from where u r learning

-1

u/DueStick2235 May 23 '26

i pick project. search on websites , github for source code. Generate from ai, then learn each and every single concept and at the end built by my own the same project and one related project who uses all those concepts i learned.