Django#

Project#

Creating a project#

$ django-admin startproject mysites

Creating an app#

$ python manage.py startapp polls

Running Development server#

$ python manage.py runserver

Models#

Creating Models#

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Migrations#

$ python manage.py makemigrations polls
$ python manage.py migrate

Fields#

Integer

models.IntegerField()

Float

models.FloatField()

Char

models.CharField(max_length=None)

Text

models.TextField()

File

models.FileField(upload_to='uploads/')

Email

models.EmailField()

Foreign Key

models.ForeignKey({model_name}, on_delete=models.CASCADE)

Views#

Creating a View#

# views.py
from django.views.generic import ListView
from polls.models import Question

class QuestionListView(ListView):
    model = Question
# urls.py
from django.urls import path
from polls.views import QuestionListView

urlpatterns = [
    path('questions/', QuestionListView.as_view()),
]

Class-based Views#

Generic

View

django.views

Template

TemplateView

django.views.generic

List

ListView

django.views.generic

Detail

DetailView

django.views.generic

Form

FormView

django.views.generic.edit

Create

CreateView

django.views.generic.edit

Delete

DeleteView

django.views.generic.edit

Update

UpdateView

django.views.generic.edit

Administration#

Creating an admin user#

$ python manage.py createsuperuser

Creating a View#

from django.contrib import admin
from .models import Question

admin.site.register(Question)