Django Step-by-Step Process

  1. Define or Update the Model
    • Location: models.py
    • Action: Add fields, relationships, constraints, and readable string output.
    • Example:
      from django.conf import settings
      from django.db import models
      
      class Post(models.Model):
          title = models.CharField(max_length=200)
          content = models.TextField()
      
          def __str__(self):
              return self.title
      
      class Comment(models.Model):
          post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
          author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
          content = models.TextField()
          created_at = models.DateTimeField(auto_now_add=True)
      
          class Meta:
              ordering = ['created_at']
      
          def __str__(self):
              return f'Comment by {self.author} on {self.post}'
  2. Create and Review Migrations
    • Command: python manage.py makemigrations
    • Purpose: Generates migration files based on model changes.
    • Action: Review generated files before applying them, especially for field defaults, indexes, constraints, and relationship changes.
  3. Apply Migrations
    • Commands: python manage.py migrate --plan then python manage.py migrate
    • Purpose: Shows the planned operations, then updates the database schema.
  4. Register the Model in Admin
    • Location: admin.py
    • Action: Register the model and add list/search configuration where useful.
    • Example:
      from django.contrib import admin
      from .models import Comment, Post
      
      @admin.register(Post)
      class PostAdmin(admin.ModelAdmin):
          list_display = ['title']
          search_fields = ['title', 'content']
      
      @admin.register(Comment)
      class CommentAdmin(admin.ModelAdmin):
          list_display = ['post', 'author', 'created_at']
          search_fields = ['content', 'author__username']
  5. Create or Update Forms
    • Location: forms.py
    • Action: Use a form when the feature accepts user input.
    • Example:
      from django import forms
      from .models import Comment
      
      class CommentForm(forms.ModelForm):
          class Meta:
              model = Comment
              fields = ['content']
  6. Create or Update Views
    • Location: views.py
    • Action: Fetch objects safely, validate forms, and redirect after successful POST requests.
    • Example:
      from django.contrib.auth.decorators import login_required
      from django.shortcuts import get_object_or_404, redirect, render
      from .forms import CommentForm
      from .models import Post
      
      @login_required
      def post_detail(request, post_id):
          post = get_object_or_404(Post, pk=post_id)
      
          if request.method == 'POST':
              form = CommentForm(request.POST)
              if form.is_valid():
                  comment = form.save(commit=False)
                  comment.post = post
                  comment.author = request.user
                  comment.save()
                  return redirect('post_detail', post_id=post.pk)
          else:
              form = CommentForm()
      
          return render(request, 'blog/post_detail.html', {
              'post': post,
              'form': form,
          })
  7. Wire URLs
    • Location: urls.py
    • Action: Route requests to the view and give the pattern a stable name.
    • Example:
      from django.urls import path
      from . import views
      
      urlpatterns = [
          path('posts/<int:post_id>/', views.post_detail, name='post_detail'),
      ]
  8. Update Templates
    • Location: templates/blog/post_detail.html
    • Action: Render existing data, display validation errors, and protect POST forms with CSRF tokens.
    • Example:
      <h1>{{ post.title }}</h1>
      <p>{{ post.content }}</p>
      
      <h2>Comments</h2>
      {% for comment in post.comments.all %}
          <p><strong>{{ comment.author }}</strong>: {{ comment.content }}</p>
      {% empty %}
          <p>No comments yet.</p>
      {% endfor %}
      
      <h2>Add a Comment</h2>
      <form method="post">
          {% csrf_token %}
          {{ form.as_p }}
          <button type="submit">Submit</button>
      </form>
  9. Run Checks and Tests
    • Commands: python manage.py check and python manage.py test
    • Action: Confirm the system check and test suite pass before shipping.
  10. Commit Changes
    • Action: Commit the model, migrations, admin, form, view, URL, template, and test changes together when they form one feature.