ModelForm验证实例

程序目录

 

models.py

from django.db import models

# Create your models here.
class UserType(models.Model):
    caption=models.CharField(max_length=32)


class UserGroup(models.Model):
    name=models.CharField(max_length=32)


class UserInfo(models.Model):
    username=models.CharField(max_length=32,verbose_name="用户名")
    email=models.EmailField()
    user_type=models.ForeignKey(to='UserType',to_field='id',on_delete=models.CASCADE)
    u2g=models.ManyToManyField(UserGroup)

 

 

 

urls.py

"""s14_day24 URL Configuration

"""
from django.contrib import admin
from django.urls import path
from app01 import views
from django.conf.urls import url
urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('user_list/', views.user_list),
    url('^edit-(\d+)/', views.user_edit),
    url('^ajax/$', views.ajax),
    url('^ajax_json/$', views.ajax_json),
    url('^upload/$', views.upload),
    url('^upload_file/$', views.upload_file),
    url('^kind/$', views.kind),
    url('^upload_img/$', views.upload_img),
    url('^file_manager/$', views.file_manager),
]

 

 

views.py

from django.shortcuts import render,HttpResponse,redirect
from django import forms
from django.forms import fields as field
# Create your views here.
from app01 import models
from django.forms import widgets as fwidget
class UserInfoModelForm(forms.ModelForm):

    is_rmb=field.CharField(widget=fwidget.CheckboxInput())

    class Meta:
        model=models.UserInfo #去哪个类获取字段
        fields='__all__'  #代指所有字段
        # fields=['username'] #只获取uername列
        # exclude=['username'] #排除username 别的都获取
        labels={
            'username':'用户',
            'email':'邮箱',
        }
        help_texts={
            'username':'帮助->输入用户名'
        }
        widgets={
            'username':fwidget.Textarea(attrs={'class':'c1'})
        }
        error_messages={
            '__all__':{

            },
            'email':{
                'required':'邮箱不能为空',
                'invalid':'邮箱格式错误'
            }
        }
        field_classes={
            # 'email':field.URLField
        }

    def clean_username(self):
        old=self.cleaned_data['username']
        return old

class UserInfoForm(forms.Form):
    username=field.CharField(max_length=32)
    email=field.EmailField()
    user_type=field.ChoiceField(
        choices=models.UserType.objects.values_list('id','caption')
    )
    def __init__(self,*args,**kwargs):#更新
        super(UserInfoForm,self).__init__(*args,**kwargs)
        self.fields['user_type'].choices=choices=models.UserType.objects.values_list('id','caption')


def index(request):
    if request.method=="GET":
        obj=UserInfoModelForm()
        return render(request,'index.html',{'obj':obj})
    elif request.method=="POST":
        obj=UserInfoModelForm(request.POST)
        if obj.is_valid():
            # obj.save() #当前类和many_to_many都会保存
            instance=obj.save(False)
            instance.save() #只会保存当前的类,不会保存many_to_many
            obj.save_m2m() #保存many_to_many
        # print(obj.is_valid())
        # print(obj.cleaned_data)
        # print(obj.errors.as_json())
        # models.UserInfo.objects.create(**obj.cleaned_data)
        return render(request,'index.html',{'obj':obj})



def user_list(request):
    li=models.UserInfo.objects.all().select_related('user_type') #关联外键 一对多
    return render(request,'user_list.html',{'li':li})


def user_edit(request,nid):
    # 获取当前id对象的用户信息
    #显示用户已经存在的数据
    if request.method=="GET":
        user_obj=models.UserInfo.objects.filter(id=nid).first()
        mf=UserInfoModelForm(instance=user_obj) #关联多对多
        return render(request, 'user_edit.html',{'mf':mf,'nid':nid})

    elif request.method=='POST':
        user_obj = models.UserInfo.objects.filter(id=nid).first()
        mf=UserInfoModelForm(request.POST,instance=user_obj)  #request.POST  前台传递数据到后台 user_obj many_to_many都传进来 增加obj不加instance
        if mf.is_valid():
            mf.save()
        else:
            print(mf.errors.as_json())
        return render(request, 'user_edit.html', {'mf': mf, 'nid': nid})




def ajax(request):
    return render(request,'ajax.html')


def ajax_json(request):
    print(request.POST)
    ret={'status':True,'data':request.POST.get('username')}
    import json
    # return HttpResponse(json.dumps(ret),status=404,reason="Not Found")
    return HttpResponse(json.dumps(ret))


def upload(request):
    return render(request,'upload.html')

