Python全棧之路-Django(十二)

1 相親網

1.1 需求分析

1 登陸,基於Session,裝飾器html

2 數據表:python

男生表:數據庫

id    username  password

女生表django

id    username  password

男生女生關係表session

id  nid  nid

3 功能:app

登陸頁:函數

用戶名:
密碼:
性別:
一週免登陸:checkbox
    
session[id]
session[xingbie]

查看異性列表:post

session[xingbie]

查看與本身有染得異性姓名列表url

1.2 簡單示例:

urls.pycode

from django.conf.urls import url
from django.contrib import admin
from app01.views import account,love

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login.html/', account.login),
    url(r'^index.html/', love.index),
    url(r'^logout.html/', account.logout),
    url(r'^others.html/', love.others),
]

app01.models.py

from django.db import models


class Boy(models.Model):
    nickname = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)


class Girl(models.Model):
    nickname = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)


class B2G(models.Model):
    b = models.ForeignKey(to='Boy',to_field='id')
    g = models.ForeignKey(to='Girl',to_field='id')

app01.views.account.py

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/7/6
from django.shortcuts import HttpResponse,render,redirect
from app01 import models

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    else:
        user = request.POST.get('username')
        pwd = request.POST.get('password')
        gender = request.POST.get('gender')
        rmb = request.POST.get('rmb')
        # 性別判斷
        if gender == '1':
            obj = models.Boy.objects.filter(username=user,password=pwd).first()
        else:
            obj = models.Girl.objects.filter(username=user,password=pwd).first()

        if not obj:
            # 未登陸成功
            return render(request,'login.html',{'msg':'用戶名或密碼錯誤'})
        else:
            # request.session['user_id'] = obj.id
            # request.session['gender'] = gender
            # request.session['username'] = user
            # 大字典寫法
            request.session['user_info'] = {
                'user_id':  obj.id,
                'gender':   gender,
                'username': user,
                'nickname': obj.nickname
            }
            return redirect('/index.html/')


def logout(request):
    # 刪除Session 會刪除數據庫中的數據
    # request.session.delete(request.session.session_key)
    # 只刪除Cookie 不會刪除數據庫中的數據
    request.session.clear()

    return redirect('/login.html/')

app01.views.love.py

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/7/6

from django.shortcuts import HttpResponse,render,redirect
from app01 import models

def index(request):
    if not request.session.get('user_info'):
        return redirect('/login.html')
    else:
        gender = request.session.get('user_info').get('gender')
        if gender == '1':
            user_list = models.Girl.objects.all()
            return render(request, 'index.html', {'user_list': user_list})
        else:
            user_list = models.Boy.objects.all()

            return render(request,'index.html', {'user_list': user_list})

def others(request):
    """
    獲取與當前用戶有關係的異性
    :param request: 
    :return: 
    """
    current_user_id = request.session.get('user_info').get('user_id')
    gender = request.session.get('user_info').get('gender')
    if gender == '1':
        user_list = models.B2G.objects.filter(b_id=current_user_id).values('g__nickname')
    else:
        user_list = models.B2G.objects.filter(b_id=current_user_id).values('b__nickname')
    return render(request, 'others.html',{'user_list': user_list})

templates.login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login.html/" method="post">
    {% csrf_token %}
    <p>用戶:<input type="text" name="username"></p>
    <p>密碼:<input type="password" name="password"></p>
    <p>
        性別:
        男<input type="radio" name="gender" value="1">
        女<input type="radio" name="gender" value="2">
    </p>
    <p><input type="checkbox" name="rmb" value="0">一個月免登錄</p>
    <input type="submit" value="提交">{{ msg }}

</form>
</body>
</html>

templates.index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% include 'user_header.html' %}
    <h3>異性列表</h3>
    <a href="/others.html">和我有關係的異性</a>

<ul>
    {% for user in user_list %}
    <li>{{ user.nickname }}</li>
    {% endfor %}

</ul>
</body>
</html>

templates.others.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% include 'user_header.html' %}
<h1>有關係的異性列表</h1>
<ul>
{% for user in user_list %}
    <li>{{ user.b__nickname }}{{ user.g__nickname }}</li>
{% endfor %}
</ul>

