真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

Django之入門CMDB系統(tǒng)(四)增刪改查-創(chuàng)新互聯(lián)

Django之入門 CMDB系統(tǒng) (四) 增刪改查


前言

作者: 何全,github地址: https://github.com/hequan2017 QQ交流群: 620176501

成都創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),孟村企業(yè)網(wǎng)站建設(shè),孟村品牌網(wǎng)站建設(shè),網(wǎng)站定制,孟村網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,孟村網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。

通過此教程完成從零入門,能夠獨(dú)立編寫一個簡單的CMDB系統(tǒng)。

目前主流的方法開發(fā)方式,分為2種:mvc 和 mvvc方式。本教程為 mvc 方式,即 django負(fù)責(zé)渲染html。后面會推出 mvvc(前后端分離)的入門教程。

教程項(xiàng)目地址: https://github.com/hequan2017/husky/

教程文檔地址: https://github.com/hequan2017/husky/tree/master/doc

Django之入門 CMDB系統(tǒng)  (四) 增刪改查

說明

  • cbv 在視圖里使用類處理請求 (下面采用這種方式,比較會抽象一點(diǎn),但是會比較簡潔)
  • fbv 在視圖里使用函數(shù)處理請求

基礎(chǔ)設(shè)置

pycharm : 菜單欄 tools --> 選擇 run manage.py task

manage.py@husky > startapp asset ##創(chuàng)建 asset app

具體內(nèi)容請看實(shí)際頁面,下面只是把重點(diǎn)代碼 進(jìn)行展示。

  • settings.py 增加系統(tǒng)配置
import sys
INSTALLED_APPS = [
    "asset",
]
  • asset/modes.py
from django.db import models

class Ecs(models.Model):
    TYPE_CHOICES = (
        ('阿里云', '阿里云'),
        ('騰訊云', '騰訊云'),
        ('華為云', '華為云'),
        ('亞馬遜', '亞馬遜'),
        ('其他', '其他'),
        (None,None),
    )
    hostname = models.CharField(max_length=96, verbose_name='主機(jī)名', blank=True, null=True, )
    type = models.CharField(choices=TYPE_CHOICES, max_length=16, verbose_name='主機(jī)類型', blank=True, null=True, )
    instance_id = models.CharField(max_length=64, verbose_name='實(shí)例ID', unique=True)
    instance_name = models.CharField(max_length=96, verbose_name='標(biāo)簽', blank=True, null=True, )
    os_name = models.CharField(max_length=64, verbose_name='系統(tǒng)版本', blank=True, null=True, )
    cpu = models.IntegerField(verbose_name='CPU', blank=True, null=True)
    memory = models.IntegerField(verbose_name='內(nèi)存', blank=True, null=True)
    private_ip = models.GenericIPAddressField(verbose_name='內(nèi)網(wǎng)IP', blank=True, null=True)
    public_ip = models.GenericIPAddressField(verbose_name='外網(wǎng)IP', blank=True, null=True)

    c_time = models.DateTimeField(auto_now_add=True, null=True, verbose_name='創(chuàng)建時間', blank=True)
    u_time = models.DateTimeField(auto_now=True, null=True, verbose_name='更新時間', blank=True)

    class Meta:
        db_table = "ecs"
        verbose_name = "主機(jī)"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.hostname

pycharm : 菜單欄 tools --> 選擇 run manage.py task

makemigrations 生成數(shù)據(jù)文件

migrate 根據(jù)文件,執(zhí)行生成表結(jié)構(gòu)

  • asset/form.py
from django import forms
from asset.models import Ecs

class EcsForm(forms.ModelForm):
    class Meta:
        model = Ecs
        fields = '__all__'

        widgets = {
            'type': forms.Select(
                attrs={'class': 'select2',
                       'data-placeholder': '----請選擇環(huán)境----'}),
        }

        help_texts = {
            'type': '* 請選擇 資產(chǎn)所在平臺.',

        }

    def clean_type(self):
        """
        自定義驗(yàn)證
        :return:
        """
        type = self.cleaned_data['type']
        return type
  • asset/admin.py
from django.contrib import admin
from asset.models import Ecs

admin.site.register(Ecs)
  • 自定義標(biāo)簽處理
    • asset/templatetags/asset_filter.py
from django import template
from django.apps import apps
from asset.models import Ecs
register = template.Library()

@register.filter(name='ecs_model_choices')
def ecs_model_choices(model_name, choice_name):
    asset_app = apps.get_app_config('assets')
    return getattr(asset_app.get_model(model_name), choice_name)

