如何显示用户组,因为它们没有在 django 视图中显示?

Posted

技术标签:

【中文标题】如何显示用户组,因为它们没有在 django 视图中显示?【英文标题】:How to display the user groups because they didn't show in django view? 【发布时间】:2021-03-02 16:34:18 【问题描述】:

我研究了几天,但 django 的文档中没有太多关于组的信息,而且真的不知道要更改什么以便显示组。

我对用户有 CRUD 操作,只能由管理员完成,他可以将用户分配到 6 个不同的组。它保存在数据库中,一切正常。我现在面临的问题是这些组在我的视图中(在 UI 中)没有可视化。

我附上图片来说明我的意思: groups

model.py

class CustomUserManager(BaseUserManager):

    def create_user(self, email, password, **extra_fields):

        if not email:
            raise ValueError(_('The Email must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):

        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, password, **extra_fields)


class CustomUser(AbstractUser):

    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.email

    username                        = models.CharField(max_length=30, blank=True, default='')
    is_superuser                    = models.BooleanField(default=True)
    is_admin                        = models.BooleanField(default=True)
    is_employee                     = models.BooleanField(default=True)
    is_headofdepartment             = models.BooleanField(default=True)
    is_reception                    = models.BooleanField(default=True)
    is_patient                      = models.BooleanField(default=True)
    is_active                       = models.BooleanField(default=True)
    is_staff                        = models.BooleanField(default=True)

forms.py

class UserForm(ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    group = forms.ModelChoiceField(queryset=Group.objects.all())

    class Meta:
        model = CustomUser
        fields = [
            'email',
            'password',
            'group',
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['group'] = ModelChoiceField(
            queryset=Group.objects.all(),
            empty_label='Избери'
        )

useradd.html

<h1 class="display-4">Add new user</h1>
            <form action="" method="post" autocomplete="off">
                % csrf_token %
                 form.as_p 
                    <button type="submit" class="btn btn-success">Save </button>

users.html

                  % for user in users %
                        <tr>
                            <td> user.email </td>
                            <td> user.group </td>
                            <td>
                                <a href="% url 'feedback:useredit' user.id %" class="btn text-secondary px"-0>
                                    <i class="far fa-edit fa-lg"></i>
                                </a>
                                <form action="% url 'feedback:userdelete' user.id %" method="post" class="d-inline">
                                    % csrf_token %
                                    <button type="submit" class="btn">
                                        <i class="far fa-trash-alt fa-lg text-danger float-right"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    % endfor %

views.py

@login_required
@admin_only
def users(request):
    context = 'users': CustomUser.objects.all()
    return render(request, 'users.html', context)

@login_required
def users_add(request):
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            users = CustomUser.objects.create_user(**form.cleaned_data)
            #login(request, users)
            # redirect, or however you want to get to the main view
            return redirect('feedback:users')
    else:
        form = UserForm() 

    return render(request, 'useradd.html', 'form': form) 

【问题讨论】:

【参考方案1】:

如果有人需要,解决方案是因为 Group 与 User 是多对多关系,它需要遍历与每个用户关联的所有 Group 对象。

<td>
% for group in user.groups.all %
 group.name 
% endfor %
<td>

【讨论】:

以上是关于如何显示用户组,因为它们没有在 django 视图中显示?的主要内容,如果未能解决你的问题,请参考以下文章

在模板Django中显示没有组的用户

Django 基于类的通用视图和身份验证

django 根据请求向所有视图添加上下文

如何修复列表视图未在 Django 中显示

如何在Django视图中显示PDF文件?

如何从 Django 视图将变量传递给 SCSS