我有一个与员工分离模型相关的扩展用户模型,我想用SeparationCreateView将该用户设置为非活动状态。这就像当一个员工离开了公司,它记录这种分离视图和禁用自动员工访问应用程序。
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
class Separation(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
创建视图分离工作但不是设置用户is_active假
class SeparationCreateView(LoginRequiredMixin, CreateView):
model = Separation
form_class = SeparationForm
template_name = 'coreHR/separation.html'
success_url = reverse_lazy('corehr:separations')
def form_valid(self, form):
separation = form.save(commit=False)
separation.employee.user.is_active = False
separation.save()
return super().form_valid(form)
我在这里做错了什么?如有任何帮助,不胜感激。
您需要保存相应的员工,因此:
class SeparationCreateView(LoginRequiredMixin, CreateView):
# ⋮
def form_valid(self, form):
user = form.save().employee.user
user.is_active = False
user.save()
return super().form_valid(form)
我们可以稍微提高效率:
from django.contrib.auth import get_user_model
class SeparationCreateView(LoginRequiredMixin, CreateView):
# ⋮
def form_valid(self, form):
separation = form.save()
User = get_user_model()
User.objects.filter(
employee__separation=separation
).update(is_active=False)
return super().form_valid(form)
后者将不运行附加到用户模型上的信号。