Django Quick Start
1. Preparation
Firstly, we can install django and create our project as follows.
# to install django framework
pip install django
pip install djangorestframework
# create our applications
django-admin startproject mysite
cd mysite
python managy.py startapp myapp
To test the project, we can use “runserver” command.
python manage.py runserver
2. Models
In the file “myapp/models.py”, we can create some models to specify the layout of our database.
from django.db import models
class User(models.Model):
name = models.CharField(max_length=32)
gender = models.BooleanField()
birth = models.DateField()
profile = models.CharField(max_len=128)
def __str__(self):
return self.name
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_len=128)
content = models.TextField()
pub_date = DateTimeField()
def __str__(self):
return self.title
For more details about “Field”, please refer to Field.
3. Views
In the directory “myapp/views.py”, we can define some views to display different pages.
from django.shortcuts import render, HttpResponse
def index(request):
return HttpResponse("Welcome page.")
def user_page(request):
return render(request, "user_page.html", {"arg": "111"})
# 1. django will look for "html" in "myapp/templates"
# 2. or, it will go into other "apps" directory based on registerd order.
4. Static & Extends
To use static files sunch as images, CSS, JS, we can put them into “static” directory.
{% raw %}
{% load static %}
...
<div>
<img src="{% static 'img/1.png' %}">
</div>
...
<!-- extends the contents of 'layout.html' -->
{% extends "layout.html" %}
{% block content %}
...
{% endblock %}
{% endraw %}
5. URL
# myapp/urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
6. Setting
# mysite/settings.py
INSTALLED_APPS = [
...
'myapp.apps.AppConfig',
]
7. Admin
python manage.py createsuperuser
...
# myapp/admin.py
from django.contrib import admin
from .models import Article
admin.site.register(Article)
8. ModelForm
from django import forms
class ArticleModelForm(forms.ModelForm):
class Meta:
model = Article
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs = {"class": "form-control", "placeholder": field.label}
def new(request):
if request.method == "GET":
form = ArticleModelForm()
return render(request, "new.html", {'form': form})
form = ArticleModelForm(data=request.POST)
if form.is_valid():
form.save()
return redirect("/")
return render(request, "new.html", {'form': form}) # with error information
def edit(request, pk):
row = Article.objects.filter(id=pk).first()
if request.method == "GET":
form = ArticleModelForm(instance=row)
return render(request, "edit.html", {"form": form})
form = ArticleModelForm(data=request.POST, instance=row) # update instead of create
if form.is_valid():
form.save()
return redirect("/")
return render(request, "new.html", {'form': form}) # with error information
def delete(request, pk):
Article.objects.filter(id=pk).delete()
return redirect("/")
<!-- new.html -->
{% extends "layout.html" %}
{% block content %}
<h1>Create New Article</h1>
<form method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group" >
<label>{{field.label}}:</label>
{{ field }}
<span style="color:red;">{{ field.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}