Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Unusual setdefault's in Django

Here's a piece of code from Django's authentification models (UserManager):

def create_superuser(self, username, email, password, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)

    if extra_fields.get('is_staff') is not True:
        raise ValueError('Superuser must have is_staff=True.')
    if extra_fields.get('is_superuser') is not True:
        raise ValueError('Superuser must have is_superuser=True.')

    return self._create_user(username, email, password, **extra_fields)

Why set a key-value pair and check it immediately afterwards? In what scenario would these conditions be met?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

setdefault sets the value only if the key is not already present in the dict. The caller of the function could still pass extra_fields with some values of id_staff or is_superuser.

What this function does is that while creating a superuser if the calling function is not providing any values then set is_staff and is_superuser both to True for this user.

But, if the values are provided then check if those are True and raise exceptions otherwise.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!