Bird
Raised Fist0
Djangoframework~20 mins

String representation with __str__ in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
String Representation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of printing a Django model instance with __str__ defined?
Consider this Django model:
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.title} by {self.author}"

What will print(book) output if book = Book(title='1984', author='Orwell')?
Django
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.title} by {self.author}"

book = Book(title='1984', author='Orwell')
print(book)
ABook(title='1984', author='Orwell')
B<Book object>
C1984 by Orwell
DError: __str__ method missing
Attempts:
2 left
💡 Hint
The __str__ method defines what print(instance) shows.
📝 Syntax
intermediate
2:00remaining
Which __str__ method is correctly defined in a Django model?
Select the option that correctly defines the __str__ method in a Django model to return the model's name attribute.
Django
class Person(models.Model):
    name = models.CharField(max_length=50)

    # Which __str__ method below is correct?
A
def __str__(self):
    print(self.name)
B
def __str__(self):
    return self.name
C
def __str__(self):
    return name
D
def __str__(self):
    return self.name()
Attempts:
2 left
💡 Hint
The __str__ method must return a string, not print it or call attributes incorrectly.
🔧 Debug
advanced
2:00remaining
Why does printing this Django model instance show instead of a custom string?
Given this model:
class Product(models.Model):
    name = models.CharField(max_length=100)

    def str(self):
        return self.name

Why does print(product) show <Product object> instead of the product name?
Django
class Product(models.Model):
    name = models.CharField(max_length=100)

    def str(self):
        return self.name

product = Product(name='Laptop')
print(product)
AThe name attribute is not set correctly
BThe model is missing a __repr__ method
Cprint() cannot print model instances
DThe method should be named __str__, not str
Attempts:
2 left
💡 Hint
Check the method name spelling for string representation.
❓ state_output
advanced
2:00remaining
What is the output of printing a Django model instance with __str__ returning a formatted string?
Consider this model and instance:
class Event(models.Model):
    name = models.CharField(max_length=50)
    date = models.DateField()

    def __str__(self):
        return f"{self.name} on {self.date.strftime('%Y-%m-%d')}"

from datetime import date

event = Event(name='Conference', date=date(2024, 7, 1))
print(event)

What will be printed?
Django
class Event(models.Model):
    name = models.CharField(max_length=50)
    date = models.DateField()

    def __str__(self):
        return f"{self.name} on {self.date.strftime('%Y-%m-%d')}"

from datetime import date

event = Event(name='Conference', date=date(2024, 7, 1))
print(event)
AConference on 2024-07-01
BEvent object
CConference on 07/01/2024
DError: date.strftime not available
Attempts:
2 left
💡 Hint
Check the date formatting inside the __str__ method.
🧠 Conceptual
expert
2:00remaining
Why is defining __str__ important for Django admin and shell usability?
Select the best explanation for why Django models should implement the __str__ method.
AIt provides a readable name for model instances in admin, shell, and logs, improving usability and debugging.
BIt speeds up database queries by caching string values.
CIt automatically creates database indexes on string fields.
DIt prevents Django from raising errors when saving models.
Attempts:
2 left
💡 Hint
Think about how you see model instances in Django admin and shell.

Practice

(1/5)
1. What is the main purpose of defining a __str__ method in a Django model?
easy
A. To create a new database migration
B. To define the database table name
C. To set default values for model fields
D. To provide a readable string representation of the model instance

Solution

  1. Step 1: Understand the role of __str__ in Django models

    The __str__ method returns a string that describes the model instance clearly and simply.
  2. Step 2: Identify what __str__ does not do

    It does not affect database table names, migrations, or default field values.
  3. Final Answer:

    To provide a readable string representation of the model instance -> Option D
  4. Quick Check:

    Purpose of __str__ = readable string [OK]
Hint: Think: How do I want to see this object as text? [OK]
Common Mistakes:
  • Confusing __str__ with database schema settings
  • Using __str__ to set default field values
  • Thinking __str__ creates migrations
