Bird
0
0

You want to automatically set a model's slug field based on its title before saving, but only if the slug is empty. Which signal and approach is best?

hard📝 lifecycle Q15 of 15
Django - Signals
You want to automatically set a model's slug field based on its title before saving, but only if the slug is empty. Which signal and approach is best?
AUse a form validation method to set <code>slug</code> before saving
BUse <code>post_save</code> signal to update <code>slug</code> after saving the instance
COverride the model's <code>save()</code> method and set <code>slug</code> after calling <code>super().save()</code>
DUse <code>pre_save</code> signal to check if <code>slug</code> is empty and set it from <code>title</code>
Step-by-Step Solution
Solution:
  1. Step 1: Identify when to set slug

    The slug should be set before saving to ensure it is stored correctly in the database.
  2. Step 2: Choose the right signal

    pre_save runs before saving, allowing modification of fields like slug before the database write.
  3. Step 3: Why not post_save or save override

    post_save runs after saving, so changing slug then requires another save. Overriding save() is possible but pre_save keeps logic separate and clean.
  4. Final Answer:

    Use pre_save signal to check if slug is empty and set it from title -> Option D
  5. Quick Check:

    Set fields before save with pre_save [OK]
Quick Trick: Modify fields before saving with pre_save signal [OK]
Common Mistakes:
MISTAKES
  • Setting slug after saving causing extra saves
  • Overriding save() but setting slug too late
  • Using form validation which may not cover all saves

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes