Django教程(四)- Django模板及进阶

字数 172阅读 749

目录:

Django模板及进阶
代码操作:

  • home.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板实例</title>
</head>
<body>
    <!--1.显示一个基本的字符串在网页上-->
    <!--{{ string }}-->

    <!--2.基本的 for 循环 和 List内容的显示-->
    <!--{% for i in list %}-->
    <!--{{ i }}-->
    <!--{% endfor %}-->

    <!--3.显示字典中内容-->
    <!--{% for key,value in dict.items %}-->
    <!--{{ key }}:{{ value }}-->
    <!--{% endfor %}-->

    <!--4.在模板进行 条件判断和 for 循环的详细操作:-->
    <!--{% for i in list %}-->
    <!--{{ i }}{% if not forloop.last %},{% endif %}-->
    <!--{% endfor %}-->

    <!--#5.模板上得到视图对应的网址:-->
    <!--<a href="{% url 'h' 4 5 %}" >友情链接</a>-->

    <!--6.模板中的逻辑操作:-->
    <!--{% if var >= 90 %}-->
    <!--成绩优秀-->
    <!--{% elif var >= 80 %}-->
    <!--成绩良好-->
    <!--{% elif var >= 70 %}-->
    <!--成绩一般-->
    <!--{% elif var >= 60 %}-->
    <!--需要努力-->
    <!--{% else %}-->
    <!--不及格-->
    <!--{% endif %}-->

    <!--7.模板中 获取当前网址,当前用户等:-->
    <!--{{ request.user }}-->

    <!--8.过滤器-->
    {{ var|lower }}



</body>
</html>
  • views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,redirect
from temforms import temform
from django.http import HttpResponse

# Create your views here.
# 简单的模板
# def test(request):
#     return render(request,'new.html',)

# 1.显示一个基本的字符串在网页上
# def home(request):
#     string =u'遇见你真是三生有幸❤'
#     return render(request,'home.html',{'string':string})

# 2.基本的 for 循环 和 List内容的显示
# def home(request):
#     list =['L','o','v','e','x','l']
#     return render(request,'home.html',{'list':list})

# 3.显示字典中内容
# def home(request):
#     dict={'name':'中二病控','age':'22','interset':'write'}
#     return render(request,'home.html',{'dict':dict})

# 4.在模板进行 条件判断和 for 循环的详细操作:
# def home(request):
#     list = map(str,range(20))# 一个长度为10的 List,对range(20)各项进行str操作
#     return render(request,'home.html',{'list':list})

#5.模板上得到视图对应的网址:
def add(request,a,b):
    c= int(a)+int(b)
    return HttpResponse(str(c))


#6.模板中的逻辑操作:
# def home(request):
#     return render(request, 'home.html', {'var': 20})

# 7.模板中 获取当前网址,当前用户等:
def home(request):
     return render(request, 'home.html', )
# 8.过滤器
def home(request):
     return render(request, 'home.html', {'var': 'LOVER'})

  • urls.py
from django.conf.urls import include, url
from django.contrib import admin
from . import views

urlpatterns = [
     # url(r'^test/',views.test,),
    url(r'^home/',views.home,),
    url(r'^add/(\d+)/(\d+)/$',views.add,name='h')

]

需求:编写注册提交,“密码”与“确认密码”不一致,显示密码不一样。成功后在另一个页面显示
代码操作:

文件树形图显示
  • ofForm.py
# -*- coding:utf-8 -*-
from django.forms import Form,widgets,fields
from django import forms

class ofForm(Form):
    userName = fields.CharField(max_length=10)
    password = fields.CharField(max_length=10,widget=widgets.PasswordInput)
    repassword = fields.CharField(max_length=10,widget=widgets.PasswordInput)

    def clean(self):
        password = self.cleaned_data['password']
        repassword = self.cleaned_data['repassword']
        if not password == repassword:
            print 'error'
            myerror = 'password is different from repassword,please write again!'
            raise forms.ValidationError(myerror)

        return self.cleaned_data
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<form action="" method="post">
    {% csrf_token %}
    用户名:{{ form.userName }}<br>
    密码:{{ form.password }}<br>
    确认密码:{{ form.repassword }}{{form.non_field_errors}}<br>

    <input type="submit" value="注册">


</form>

</body>
</html>
  • urls.py
from django.conf.urls import url
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^reg/$',views.register)

]
  • views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from ofForms import ofForm
from models import UserModel


# Create your views here.
def register(request):
    if request.method == 'GET':
        form =ofForm.ofForm()
        return render(request,'index.html',{'form':form})
    elif request.method == 'POST':
        form = ofForm.ofForm(request.POST)
        if form.is_valid():
            userModel = UserModel()
            userModel.userName = form.cleaned_data['userName']
            userModel.password = form.cleaned_data['password']
            userModel.save()

            return HttpResponse('数据提交成功!')
        else:
            return render(request,'index.html',{'form':form})

  • models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

# Create your models here.
class UserModel(models.Model):
    userName = models.CharField(max_length=10)
    password = models.CharField(max_length=10)

效果展示:

首页
两次密码一致
两次密码不一致

推荐阅读更多精彩内容