[英]How to add a user to a ManyToManyField when creating User in Django?
Models.py: Models.py:
class RegularUser(MyUser):
MyUser.is_staff = False
MyUser.is_superuser = False
class Meta:
verbose_name = 'Usuario Regular'
verbose_name_plural = 'Usuarios Regulares'
class AdminUser(MyUser):
usuarios = models.ManyToManyField(RegularUser, help_text="Selecciona los usuarios que administra", blank=True)
MyUser.is_staff = True
class Meta:
verbose_name = 'Administrador'
verbose_name_plural = 'Adminsitradores'
I want the next: I log in the admin site as AdminUser, which have staff permission. 我想要下一个:我以具有用户权限的AdminUser登录管理站点。 Then I can create RegularUsers.
然后,我可以创建RegularUsers。 When I create a new RegularUser I want link this Regular User to the AdminUser through the ManyToManyField so this RegularUser owns to the AdminUser.
当我创建一个新的RegularUser时,我想通过ManyToManyField将此常规用户链接到AdminUser,以便此RegularUser拥有AdminUser。 And the AdminUser could manage this RegularUser in the adminSite.
AdminUser可以在adminSite中管理此RegularUser。
I want some like this: 我想要这样的东西:
class RegularUserCreationForm(forms.ModelForm): ... ... class RegularUserCreationForm(forms.ModelForm):... ...
@receiver(post_save, sender=RegularUser)
def link_user_admin(sender, instance, created, **kwargs):
if created:
instance.adminuser = request.user
But adminuser isn't a field of RegularUser. 但是adminuser不是RegularUser的字段。 And using request in signals is forbidden.
并且禁止在信号中使用请求。 Can someone help me please?
有人能帮助我吗?
Well. 好。 I have found the solution.
我找到了解决方案。 I need to use the request in the post_save method.
我需要在post_save方法中使用该请求。 However, you can't use it in Django signals, so it's possible to use the Django save_model method which you can get access to the request.
但是,您不能在Django信号中使用它,因此可以使用Django save_model方法来访问请求。
def save_model(self, request, obj, form, change):
if obj:
# Save the object
super().save_model(request, obj, form, change)
# Add the user instance to M2M field of the request.user (The admin User) who create the RegularUser
request.user.adminuser.usuarios.add(obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.