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



我研究了几天,但在django的文档中没有太多关于组的信息,真的不知道该更改什么,所以组会被显示出来。

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

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

型号.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)

表单.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 %}

视图.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}) 

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

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

相关内容

  • 没有找到相关文章

最新更新