Reputation: 4937
I have a field on my user profile model to see if a user:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
...
password_change_required = models.BooleanField(default=True)
Is their a way I can redirect all views like this:
if request.user.profile.password_change_required:
redirect(....)
Where can I put this logic so it hits all views?
Upvotes: 1
Views: 1389
Reputation: 2422
Use Middleware:
During the request phase, before calling the view, Django applies middleware in the order it’s defined in MIDDLEWARE, top-down.
You can think of it like an onion: each middleware class is a “layer” that wraps the view, which is in the core of the onion. If the request passes through all the layers of the onion (each one calls get_response to pass the request in to the next layer), all the way to the view at the core, the response will then pass through every layer (in reverse order) on the way back out.
If one of the layers decides to short-circuit and return a response without ever calling its get_response, none of the layers of the onion inside that layer (including the view) will see the request or the response. The response will only return through the same layers that the request passed in through.
Which should do what you want so long as your ordering is correct (e.g. after auth middleware so request.user
is available).
Upvotes: 4
Reputation: 93
class ProfileUpdateView(UpdateView):
def get(self, request, *args, **kwargs):
if not request.user.profile.password_change_required:
return super(ProfileUpdateView, self).get(request, *args, **kwargs)
else:
return redirect('/accounts/change-password/?next=%s' % request.path)
make sure you also import redirect
from django.shortcuts import redirect
Upvotes: 1