Labs ICT
Pro Login
← Back to Django Tutorial

Static Files

Simulated Django Environment

views.py
<%- content %>
Project File Tree
📁 myproject/
📁 myproject/
- __init__.py
- settings.py
- urls.py
- wsgi.py
📁 app/
- models.py
- views.py
- urls.py
- admin.py
- forms.py
- apps.py
📁 templates/
📁 static/
📁 manage.py
Quick Reference

Model

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Class-Based View

from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = 'app/post_list.html'
    context_object_name = 'posts'

URL Patterns

from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('post/<int:pk>/', views.post_detail,
         name='post_detail'),
]

Admin

from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'created')
    search_fields = ('title',)

Form

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body']

Template Tags

{% extends "base.html" %}
{% block content %}
  {% for post in posts %}
    <h2>{{ post.title }}</h2>
    <p>{{ post.body }}</p>
  {% endfor %}
{% endblock %}

Signals

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

Settings (INSTALLED_APPS)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'myapp',
]