美文网首页
初探Django创建前台(二)

初探Django创建前台(二)

作者: Treehl | 来源:发表于2018-02-03 16:05 被阅读0次

    上一篇创建了Django的后台,今天来创建前台视图

    创建Django首页视图

    编辑视图函数views.py

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    
    
    def index(request):
        # render()构造HttpResponse
        # context: 将index.html中的变量替换为context传递的变量,
        # {{ words}}替换为'words'的值
        words = 'World!'
        return render(request, 'index.html', context={'words': words})
    

    创建完成后,在django_student同级目录下创建templates文件夹并创建index.html文件

    ├─django_student
    │  │  admin.py
    │  │  admin.pyc
    │  │  apps.py
    │  │  forms.py
    │  │  forms.pyc
    │  │  models.py
    │  │  models.pyc
    │  │  tests.py
    │  │  views.py
    │  │  views.pyc
    │  │  __init__.py
    │  │  __init__.pyc
    │  │
    │  ├─migrations
    │  │      0001_initial.py
    │  │      0001_initial.pyc
    │  │      0002_student_home_phone.py
    │  │      0002_student_home_phone.pyc
    │  │      __init__.py
    │  │      __init__.pyc
    │  │
    │  └─templates
    │          index.html
    │          __init__.py
    

    我们在index.html内写入如下代码, {{ words }}是模板变量,在views.py中指定了context来传递模板变量的值

    <!DOCTYPE html>
    <html>
        <head>
            <title>学员管理系统</title>
        </head>
        <body>
            Hello {{ words }}!
        </body>
    </html>
    

    接下来,还需要再配置下django_student/urls.py,让用户访问url时把数据发送到定义的index这个视图,使用正则表达式来匹配

    <!DOCTYPE html>
    <html>
    from django.conf.urls import url
    from django.contrib import admin
    from student.views import index
    
    
    urlpatterns = [
        url(r'^$', index, name='index'),
        url(r'^admin/', admin.site.urls),
    ]
    
    

    开启服务,访问下网页,会出现Hello,World!

    python manage.py runserver

    输出数据

    将后台数据渲染到页面上,现在admin中创建几条数据
    修改views.py

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    
    from .models import Student
    
    
    def index(request):
        # Student.objects.all(): 获取所有数据
        students = Student.objects.all()
        return render(request, 'index.html', context={'students': students})
    
    

    修改index.html中代码
    { % % }是模板标签,先用for循环将students一个个取出来
    {% endfor %}:循环结束了
    {{ student.get_status_display }}:我们在models.py中定义了status字段,设置了choices来获取对应的值
    我们还可以在index.html中设置admin后台链接

    <!DOCTYPE html>
    <html>
        <head>
            <title>学员管理系统</title>
        </head>
        <body>
            <a href="/admin/">Admin</a>
            <ul>
            {% for student in students %}
                <li>{{ student.name }} - {{ student.get_status_display }}</li>
            {% endfor %}
            </ul>
        </body>
    </html>
    

    再次运行服务,查看网页


    django_test2.png

    提交数据

    这里我们用上了表单Form,在views.py同级目录下创建forms.p

    # coding:utf-8
    from __future__ import unicode_literals
    
    from django import forms
    
    from .models import Student
    
    
    class StudentForm(forms.Form):
        name = forms.CharField(label='姓名', max_length=128)
        sex = forms.ChoiceField(label='性别', choices=Student.SEX_ITEMS)
        profession = forms.CharField(label='职业', max_length=128)
        email = forms.EmailField(label='邮箱', max_length=128)
        qq = forms.CharField(label='QQ', max_length=128)
        phone = forms.CharField(label='手机', max_length=128)
    

    代码和定义models.py很相似,可以使用继承ModelForm来缩小代码量

    # coding:utf-8
    from __future__ import unicode_literals
    
    from django import forms
    
    from .models import Student
    
    
    class StudentForm(forms.ModelForm):
        class Meta:
            model = Student
            fields = (
                'name', 'sex', 'profession',
                'email', 'qq', 'phone'
            )
    

    接下来我们需要修改视图函数views.py,在页面中展示表单Form,对于提交的数据做校验,通过后存入数据库

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    
    from django.http import HttpResponseRedirect
    from django.urls import reverse
    from django.shortcuts import render
    
    from .models import Student
    from .forms import StudentForm
    
    
    def index(request):
        # render()构造HttpResponse
        # context: 将index.html中的变量替换为context传递的变量,
        # {{ words}}替换为'words'的值
        # form.cleaned_data:是Django的form是对用户提交的数据根据字段类型做完转换后的结果
        # words = 'World'
        students = Student.objects.all()
        if request.method == 'POST':
            form = StudentForm(request.POST)
            if form.is_valid():
                cleaned_data = form.cleaned_data
                student = Student()
                student.name = cleaned_data['name']
                student.sex = cleaned_data['sex']
                student.email = cleaned_data['email']
                student.profession = cleaned_data['profession']
                student.qq = cleaned_data['qq']
                student.phone = cleaned_data['phone']
                student.save()
                # reverse():urls.py中和index对应
                # HttpResponseRedirect()重定向到我们的首页
                return HttpResponseRedirect(reverse('index'))
        else:
            form = StudentForm()
    
        context = {
            'students': students,
            'form': form,
        }
    
        # return render(request, 'index.html', context={'words': words})
        return render(request, 'index.html', context=context)
    
    

    接下来要把form传入模板中,才能在页面显示表单
    {% csrf_token %}:设置安全,跨站伪造请求攻击

    <!DOCTYPE html>
    <html>
        <head>
            <title>学院管理系统</title>
        </head>
        <body>
            <a href="/admin/">Admin</a>
            <ul>
                {% for student in students %}
                    <li>{{ student.name }} - {{ student.get_status_display }}</li>
                {% endfor %}
            </ul>
            <hr/>
            <form action="/" method="post">
                {% csrf_token %}
                {{ form }}
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>
    
    
    

    校验数字

    以上步骤完成后,我们发现电话和QQ输入字符没有限制,可以使用IntegerField()来设置字符类型,或者使用clean来做限制,修改forms.py

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django import forms
    from .models import Student
    
    
    '''
    class StudentForm(forms.Form):
        name = forms.CharField(label='姓名', max_length=128)
        sex = forms.ChoiceField(label='性别', choices=Student.SEX_ITEMS)
        profession = forms.CharField(label='职业', max_length=128)
        email = forms.EmailField(label='邮箱', max_length=128)
        qq = forms.CharField(label='QQ', max_length=128)
        phone = forms.CharField(label='手机', max_length=128)
    '''
    # 通过继承ModelForm,来写下我们需要展示的fields
    class StudentForm(forms.ModelForm):
        def clean_qq(self):
            cleaned_data = self.cleaned_data['qq']
            # isdigit():验证是否是数字
            if not cleaned_data.isdigit():
                raise forms.ValidationError('必须是数字!')
            return int(cleaned_data)
    
        def clean_phone(self):
            cleaned_data = self.cleaned_data['phone']
            if not cleaned_data.isdigit():
                raise forms.ValidationError('必须是数字!')
            return int(cleaned_data)
    
    
    
        class Meta:
            model = Student
            fields = (
                'name', 'sex', 'profession',
                'email', 'qq', 'phone',
            )
    
    

    运行服务

    python manage.py runserver


    django_test3.png

    修改为数字再次提交就OK了

    相关文章

      网友评论

          本文标题:初探Django创建前台(二)

          本文链接:https://www.haomeiwen.com/subject/pimuzxtx.html