</body>
</html>
templates.user_header.html
<h1>當前用戶:{{ request.session.user_info.nickname }}</h1>
<a href="/logout.html">註銷</a>

2 自關聯related_name

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/', views.test),
]

app01.models.py

from django.db import models


class UserInfo(models.Model):
    nickname = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    gender_choices = (
        (1, '男'),
        (2, '女'),
    )
    gender = models.IntegerField(choices=gender_choices)


# relate_query_name  反向關聯別名,保留_set
# obj對象男.b_set.all()
# obj對象女.a_set.all()
# relate_name(推薦) 反向關聯別名
# obj對象男.b.all()
# obj對象女.a.all()
class U2U(models.Model):
    # g = models.ForeignKey('UserInfo', related_query_name='a')
    # b = models.ForeignKey('UserInfo', related_query_name='b')
    g = models.ForeignKey('UserInfo', related_name='boys')
    b = models.ForeignKey('UserInfo', related_name='girls')

app01.views.py

from django.shortcuts import render, HttpResponse
from app01 import models
# Create your views here.


def test(request):
    # models.U2U.objects.create(b_id=2, g_id=6)
    # models.U2U.objects.create(b_id=1, g_id=6)
    # models.U2U.objects.create(b_id=1, g_id=4)
    # models.U2U.objects.create(b_id=1, g_id=5)

    # boy = models.UserInfo.objects.filter(gender=1, id=2).first()
    # girl = models.UserInfo.objects.filter(gender=2, id=6).first()
    # models.U2U.objects.create(b=boy, g=girl)

    xz = models.UserInfo.objects.filter(id=1).first()
    result = xz.girls.all()  # <QuerySet [<U2U: U2U object>, <U2U: U2U object>, <U2U: U2U object>]>
    for u in result:
        print(u.g.nickname)
    return HttpResponse('...')

3 manytomany自關聯

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/', views.test),
]

app01.models.py

from django.db import models


class UserInfo(models.Model):
    nickname = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    gender_choices = (
        (1, '男'),
        (2, '女'),
    )
    gender = models.IntegerField(choices=gender_choices)
    m = models.ManyToManyField('UserInfo')

app01.views.py

from django.shortcuts import render, HttpResponse
from app01 import models
# Create your views here.


def test(request):
    # 查男生(正向操做)
    # xz = models.UserInfo.objects.filter(id=1).first()
    # u = xz.m.all()  # <QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
    # for row in u:
    #     print(row.nickname)

    # 查女生(反向操做)
    mr = models.UserInfo.objects.filter(id=4).first()
    v = mr.userinfo_set.all()
    for row in v:
        print(row.nickname)

    return HttpResponse('...')

4 ForeignKey自關聯

class Comment(models.Model):
    """
    評論表
    """
    news_id = models.IntegerField()            # 新聞ID
    content = models.CharField(max_length=32)  # 評論內容
    user = models.CharField(max_length=32)     # 評論者
    reply = models.ForeignKey('Comment',null=True,blank=True,related_name='xxxx')
"""
    新聞ID                         reply_id
1   1        別比比    root         null
2   1        就比比    root         null
3   1        瞎比比    shaowei      null
4   2        寫的正好  root         null
5   1        拉倒吧    由清濱         2
6   1        拉倒吧1    xxxxx         2
7   1        拉倒吧2    xxxxx         5
"""
"""
新聞1
    別比比
    就比比
        - 拉倒吧
            - 拉倒吧2
        - 拉倒吧1
    瞎比比
新聞2:
    寫的正好
"""

5 中間件

m1.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse

class Middle1(MiddlewareMixin):
    def process_request(self, request):
        print('m1.process_request')
        # return HttpResponse('不要再往下執行了')  # 這裏返回值後,下面的中間件和函數將不會被執行

    def process_response(self, request, response):
        print('m1.process_response')
        return response

class Middle2(MiddlewareMixin):
    def process_request(self, request):
        print('m2.process_request')
        # return HttpResponse('不要再往下執行了')  # 這裏返回值後,下面的中間件和函數將不會被執行

    def process_response(self, request, response):
        print('m2.process_response')
        return response

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'm1.Middle1',
    'm1.Middle2',
]
相關文章
相關標籤/搜索