码迷,mamicode.com
首页 > Web开发 > 详细

Django(十三)ajax 与 Bootstrap,font-awesome

时间:2019-04-02 17:07:31      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:std   request   rap   asc   bootstra   .text   .com   hide   containe   

 

font-awesome:字体,图标库

对话框添加,删除,修改:
    添加:
        Ajax偷偷向后台发请求:
            1. 下载引入jQuery
            2. 
                $.ajax({
                    url: /add_classes.html,
                    type: POST,
                    data: {username:root,password: 123},
                    success:function(arg){
                        // 回调函数,arg是服务端返回的数据
                    }
                })

 

技术图片
"""ajax_learn URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path(‘‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path(‘‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path(‘blog/‘, include(‘blog.urls‘))
"""
from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path(admin/, admin.site.urls),
    path(students/, views.students),
    path(add_student/, views.add_student),
]
urls
技术图片
from django.shortcuts import render,HttpResponse
from app01 import models

# Create your views here.

def students(request):
    student_list = models.Student.objects.all()
    class_list = models.Classes.objects.all()
    return render(request, "students.html", {"student_list": student_list,
                                             "class_list": class_list})

def add_student(request):
    response = {status: True, message: None}
    print(request.POST)
    ‘‘‘
    <QueryDict: {‘username‘: [‘Mike‘], ‘age‘: [‘29‘], 
                ‘gender‘: [‘1‘], ‘class_id‘: [‘3‘]}>
    ‘‘‘
    try:
        u = request.POST.get("username")
        a = request.POST.get("age")
        g = request.POST.get("gender")
        c = request.POST.get("class_id")

        models.Student.objects.create(username=u, age=a, gender=g, cs_id=c)
    except Exception as e:
        response[status] = False
        response[message] = 用户输入错误
    import json
    result = json.dumps(response, ensure_ascii=False)
    return HttpResponse(result)
views
技术图片
from django.db import models

# Create your models here.
class Classes(models.Model):
    """
    班级表,男
    """
    title = models.CharField(max_length=32)
    m = models.ManyToManyField("Teachers")

class Teachers(models.Model):
    """
    老师表,女
    """
    name = models.CharField (max_length=32)

class Student(models.Model):
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    gender = models.BooleanField(null=True)
    cs = models.ForeignKey(Classes, on_delete=models.CASCADE)
models
技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
    <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css">
    <style>
        .icon {
            margin: 0px 5px;
        }
    </style>
</head>
<body>
<div class="container">
    <div style="padding: 20px 0">
        <a href="#" class="btn btn-primary" id="addBtn">添加</a>
        <a href="#" class="btn btn-danger">删除</a>
    </div>
    <div>
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>班级</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for row in student_list %}
                    <tr>
                        <td>{{ row.id }}</td>
                        <td>{{ row.username }}</td>
                        <td>{{ row.age }}</td>
                        <td>{{ row.gender }}</td>
                        <td>{{ row.cs.title }}</td>
                        <td>
                            <a href="#" class="glyphicon glyphicon-remove icon"></a>
                            <a href="#" class="fa fa-pencil-square-o icon" style="font-size: 17px"></a>
                        </td>

                    </tr>
                {% endfor %}
            </tbody>

        </table>
    </div>
</div>


<!-- Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">创建学生</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal">
          <div class="form-group">
            <label for="username" class="col-sm-2 control-label">姓名</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" name="username" placeholder="姓名">
            </div>
          </div>

          <div class="form-group">
            <label for="age" class="col-sm-2 control-label">年龄</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" name="age" placeholder="年龄">
            </div>
          </div>

          <div class="form-group">
            <label for="gender" class="col-sm-2 control-label">性别</label>
            <div class="col-sm-10">
                <label class="radio-inline">
                  <input type="radio" name="gender" value="1"></label>
                <label class="radio-inline">
                  <input type="radio" name="gender" value="0"></label>
            </div>
          </div>

           <div class="form-group">
                <label for="classes" class="col-sm-2 control-label">班级</label>
                <div class="col-sm-10">
                    <select class="form-control" name="class_id">
                        {% for row in class_list %}
                            <option value="{{ row.id }}">{{ row.title }}</option>
                        {% endfor %}
                    </select>
                </div>
           </div>

        </form>
      </div>
      <div class="modal-footer">
          <span id="errorMsg" style="color: red;"></span>
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="btnSave">保存</button>
      </div>
    </div>
  </div>
</div>

<script src="/static/js/jquery-3.3.1.js"></script>
<script src="/static/plugins/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<script>
    $(function () {
        bindEvent();
        bindSave();
    });
    
    function bindEvent() {
        $("#addBtn").click(function () {
            $("#addModal").modal(show);
        })
    };

    function bindSave() {
        $("#btnSave").click(function () {
            var postData = {};
            $(".modal").find("input,select").each(function () {
                {#console.log($(this)[0]);#}
                var v = $(this).val();
                var n = $(this).attr("name");
                if (n == "gender") {
                    if($(this).prop("checked")) {
                        postData[n] = v
                    }
                }else{
                    postData[n] = v
                }
            });
            console.log(postData)
            $.ajax({
                url:"/add_student/",
                type:"POST",
                data:postData,
                success:function (arg) {
                    // arg是字符串
                    // JSON.parse将字符串转换成字典, json.loads
                    var dict = JSON.parse(arg);
                    if(dict.status){
                        window.location.reload();
                    }else {
                        $("#errorMsg").text(dict.message);
                    }
                }
            })
        });
    }

</script>

</body>
</html>
student.html

 

Django(十三)ajax 与 Bootstrap,font-awesome

标签:std   request   rap   asc   bootstra   .text   .com   hide   containe   

原文地址:https://www.cnblogs.com/xiangtingshen/p/10643497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!