zoukankan      html  css  js  c++  java
  • CRM 增加信息不进行readonly,自定义user

    1、CRM 增加信息不进行readonly,只要在kind_admin/view.py中的table_objs_add函数加上admin_class.is_add_form = True,在前端做判断

    def table_objs_add(request,app_name,table_name):
        """增加信息页面"""
    
        admin_class = kind_admin.enabled_admins[app_name][table_name]
        model_form_class = creat_model_form(request, admin_class)
        admin_class.is_add_form = True
        #admin_class.only_readonly = True
        if request.method == 'POST':
            form_obj = model_form_class(request.POST) #新增
            if form_obj.is_valid():
                form_obj.save()
            return redirect(request.path.replace("/add/","/"))
    
        else:
            form_obj = model_form_class()
    
    
        return render(request,"kindadmin/table_objs_add.html",{"form_obj":form_obj,
                                                               "admin_class":admin_class})

    2、为了使页面只读的不能够删除数据,可以在kind_admin.py 中加上readonly_table = False判断

    发现了一个问题,之前自定义了一个clean_name函数,判断name不能为空,但是当我去修改name的名字时候,后端一直没有保存name的值,返回给前端的一直是None(求大佬指点)代码如下:

    #判断name不能为空kind_admin.py
        def clean_name(self):
            print("name clean validation:", self.cleaned_data["name"])
            if not self.cleaned_data["name"]:
                self.add_error('name', "cannot be null")
    #判断名字不能为空,加到form的claen_name中
                #判断admin_class里否有clean_name函数
                if hasattr(admin_class, 'clean_%s' % field_name):
                    #获取clean_name函数
                    field_clean_func = getattr(admin_class,"clean_%s" %field_name)
                    #把clean_name函数添加到form的clean_field中
                    setattr(cls, 'clean_%s'%field_name, field_clean_func)

    3、自定义user不用django自带的user

    django的文档有:https://docs.djangoproject.com/en/1.10/topics/auth/customizing/

    crm/models.py文件中

    class UserProfile(AbstractBaseUser):
        email = models.EmailField(
            verbose_name='email address',
            max_length=255,
            unique=True,
            null =True
        )
    
        name = models.CharField(max_length=32)
        is_active = models.BooleanField(default=True)
        is_admin = models.BooleanField(default=False)
    
        objects = UserProfileManager()#创建用户
    
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['name'] #那个字段是必须的
    
        def get_full_name(self):
            # The user is identified by their email address
            return self.email
    
        def get_short_name(self):
            # The user is identified by their email address
            return self.email
    
        def __str__(self):              # __unicode__ on Python 2
            return self.email
    
        def has_perm(self, perm, obj=None):
            "Does the user have a specific permission?"
            # Simplest possible answer: Yes, always
            return True
    
        def has_module_perms(self, app_label):
            "Does the user have permissions to view the app `app_label`?"
            # Simplest possible answer: Yes, always
            return True
    
        @property
        def is_staff(self):
            "Is the user a member of staff?"
            # Simplest possible answer: All admins are staff
            return self.is_admin

    在Perfectcrm/setting.py中加下如下以让dajngo不用自带的

    AUTH_USER_MODEL = 'crm.UserProfile' #crm app名 UserProfile用户表名

    创建用户的函数crm/models:

    class UserProfileManager(BaseUserManager):
        def create_user(self, email, name, password=None):
            """
            Creates and saves a User with the given email, date of
            birth and password.
            """
            if not email:
                raise ValueError('Users must have an email address')
    
            user = self.model(
                email=self.normalize_email(email),
                name=name,
            )
    
            user.set_password(password)
            user.is_active = True
            user.save(using=self._db)
            return user
    
        def create_superuser(self, email, name, password):
            """
            Creates and saves a superuser with the given email, date of
            birth and password.
            """
            user = self.create_user(
                email,
                password=password,
                name=name,
            )
            user.is_admin = True
            user.is_active = True
            user.save(using=self._db)
            return user

    在crm/admin.py加上UserProfile用邮箱作为用户名
           :

    
    
    from django.contrib import admin
    from django.contrib.auth.models import Group
    from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
    from django.contrib.auth.forms import ReadOnlyPasswordHashField
    class UserCreationForm(forms.ModelForm):
        """A form for creating new users. Includes all the required
        fields, plus a repeated password."""
        password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
        password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
    
        class Meta:
            model = models.UserProfile
            fields = ('email', 'name')
    
        def clean_password2(self):
            # Check that the two password entries match
            password1 = self.cleaned_data.get("password1")
            password2 = self.cleaned_data.get("password2")
            if password1 and password2 and password1 != password2:
                raise forms.ValidationError("Passwords don't match")
            return password2
    
        def save(self, commit=True):
            # Save the provided password in hashed format
            user = super(UserCreationForm, self).save(commit=False)
            user.set_password(self.cleaned_data["password1"])
            if commit:
                user.save()
            return user
    
    
    class UserChangeForm(forms.ModelForm):
        """A form for updating users. Includes all the fields on
        the user, but replaces the password field with admin's
        password hash display field.
        """
        password = ReadOnlyPasswordHashField()
    
        class Meta:
            model = models.UserProfile
    
            fields = ('email', 'password', 'name', 'is_active', 'is_admin')
    
        def clean_password(self):
            # Regardless of what the user provides, return the initial value.
            # This is done here, rather than on the field, because the
            # field does not have access to the initial value
            return self.initial["password"]
    
    
    class UserProfileAdmin(BaseUserAdmin):
        # The forms to add and change user instances
        form = UserChangeForm
        add_form = UserCreationForm
    
        # The fields to be used in displaying the User model.
        # These override the definitions on the base UserAdmin
        # that reference specific fields on auth.User.
        list_display = ('email', 'name', 'is_admin')
        list_filter = ('is_admin',)
        fieldsets = (
            (None, {'fields': ('email', 'password')}),
            ('Personal info', {'fields': ('name',)}),
            ('Permissions', {'fields': ('is_admin',)}),
        )
        # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
        # overrides get_fieldsets to use this attribute when creating a user.
        add_fieldsets = (
            (None, {
                'classes': ('wide',),
                'fields': ('email', 'name', 'password1', 'password2')}
            ),
        )
        search_fields = ('email',)
        ordering = ('email',)
        filter_horizontal = ()
    
    # Now register the new UserAdmin...
    admin.site.register(models.UserProfile, UserProfileAdmin)
    # ... and, since we're not using Django's built-in permissions,
    # unregister the Group model from admin.
    admin.site.unregister(Group)

    3、把之前创建的数据库删除:

     drop database crm;

    在此创建crm库:

     drop database crm;

    把在crm/migrations文件下的文件删除只剩下__init.py文件

    然后再:

    python3 manage.py makemigrations

    python3 manage.py migrate

  • 相关阅读:
    没用完的手机流量是否清零?讨论+吐槽
    南方周末:《系统》
    如何将Excel表批量赋值到ArcGIS属性表
    解决4K屏电脑显示问题
    坐标或测量值超出范围
    快速手工实现软件著作权源码60页制作
    SVN版本更新自动通知提醒
    1130不允许连接到MySql server
    Win10中SVN图标不显示的解决
    注意地理坐标系下的距离和面积计算
  • 原文地址:https://www.cnblogs.com/venvive/p/11410155.html
Copyright © 2011-2022 走看看