pip install django | Django 설치 |
django-admin startproject myproject | 프로젝트 생성 |
python manage.py startapp myapp | 앱 생성 |
python manage.py runserver | 서버 실행 |
python manage.py makemigrations | 마이그레이션 생성 |
python manage.py migrate | 마이그레이션 적용 |
python manage.py createsuperuser | 관리자 생성 |
python manage.py shell | Django 셸 |
python manage.py collectstatic | 정적 파일 수집 |
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title CharField(max_length=100)
TextField()
IntegerField()
FloatField()
BooleanField(default=False)
DateField() / DateTimeField()
EmailField()
URLField()
FileField(upload_to="files/")
ImageField(upload_to="images/")
ForeignKey(Model, on_delete=models.CASCADE)
ManyToManyField(Model)
OneToOneField(Model, on_delete=models.CASCADE) Model.objects.all()
Model.objects.filter(field=value)
Model.objects.exclude(field=value)
Model.objects.get(pk=1)
Model.objects.first() / .last()
Model.objects.order_by("-created")
Model.objects.values("field1", "field2")
Model.objects.annotate(count=Count("id"))
Model.objects.select_related("fk_field")
Model.objects.prefetch_related("m2m_field") from django.shortcuts import render, get_object_or_404, redirect
def article_list(request):
articles = Article.objects.all()
return render(request, "articles/list.html", {"articles": articles})
def article_detail(request, pk):
article = get_object_or_404(Article, pk=pk)
return render(request, "articles/detail.html", {"article": article}) from django.views.generic import ListView, DetailView, CreateView
from django.urls import reverse_lazy
class ArticleListView(ListView):
model = Article
template_name = "articles/list.html"
context_object_name = "articles"
paginate_by = 10
class ArticleCreateView(CreateView):
model = Article
fields = ["title", "content"]
success_url = reverse_lazy("article_list") from django.urls import path, include
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("articles/", views.article_list, name="article_list"),
path("articles/<int:pk>/", views.article_detail, name="article_detail"),
path("articles/<slug:slug>/", views.article_by_slug, name="article_slug"),
path("api/", include("api.urls")),
] {{ variable }}
{{ article.title|truncatewords:30 }}
{{ date|date:"Y-m-d" }}
{% if condition %}...{% endif %}
{% for item in items %}...{% endfor %}
{% url "view_name" pk=1 %}
{% include "partial.html" %}
{% extends "base.html" %}
{% block content %}...{% endblock %}