Sitemap

DRY and SoC in Django..

2 min readMay 3, 2025

--

what they mean, why they matter, and how they help you build clean, modular apps.

What is DRY?

DRY stands for Don’t Repeat Yourself.
It means: “Write code once, use it many times.”

Why it matters:

  • Less code = fewer bugs
  • Easy to update (change in one place updates everywhere).
  • Cleaner, shorter files

🛠 How Django helps you follow DRY:

  • Templates: Use Jinja tags{% extends %} and {% include %} so you don’t repeat HTML.
  • Forms and Models: Write model fields once, reuse them in forms and serializers.
  • Generic views: Use ListView, CreateView, etc., instead of writing the same view code again and again.
  • Middleware and Decorators: Handle common logic (like authentication or logging) once across multiple views.

What is SoC?

SoC stands for Separation of Concerns. It means: “Each part of your app should have one job only.”

Why it matters:

  • Easier to understand: Each file or function does just one thing
  • Easier to test and debug
  • Helps team members work on different parts without conflicts

🛠 How Django helps with SoC:

  • Apps: Break your project into small apps like users, orders, payments. Each handles its own task.
  • Views, Models, Templates: Logic (views), data (models), and UI (templates) are in separate files.
  • Service layer (optional): Put complex business logic in services.py to keep views clean.
  • Serializers (in DRF): Separate data conversion from views and models

🔧 How DRY + SoC make Django modular

Django already encourages modular structure:

project/
└── users/
├── models.py
├── views.py
├── urls.py
└── forms.py
└── payments/
└── orders/

Now when you apply DRY and SoC:

  • You reuse code instead of repeating it across apps
  • You separate logic by feature, not just by file type
  • Your code stays clean, easy to change, and scalable

Example :

Let’s say you send a welcome email when a user signs up. Instead of writing the email logic directly in the view:

# BAD: View doing too much
def signup_view(request):
...
send_mail(...) # sending email here is not SoC
# GOOD: Separated concern
# services.py
def send_welcome_email(user):
send_mail(...)

# views.py
from .services import send_welcome_email

def signup_view(request):
...
send_welcome_email(user)

Now the email logic is reusable and easier to test. That’s SoC + DRY in action.

Get Farhan Mahmood’s stories in your inbox

Join Medium for free to get updates from this writer.

What are some of your favorite ways to keep your Django code DRY and well-separated? Share your tips and experiences in the comments below — let’s learn and build better applications together!

--

--

Farhan Mahmood
Farhan Mahmood

Written by Farhan Mahmood

Farhan Mahmood | Software Engineer | Technical Educator. Building with Python, PSQL, React and MongoDB. I share insights on full-stack development & algorithms.