如何在Django 2.0后端中为员工用户添加个人资料页面?

时间:2019-05-07 11:15:57

标签: django django-models django-templates django-admin django-authentication

我在网上冲浪是这样的,但我只能找到前端解决方案或过时的指南。 我希望允许工作人员用户编辑一些默认信息,例如first_name,last_name,电子邮件,还可以编辑其他一些额外信息,例如bio,电话等。 根据建议here,我创建了一个与 User 具有OneToOneField关系的 Profile 类,但是只有超级用户才能编辑这些信息。 如果我授予职员组 can_change_user 权限,则每个“职员”用户都可以编辑任何个人资料。

修改 这些是我应用程序中名为 users

的文件

#admin.py-用户

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'

class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )

    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)  

#models.py-用户

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    extra_info = models.CharField(max_length=30, blank=True)    

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save() 

编辑1:我以这种方式编辑了两个类

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profilo'
    fk_name = 'user'

    def has_change_permission(self, request, obj=None):
        print("utente:")
        print(request.user)
        if obj == request.user:
            return True
        else:
            return False    


class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )

    # this function prints error *"get_queryset() missing 1 required positional argument: 'request'"*  
    '''
    def get_queryset(self, request):
        queryset = super(CustomUserAdmin, self).get_queryset()
        queryset = queryset.filter(user=self.request.user)
        return queryset
    '''

    def get_fieldsets(self, request, obj=None):
        if not request.user.is_superuser:
            if obj == request.user:
                fieldsets = (
                (('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
                )
            else:
                fieldsets = ()
        else:
            fieldsets = self.fieldsets

        return fieldsets


    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)  

在用户填写字段之前,为什么会出现“#1”? #1 is is shown until the user fills in the field

0 个答案:

没有答案