def upload_file(request):
    username=request.POST.get('username')
    fafafa=request.FILES.get('fafafa')
    import os
    img_path=os.path.join('static/image/',fafafa.name)
    print(username,fafafa.name)
    with open(img_path,'wb') as f:
        for item in fafafa.chunks():
            f.write(item)

    ret = {'status': True, 'data': img_path}
    import json
    # return HttpResponse(json.dumps(ret),status=404,reason="Not Found")
    return HttpResponse(json.dumps(ret))


def kind(request):
    return render(request,'kind.html')

import json
def upload_img(request):
    request.GET.get('dir')
    #获取文件保存
    dic = {
        'error': 0,
        'url': '/static/image/IMG_2236.JPG',
        'message': '错误了...'
    }
    return HttpResponse(json.dumps(dic))

import os,time
def file_manager(request): #文件空间管理
    """
    文件管理
    :param request:
    :return:
    """
    dic = {}
    root_path = 'D:/python_study/s14_day24/static'
    static_root_path = '/static/'
    request_path = request.GET.get('path')
    if request_path:
        abs_current_dir_path = os.path.join(root_path, request_path)
        move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
        dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path

    else:
        abs_current_dir_path = root_path
        dic['moveup_dir_path'] = ''

    dic['current_dir_path'] = request_path
    dic['current_url'] = os.path.join(static_root_path, request_path)

    file_list = []
    for item in os.listdir(abs_current_dir_path):
        abs_item_path = os.path.join(abs_current_dir_path, item)
        a, exts = os.path.splitext(item)
        is_dir = os.path.isdir(abs_item_path)
        if is_dir:
            temp = {
                'is_dir': True,
                'has_file': True,
                'filesize': 0,
                'dir_path': '',
                'is_photo': False,
                'filetype': '',
                'filename': item,
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
            }
        else:
            temp = {
                'is_dir': False,
                'has_file': False,
                'filesize': os.stat(abs_item_path).st_size,
                'dir_path': '',
                'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
                'filetype': exts.lower().strip('.'),
                'filename': item,
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
            }

        file_list.append(temp)
    dic['file_list'] = file_list
    return HttpResponse(json.dumps(dic))

 

 

index.py

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <form action="/index/" method="post">
        {% csrf_token %}
        {{ obj.as_p }}
        <input type="submit" value="提交">
    form>
body>
html>

 

 

 

user_list.html

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <ul>
        {% for row in li %}
            <li>{{ row.username }} - {{ row.user_type.caption }}-<a href="/edit-{{ row.id }}/">编辑a>li>
        {% endfor %}
    ul>
body>
html>

 

 

 

