By default after login django redirects the user to an accounts/profile page or if you edit the LOGIN_REDIRECT_URL you can send the user to another page you specify in the settings.py.
This is great but I would like the user (after login) to be redirected to a custom page where the link to that page would look something like this: mysite.com/username
. So the default accounts/profile or the LOGIN_REDIRECT_URL settings would not work in this case since both are somehow static. In my case the username
section of the address changes for every user.
Any ideas how I can make it so when the user is logged in would go to a custom user page that has user's name in the address like: mysite.com/username
? Any input is truly appreciated.
If you're using Django's built-in
LoginView
, it takesnext
as context, which is "The URL to redirect to after successfullogin
. This may contain a query string, too." (see docs)Also from the docs:
"If login is successful, the view redirects to the URL specified in
next
. If next isn’t provided, it redirects tosettings.LOGIN_REDIRECT_URL
(which defaults to /accounts/profile/)."Example code:
urls.py
login.html
You can authenticate and log the user in as stated here: http://docs.djangoproject.com/en/dev/topics/auth/#how-to-log-a-user-in
This will give you access to the User object from which you can get the username and then do a HttpResponseRedirect to the custom URL.
A simpler approach relies on redirection from the page LOGIN_REDIRECT_URL. The key thing to realize is that the user information is automatically included in the request.
Suppose:
and you have configured a urlpattern:
Then, all you need to write for the view
home()
is:where
NAME_OF_PROFILE_VIEW
is the name of the callback that you are using. With django-profiles,NAME_OF_PROFILE_VIEW
can be 'profiles_profile_detail'.Yes! In your settings.py define the following
And have '/your-path' be a simple View that looks up
self.request.user
and does whatever logic it needs to return aHttpResponseRedirect
object.A better way might be to define a simple URL like
'/simple'
that does the lookup logic there. The URL looks more beautiful, saves you some work, etc.Got into django recently and been looking into a solution to that and found a method that might be useful.
So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:
Then create a view that captures it in one of your apps, for example:
Where the urlpatterns capture would look like this:
Works well for me.