Django views are functions (or classes) that branch on HTTP method, user permissions, and validation results. Loops and conditionals appear in management commands, data migrations, and template logic.
Control flow essentials
if/elif/else— permission checks, method dispatch (if request.method == "POST")forloops — iterate querysets, build lists for templatestry/except— handleDoesNotExist, validation errors
Functions in Django
def publish_status(article):
if article.get("published"):
return "live"
return "draft"
Keep views thin—extract reusable logic into utility functions or model methods.
Important interview questions and answers
- Q: Where to put business logic?
A: Prefer model methods or service modules over bloated views—easier to test and reuse. - Q: Early return in views?
A: Common pattern—return redirect or 404 immediately instead of deep nesting. - Q: List comprehension vs loop?
A: Comprehensions are concise for simple transforms; use loops when logic is complex.
Self-check
- How do you handle GET vs POST in a function-based view?
- When should logic move out of a view into a model method?