美文网首页django
django admin test

django admin test

作者: swotpp | 来源:发表于2020-04-25 22:08 被阅读0次
    1. 创建模型 models.py

       from django.db import models
      
       class Call(models.Model):
           ordernum = models.CharField(
               "工单号",
               max_length=200,
               default="",)
      
    2. admin.py

      from django.contrib import admin
      from . import models
      
      def add_delete_permission(request):
          group_name = request.user.groups.first().name
          if group_name == "风控":
              return False
          return True
      
      class CallAdmin(admin.ModelAdmin):
          def has_add_permission(self, request):
              return add_delete_permission(request)
          def has_delete_permission(self, request, obj=None):
              return add_delete_permission(request)
      
      admin.site.register(models.Call, CallAdmin)
      
    3. tests.py 使用mock来减少创建用户、组及将用户加入组中的代码

       from django.test import TestCase
       from . import models
       from django.contrib.admin.sites import AdminSite
       from .admin import CallAdmin
       from unittest import mock
      
       class CallAdminTests(TestCase):
      
           def setUp(self):
               self.call_admin = CallAdmin(model=models.Call, admin_site=AdminSite())
               self.OurRequest = mock.Mock()
               self.OurRequest.user.groups.first.return_value.name = '风控'
      
           def test_has_add_permission(self):
               self.assertEquals(self.call_admin.has_add_permission(self.OurRequest), False)
      
           def test_has_delete_permission(self):
               self.assertEquals(self.call_admin.has_delete_permission(self.OurRequest), False)
      
    4. 项目下 urls.py

       from django.contrib import admin
       from django.urls import path
      
       urlpatterns = [
           path('admin/', admin.site.urls),
       ]
      

    相关文章

      网友评论

        本文标题:django admin test

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