[Fixed]-Need success_url to vary depending on user group in CreateView

1👍

It’s not possible to access the user in the class definition as you are doing. Instead, the CreateView has a get_success_url method, which allows you to set the success view dynamically.

In the method, you can access the request with self.request, therefore you can access the logged in user with self.request.user.

class ServiceAddBlankView(generic.CreateView):

    def get_success_url(self):
        if self.request.user.groups.filter(name="Owner").exists():
            return '/wesapp/services/'
        elif self.request.user.groups.filter(name="Employee").exists():
            return '/wesapp/service_list/'
        else:
            return '/fallback/url/'

I’ve changed the query to check whether the user is in the Owner or Employee group. In your original code, you were unnecessarily loading every Owner and Employee. Note that my code is behaves slightly different if the user is an Owner and an Employee – if that’s important, you need to change it.

0👍

Django’s request object has access to the user. Refer to request.user as documented here :

https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.HttpRequest.user

Leave a comment