Django 筆記

weixin_33727510發表於2017-10-07

Anacoda裡建立環境:

conda create --name django

切換環境

source activate django

安裝django

conda install -c anaconda django

檢查django是否安裝

python -m django --version

建立工程,一個工程由多個app組成

django-admin startproject myproject

生成的工程目錄結構

3061379-5faa2db90e327d32.png
image.png

執行自帶的伺服器

python manage.py runserver

建立app

django-admin startapp boards

3061379-444966718fbd7db7.png
image.png

將建立的app新增到settings.py

3061379-8650b704284e99d8.png
image.png

在urls.py裡新增處理函式

3061379-11954e7fc191f621.png
image.png

boards/views.py

from django.http import HttpResponse

def home(request):
    return HttpResponse('Hello, World!')

定義模型,每個模型對應資料庫中的table
boards/models.py

from django.db import models
from django.contrib.auth.models import User


class Board(models.Model):
    name = models.CharField(max_length=30, unique=True)
    description = models.CharField(max_length=100)


class Topic(models.Model):
    subject = models.CharField(max_length=255)
    last_updated = models.DateTimeField(auto_now_add=True)
    board = models.ForeignKey(Board, related_name='topics')
    starter = models.ForeignKey(User, related_name='topics')


class Post(models.Model):
    message = models.TextField(max_length=4000)
    topic = models.ForeignKey(Topic, related_name='posts')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(null=True)
    created_by = models.ForeignKey(User, related_name='posts')
    updated_by = models.ForeignKey(User, null=True, related_name='+')

提交修改:

python manage.py makemigrations

python manage.py migrate

開啟shell可以experiment模型

python manage.py shell

模型的一些操作

3061379-9c5d29ce500815ab.png
image.png

建立template資料夾存放htnl模板

3061379-ab53787b1f8a9558.png
image.png
3061379-9cd174d108785be8.png
image.png

建立static資料夾存放靜態檔案

3061379-817f6de681da1184.png
image.png

settings.py新增

3061379-bd2b0f5f800b954e.png
image.png

使用:

3061379-c99cdb6dac5c7359.png
image.png

部署到正式環境時修改settings.py中的STATIC_URL

建立超級使用者

python manage.py createsuperuser

訪問管理介面http://127.0.0.1:8000/admin/

管理介面新增Board的訪問

boards/admin.py

from django.contrib import admin
from .models import Board

admin.site.register(Board)

url(r'^(?P<username>[\w.@+-]+)/$', views.user_profile, name='user_profile')

username作為引數傳入user_profile

{% url %}引用urls.py中name指向的url

{% extends 'base.html' %} 繼承template,重寫{% block %}

表單:

建立forms.py

boards/forms.py

from django import forms
from .models import Topic

class NewTopicForm(forms.ModelForm):
    message = forms.CharField(widget=forms.Textarea(), max_length=4000)

    class Meta:
        model = Topic
        fields = ['subject', 'message']
if  request.method == 'POST':
    form = NewTopicForm(request.POST)
    if form.is_valid():
        topic = form.save()
        return redirect('board_topics', pk=board.pk)
else:
    form = NewTopicForm()
return render(request, 'new_topic.html', {'form': form})

html template中使用form
{{ form.as_p }} or {{ form.as_table}} or {{ form.as_ul }}


建立使用者(sign up):

UserCreationForm

from django.contrib.auth import login as auth_login
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth_login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'signup.html', {'form': form})

sign out:

from django.contrib.auth import views as auth_views

url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),

settings.py新增

3061379-cfb6c833fc0c95d0.png
image.png

login in:

url(r'^login/$', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
3061379-b73c2f21056c6db1.png
image.png

相關文章