@register.filter(name='ecs_type_choices')
def ecs_type_choices(value):
    return  Ecs.TYPE_CHOICES

增加

  • asset/views.py
class EcsCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
    """
    Ecs 創(chuàng)建
    """
    permission_required = ('asset.add_ecs',)
    model = Ecs
    form_class = EcsForm
    template_name = 'asset/ecs-create.html'
    success_url = reverse_lazy('asset:ecs-list')

    def get_context_data(self, **kwargs):
        context = {}
        if '__next__' in self.request.POST:  # 為了獲取 點(diǎn)擊本頁之前的 瀏覽網(wǎng)頁
            context['i__next__'] = self.request.POST['__next__']
        else:
            try:
                context['i__next__'] = self.request.META['HTTP_REFERER']
            except Exception as e:
                logger.error(e)
        kwargs.update(context)
        return super().get_context_data(**kwargs)

    def get_success_url(self):
        return self.request.POST['__next__']

    def form_valid(self, form):  #  保存結(jié)果 可以進(jìn)行 手動 修改 再保存
        obj = form.save(commit=False)
        obj.save()
        return super().form_valid(form)

    def form_invalid(self, form):
        print(form.errors)
        """If the form is invalid, render the invalid form."""
        return self.render_to_response(self.get_context_data(form=form))
  • asset/urls.py
from django.urls import path
from asset import views

app_name = "asset"

urlpatterns = [
    path('ecs-create', views.EcsCreateView.as_view(), name='ecs-create')
]
  • templates/base/_js.html


  • templates/base/_nav.html
                
  • templates/asset/ecs-create.html
    
{% csrf_token %} {% if form.non_field_errors %}
{{ form.non_field_errors }}
{% endif %}

基本

{% bootstrap_field form.hostname layout="horizontal" %} {% bootstrap_field form.type layout="horizontal" %} {% bootstrap_field form.instance_id layout="horizontal" %} {% bootstrap_field form.instance_name layout="horizontal" %} {% bootstrap_field form.os_name layout="horizontal" %} {% bootstrap_field form.cpu layout="horizontal" %} {% bootstrap_field form.memory layout="horizontal" %} {% bootstrap_field form.private_ip layout="horizontal" %} {% bootstrap_field form.public_ip layout="horizontal" %}
{% bootstrap_button "保存" button_type="submit" button_class="btn-primary" %} 取消
{% block footer-js %} {% endblock %}

列表

  • asset/views.py
def get_list(function):
    """
    列表頁面  獲取 搜索
    :param function: self.model
    :return:
    """

    @wraps(function)
    def wrapped(self):
        # user = self.request.user
        # groups = [x['name'] for x in self.request.user.groups.values()]
        # request_type = self.request.method
        # model = str(self.model._meta).split(".")[1]

        filter_dict = {}
        not_list = ['page', 'order_by', 'csrfmiddlewaretoken']
        for k, v in dict(self.request.GET).items():
            if [i for i in v if i != ''] and (k not in not_list):
                if '__in' in k:
                    filter_dict[k] = v
                else:
                    filter_dict[k] = v[0]

        self.filter_dict = filter_dict
        self.queryset = self.model.objects.filter(**filter_dict).order_by('-id')
        order_by_val = self.request.GET.get('order_by', '')
        if order_by_val:
            self.queryset = self.queryset.order_by(order_by_val) if self.queryset else self.queryset
        result = function(self)
        return result

    return wrapped

class EcsListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
    permission_required = ('asset.view_ecs',)
    template_name = 'asset/ecs-list.html'
    model = Ecs
    queryset = Ecs.objects.get_queryset().order_by('-id')

    @get_list  ## 處理查詢
    def get_context_data(self, **kwargs):
        try:
            page = self.request.GET.get('page', 1)
        except PageNotAnInteger as e:
            page = 1
        p = Paginator(self.queryset, getattr(settings, 'DISPLAY_PER_PAGE'), request=self.request)
        ecs_list = p.page(page)

        context = {
            "ecs_list": ecs_list,
            "filter_dict": self.filter_dict  # 把查詢條件返回給前端
        }

        kwargs.update(context)
        return super().get_context_data(**kwargs)
  • asset/urls.py
path('ecs-list', views.EcsListView.as_view(), name='ecs-list'),
  • templates.py/asset/ecs-list.html
   