2. Which of the following is the correct way to define a __str__ method in a Django model?
easy
A. def __str__(self): return self.name
B. def str(self): return self.name
C. def __str__(self): print(self.name)
D. def __string__(self): return self.name

Solution

  1. Step 1: Recall the exact method name and return type

    The method must be named __str__ and return a string, not print it.
  2. Step 2: Check each option for correctness

    def __str__(self): return self.name correctly defines __str__ and returns self.name. Others have wrong names or use print instead of return.
  3. Final Answer:

    def __str__(self): return self.name -> Option A
  4. Quick Check:

    Correct method name and return string = def __str__(self): return self.name [OK]
Hint: Remember: __str__ must return a string, not print it [OK]
Common Mistakes:
  • Using print instead of return inside __str__
  • Misspelling __str__ method name
  • Defining __string__ or str instead of __str__
3. Given this Django model:
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)

    def __str__(self):
        return f"{self.title} by {self.author}"

book = Book(title='Django Basics', author='Anna')
print(str(book))
What will be printed?
medium
A. Book object (None)
B. Django Basics
C. Django Basics by Anna
D.

Solution

  1. Step 1: Understand the __str__ method output

    The __str__ method returns a formatted string combining title and author.
  2. Step 2: Check what print(str(book)) outputs

    It calls the __str__ method, so it prints "Django Basics by Anna" exactly.
  3. Final Answer:

    Django Basics by Anna -> Option C
  4. Quick Check:

    __str__ output = printed string [OK]
Hint: print(str(object)) shows __str__ return value [OK]
Common Mistakes:
  • Expecting default object representation instead of __str__ output
  • Confusing __repr__ with __str__ output
  • Ignoring f-string formatting in __str__
4. What is wrong with this __str__ method in a Django model?
def __str__(self):
    print(self.name)
medium
A. It should return a string, not print it
B. The method name is incorrect
C. It should raise an exception
D. It should be a class method

Solution

  1. Step 1: Check the method's behavior

    The method uses print instead of returning a string, so it returns None by default.
  2. Step 2: Understand the expected __str__ behavior

    __str__ must return a string to represent the object, not print it.
  3. Final Answer:

    It should return a string, not print it -> Option A
  4. Quick Check:

    __str__ must return string [OK]
Hint: Always return a string in __str__, never print [OK]
Common Mistakes:
  • Using print instead of return
  • Misnaming the method
  • Making __str__ a class method
5. You have a Django model with fields first_name and last_name. You want the admin and print statements to show the full name. Which __str__ method correctly achieves this and handles missing names gracefully?
hard
A. def __str__(self): return self.first_name + ' ' + self.last_name
B. def __str__(self): return f"{self.first_name or ''} {self.last_name or ''}".strip()
C. def __str__(self): return self.first_name if self.first_name else self.last_name
D. def __str__(self): print(f"{self.first_name} {self.last_name}")

Solution

  1. Step 1: Analyze each option for handling missing names

    def __str__(self): return self.first_name + ' ' + self.last_name concatenates directly, which can cause errors if either is None. def __str__(self): return f"{self.first_name or ''} {self.last_name or ''}".strip() uses or '' to avoid None and strips extra spaces. def __str__(self): return self.first_name if self.first_name else self.last_name only returns one name, not full name. def __str__(self): print(f"{self.first_name} {self.last_name}") uses print instead of return.
  2. Step 2: Choose the option that returns full name safely

    def __str__(self): return f"{self.first_name or ''} {self.last_name or ''}".strip() returns a full name string, handles missing values, and returns a clean string.
  3. Final Answer:

    def __str__(self): return f"{self.first_name or ''} {self.last_name or ''}".strip() -> Option B
  4. Quick Check:

    Safe full name string return = def __str__(self): return f"{self.first_name or ''} {self.last_name or ''}".strip() [OK]
Hint: Use or '' and strip() to handle missing fields in __str__ [OK]
Common Mistakes:
  • Concatenating without checking for None
  • Using print instead of return
  • Returning only one field instead of full name
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard