django主机管理(ajax,模态框)Django

jquery的Ajax(删除与添加数据)

2017-07-08  本文已影响0人  赖三石

models.py

from __future__ import unicode_literals
from django.db import models

# Create your models here.

class Host(models.Model):
   hostname = models.CharField(max_length=32, unique=True)
   ip = models.GenericIPAddressField(max_length=20, unique=True)
   port = models.IntegerField()
   category = models.ForeignKey('Category')

   def __unicode__(self):
       return self.hostname

class Category(models.Model):
   name = models.CharField(max_length=32, unique=True)

   def __unicode__(self):
       return self.name

views.py

# -*- coding: UTF-8 -*-
from django.shortcuts import render, get_object_or_404, redirect, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import *
import json
# Create your views here.


def index(request):
    hosts = Host.objects.all()
    categorys = Category.objects.all()
    return render(request, 'index.html', {'hosts': hosts, 'categorys': categorys})


def delete_host(request, host_id):
    host_one = get_object_or_404(Host, pk=host_id)
    host_one.delete()
    return redirect('/')


# @csrf_exempt
def create_host(request):
    res = {'status': True, 'error': None, 'data': None}
    try:
        hostname = request.POST.get('hostname')
        ip = request.POST.get('ip')
        port = request.POST.get('port')
        category = request.POST.get('category')
        # print('%s,%s,%s,%s' %(hostname, ip, port, category))
        if hostname and len(hostname) > 5:
            Host.objects.create(hostname=hostname, ip=ip, port=port, category_id=category)
        else:
            res['status'] = False
            res['error'] = '太短了'
    except Exception as e:
        res['status'] = False
        res['error'] = '请求错误'
    return HttpResponse(json.dumps(res))

template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
    <div class="row">
    <table class="table table-bordered">
        <thead>
            <tr>
                <td>name</td>
                <td>ip</td>
                <td>port</td>
                <td>category</td>
                <td></td>
                <td></td>
            </tr>
        </thead>
        <tbody>
            {% for host in hosts %}
            <tr>
                <td>{{ host.hostname }}</td>
                <td>{{ host.ip }}</td>
                <td>{{ host.port }}</td>
                <td>{{ host.category.name }}</td>
                <td><a href="{% url 'delete_host' host.id %}">删除</a></td>
                <td><a href="#">编辑</a></td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    </div>
    </div>

<!-- Button trigger modal -->
  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  创建主机
</button>


<!-- Modal -->
<div class="modal fade" id="myModal" 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">×</span></button>
        <h4 class="modal-title" id="myModalLabel">创建主机</h4>
      </div>
      <div class="modal-body">
        <form id="aform" class="form-group" action="" method="post">
            hostname:<input id="hostname" type="text" class="form-control" name="hostname"><br>
            ipaddress:<input id="ip" type="text" class="form-control" name="ip"><br>
            port:<input id="port" type="text" class="form-control" name="port"><br>
            <select id="category" name="category" class="form-control-static">
                {% for category in categorys %}
                    <option value="{{ category.id }}">{{ category }}</option>
                {% endfor %}
            </select>
        <span id="messee"></span>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button id="btn1" type="button" class="btn btn-primary">确定</button>
      </div>
    </div>
  </div>
</div>

</body>
<script src="/static/js/jquery.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script>

    $(document).ready(function(){

        $('#btn1').click(function(){

            $.ajax({
                url: '/host',
                type: 'POST',
                data: {csrfmiddlewaretoken: '{{ csrf_token }}','hostname':$('#hostname').val(),'ip': $('#ip').val(), 'port': $('#port').val(), 'category': $('#category').val()},
{#                data: $('#aform').serialize(),#}
                success: function(data){
                    var a = JSON.parse(data)
                    console.log(a)
                    if(a.status){
                        location.reload();
                    }else{
                        $('#messee').text(a.error);
                    }
                }
            })
        });
    });

</script>
</html>

注意:

ajax中POST的csrf的屏蔽和解决:

注释settings.py 那行
MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
   # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
用@csrf_exempt装饰器
from django.views.decorators.csrf import csrf_exempt
在$ajax , data:中加入csrfmiddlewaretoken: '{{ csrf_token }}'
       $.ajax({
                url: '/host',
                type: 'POST',
                data: {csrfmiddlewaretoken: '{{ csrf_token }}','hostname':$('#hostname').val(),'ip': $('#ip').val(), 'port': $('#port').val(), 'category': $('#category').val()},
{#                data: $('#aform').serialize(),#}
                success: function(data){
                    var a = JSON.parse(data)
                    console.log(a)
                    if(a.status){
                        location.reload();
                    }else{
                        $('#messee').text(a.error);
                    }
                }
            })
上一篇 下一篇

猜你喜欢

热点阅读