{% csrf_token %} {% for row in ecs_list.object_list %} {% endfor %}
主機(jī)名 主機(jī)類型 實(shí)例ID 標(biāo)簽 系統(tǒng)版本 內(nèi)網(wǎng)IP 創(chuàng)建時間 操作
{{ row.hostname }}
{{ row.get_type_display }}
{{ row.instance_id }}
{{ row.instance_name }}
{{ row.os_name }}
{{ row.private_ip }}
{{ row.c_time | date:'Y-m-d' }}
{% if perms.asset.view_ecs %} 詳情 {% endif %} {% if perms.asset.change_ecs %} 編輯 {% endif %} {% if perms.asset.delete_ecs %} 刪除 {% endif %}
{% block footer-js %}

更新

  • asset/views.py

class EcsUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):

    permission_required = ('asset.change_ecs',)
    model = Ecs
    form_class = EcsForm
    template_name = 'asset/ecs-create.html'
    success_url = reverse_lazy('asset:ecs-list')

    def get_context_data(self, **kwargs):
        context = {}
        if '__next__' in self.request.POST:  # 為了獲取 點(diǎn)擊本頁之前的 瀏覽網(wǎng)頁
            context['i__next__'] = self.request.POST['__next__']
        else:
            try:
                context['i__next__'] = self.request.META['HTTP_REFERER']
            except Exception as e:
                logger.error(e)
        kwargs.update(context)
        return super().get_context_data(**kwargs)

    def get_success_url(self):
        return self.request.POST['__next__']
  • asset/urls.py
    path('ecs-update-', views.EcsUpdateView.as_view(), name='ecs-update'),
  • templates.py/asset/ecs-create.html 創(chuàng)建頁面 同時也當(dāng)更新頁面
     {% if perms.asset.change_ecs %}
        編輯
    {% endif %}

刪除

  • asset/views.py
class EcsDeleteView(LoginRequiredMixin, PermissionRequiredMixin, View):

    permission_required = ('asset.delete_ecs',)
    model = Ecs

    def post(self, request):
        ret = {'status': True, 'error': None, }
        nid = self.request.POST.get('nid', None)
        self.model.objects.get(id=nid).delete()
        return HttpResponse(json.dumps(ret))
  • asset/urls.py

path('ecs-delete', views.EcsDeleteView.as_view(), name='ecs-delete'),

templates.py/asset/ecs-list.html

 {% if perms.asset.delete_ecs %}
 刪除
  {% endif %}
   $(function () {

                $(document).on('click', '.ecs-delete', function () {
                    var id = $(this).parent().parent().attr('id');
                    var name = $(this).parent().parent().attr('name');
                    swal({
                        title: "你確定刪除",
                        text: name,
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "確定",
                        cancelButtonText: "取消",
                        closeOnConfirm: false
                    }, function () {
                        $.ajax({
                            url: "{% url 'asset:ecs-delete' %}",
                            type: 'POST',
                            data: {'nid': id},
                            success: function (data) {
                                var obj = JSON.parse(data);
                                if (obj.status) {
                                    swal({title: "刪除", text: "已成功刪除", type: "success"}, function () {
                                        window.location.reload();
                                    })
                                } else {
                                    swal("錯誤", "刪除" + "[ " + obj.error + " ]" + "遇到錯誤", "error");
                                }
                            }
                        });
                    });

                });

            });

詳情

  • asset/views.py
class EcsDetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView):
    permission_required = ('asset.view_ecs',)
    model = Ecs
    form_class = EcsForm
    template_name = 'asset/ecs-detail.html'
    def get_context_data(self, **kwargs):
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        context = {
            "ecs": self.model.objects.get(id=pk),
            "nid": pk
        }
        kwargs.update(context)
        return super().get_context_data(**kwargs)
  • asset/urls.py

path('ecs-detail-', views.EcsDetailView.as_view(), name='ecs-detail'),

  • templates.py/asset/ecs-list.html

    
主機(jī)類型: {{ ecs.get_type_display }}
實(shí)例ID: {{ ecs.instance_id }}
標(biāo)簽: {{ ecs.instance_name }}
系統(tǒng)版本: {{ ecs.os_name }}
CPU: {{ ecs.cpu }}
內(nèi)存: {{ ecs.memory }}
內(nèi)網(wǎng)IP: {{ ecs.private_ip }}
外網(wǎng)IP: {{ ecs.public_ip }}
創(chuàng)建時間: {{ ecs.c_time }}
更新時間: {{ ecs.u_time }}

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。


當(dāng)前題目:Django之入門CMDB系統(tǒng)(四)增刪改查-創(chuàng)新互聯(lián)
本文路徑:http://weahome.cn/article/cepgjs.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部