ajax.html

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
{#    {% csrf_token %}#}
    <input type="text">
    <input type="button" value="Ajax1" οnclick="Ajax1()">

    

    <form action="/ajax_json/" method="post" target="ifm1">  
        <iframe id="ifm1" name="ifm1" >iframe>
        <input type="text" name="username">
        <input type="text" name="email">
        <input type="submit" οnclick="submitForm();" value="Form提交">
    form>

    <script type="text/javascript" src="/static/jquery-1.12.4.js">script>
    <script>
         function getXHR(){
            var xhr = null;
            if(XMLHttpRequest){
                xhr = new XMLHttpRequest();
            }else{
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xhr;
        }

        function Ajax1() {
            var x_h_r=new getXHR(); //XMLHttpRequest兼容性操作
            x_h_r.open('POST','/ajax_json/',true);
            x_h_r.onreadystatechange=function () {
              if (x_h_r.readyState==4){
                  //接收完毕
{#                  console.log(x_h_r.responseText);#}
                  var obj=JSON.parse(x_h_r.responseText);
                  console.log(obj);
{#                  console.log(x_h_r.status);#}
{#                  console.log(x_h_r.statusText);#}
              }
            };
            x_h_r.setRequestHeader('k1','v1');//额外发送的请求头
            x_h_r.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); //设置请求头 值才能发过去
            x_h_r.send("name=root;pwd=123");
        }

        $.ajax({
            success:function (arg,a1,a2) {
                console.log(a2);//a2就是XMLHttpRequest对象
                console.log(a2.readyState);
                a2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
                console.log(a2.status);
                console.log(a2.statusText);
            }
        });

         /*
        function iframeRequest() {
            var url=$('#url').val();
            $('#if1').attr('src',url);
        }
        */
         function submitForm() {
             $('#ifm1').load(function () {
                 var text= $('#ifm1').contents().find('body').text();
                 var obj=JSON.parse(text);
             })
         }

    script>
body>
html>

 

 

 

user_edit.html

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <form method="post" action="/edit-{{ nid }}/">
        {% csrf_token %}
        {{ mf.as_p }}
        <input type="submit" value="提交">
    form>
body>
html>

 

 

 

upload.html

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <style>
        .upload{
            display:inline-block;padding: 10px;
            background-color: blue;
            position: absolute;
            top:0;
            bottom:0;
            right:0;
            left:0;
            z-index: 9;
        }
        .file{
            width: 100px;height: 50px;opacity: 0;
            position: absolute;
            top:0;
            bottom:0;
            right:0;
            left:0;
            z-index: 10;
        }
        .div_class{
            position: relative;width: 100px;height: 50px;
        }
    style>
head>
<body>
    <div class="div_class">
        <input class="file" type="file" id="fafafa" name="afafa">
        <a class="upload">上传a>
    div>
    <input type="button" value="提交XHR" οnclick="xhrSubmit();">
    <input type="button" value="提交jQuery" οnclick="jqSubmit();">
    <hr/>
    <form id="f1" action="/upload_file/" method="post" enctype="multipart/form-data" target="ifm1" >  
        <iframe id="ifm1" name="ifm1"  style="display: none;">iframe>
        <input type="file" name="fafafa" οnchange="changeUp();">
        <input type="submit" οnclick="iframeSubmit();" value="iframe提交">
    form>


    <div id="preview">div>
    
    <script type="text/javascript" src="/static/jquery-1.12.4.js">script>
    <script>
        function changeUp() {
             $('#ifm1').load(function () {
                 var text= $('#ifm1').contents().find('body').text();
                 var obj=JSON.parse(text);
                 console.log(obj);
                 $('#preview').empty();
                 var imgtag=document.createElement('img');
                 imgtag.src="/" + obj.data;
                 $('#preview').append(imgtag);
             });
                $('#f1').submit();
        }


        function xhrSubmit(){
{#            $('#fafafa')[0]#}
            var file_obj= document.getElementById('fafafa').files[0];

            var fd=new FormData();
            fd.append('username','root');
            fd.append('fafafa',file_obj);

            var x_h_r=new XMLHttpRequest();

            x_h_r.open('POST','/upload_file/',true);

            x_h_r.onreadystatechange=function () {
                if (x_h_r.readyState==4){
                  //接收完毕
{#                  console.log(x_h_r.responseText);#}
                  var obj=JSON.parse(x_h_r.responseText);
                  console.log(obj);
{#                  console.log(x_h_r.status);#}
{#                  console.log(x_h_r.statusText);#}
              }
            };
           x_h_r.send(fd);
        }
        
        function jqSubmit() {
            var file_obj= document.getElementById('fafafa').files[0];

            var fd=new FormData();
            fd.append('username','root');
            fd.append('fafafa',file_obj);
            
            $.ajax({
                url:'/upload_file/',
                type:'POST',
                data:fd,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success:function (arg,a1,a2) {
                        console.log(arg);
                        console.log(a1);
                        console.log(a2);
                }
            })
        }

        function iframeSubmit() {
             $('#ifm1').load(function () {
                 var text= $('#ifm1').contents().find('body').text();
                 var obj=JSON.parse(text);
                 console.log(obj);
                 $('#preview').empty();
                 var imgtag=document.createElement('img');
                 imgtag.src="/" + obj.data;
                 $('#preview').append(imgtag);
             })
         }


    script>
body>
html>

 

 

 

kind.html

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <div style="width: 500px;margin: 0 auto;">
        <textarea id="content_1">textarea>

        <script src="/static/jquery-1.12.4.js">script>
        <script src="/static/kindeditor-4.1.10/kindeditor-all.js">script>
        <script>
            $(function () {
                KindEditor.create('#content_1', {
                    width: '100%',
                    height: '300px',
                    minwidth: '80%',
                    minHeight: "260px",
                    {#                    items:["source",'fullscreen','preview', 'print', 'template', 'code', 'cut', 'copy', 'paste'],#}
                    noDisableItems: ["source", 'fullscreen', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste'],
                    {#                    designMode:false,#}
                    wellFormatMode: false,
                    useContextmenu: false,
                    fileManagerJson:'/file_manager/',
                    uploadJson: '/upload_img/',
                    {#                    allowImageUpload:false#}
                    autoHeightMode: true,
                    allowFileManager: true,
                    extraFileUploadParams: {
                        csrfmiddlewaretoken:"{{ csrf_token }}"
                    },
                    filePostName:'fafafa'
                });

            })
        script>
    div>
body>
html>

转载于:https://www.cnblogs.com/leiwenbin627/p/11123842.html

你可能感兴趣的:(ModelForm验证实例)