将用户转换为经理后,我需要设置"is_employe=False"one_answers"is_manager=True"。这个过程看起来很简单,但我无法让它发挥作用。
型号.py
class User(AbstractUser):
is_admin = models.BooleanField(default=False)
is_employee = models.BooleanField(default=True)
is_manager = models.BooleanField(default=False)
def __str__(self):
return f'{self.first_name} {self.last_name} as {self.username}'
class Manager(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
user_profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
business_unit = models.OneToOneField(BusinessUnit, on_delete=models.SET_NULL, null=True)
previous_business_units = models.CharField(max_length=100, default=None, blank=True, null=True)
manager_description = models.TextField(blank=True, null=True)
manager_created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return f'{self.user.first_name} {self.user.last_name}'
views.py
@login_required
@admin_required
def manager_create_view(request):
form = ManagerCreationForm()
if request.method == 'POST':
form = ManagerCreationForm(request.POST)
if form.is_valid():
new_manager = form.save(commit=False)
group = Group.objects.get(name='Manager')
new_manager.user.groups.add(group)
new_manager.user.is_employee = False
new_manager.user.is_manager = True
new_manager = form.save()
new_manager = form.cleaned_data.get('user')
messages.success(request, f'{new_manager} is now a Manager!')
return redirect ('list-managers')
messages.error(request, 'Something went wrong, please check the hilighted field(s)')
context = {
'title': 'Create Manager',
'form': form
}
return render(request, 'managers/manager-form.html', context)
我也试着使用信号,但没有成功。
信号.py
from django.db.models.signals import post_save
from accounts.models import User, Manager
from django.dispatch import receiver
@receiver(post_save, sender=Manager)
def change_user_type(sender, instance, created, **kwargs):
if created:
instance.user.is_manager = True
instance.user.is_employee = False
我试着自己学习,所以任何帮助都将不胜感激!:(
您需要保存管理器的用户,而不仅仅是管理器本身,因此:
@login_required
@admin_required
def manager_create_view(request):
form = ManagerCreationForm()
if request.method == 'POST':
form = ManagerCreationForm(request.POST)
if form.is_valid():
new_manager = form.save() # 🖘 save the manager object
group = Group.objects.get(name='Manager')
user = new_manager.user
user.groups.add(group)
user.is_employee = False
user.is_manager = True
user.save()# 🖘 save the user object
messages.success(request, f'{user} is now a Manager!')
return redirect('list-managers')
messages.error(request, 'Something went wrong, please check the hilighted field(s)')
context = {
'title': 'Create Manager',
'form': form
}
return render(request, 'managers/manager-form.html', context)