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#
Documentation: https://docs.djangoproject.com/en/4.1/ref/models/fields/
Integer |
|
Float |
|
Char |
|
Text |
|
File |
|
|
|
Foreign Key |
|
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#
Inspector: https://ccbv.co.uk
Generic |
|
|
Template |
|
|
List |
|
|
Detail |
|
|
Form |
|
|
Create |
|
|
Delete |
|
|
Update |
|
|
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)