I have an extended User model that is related to the employee Separation model and I would like to set that User as inactive with the SeparationCreateView. It's like when an employee leaves the company, it is recorded with this separation view and it is disabling employee access to the app automatically.
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
class Separation(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
Separation create view is working but it is not setting the user is_active to false
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)
What am I doing wrong here? Any help is highly appreciated.
CodePudding user response:
You need to save the corresponding employee, so:
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)
we can make this slightly more efficient with:
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)
the latter will not run signals attached to the user model.