48071

Django- why inbuilt auth login function not passing info about user to after successful login url

Question:

Hi I used the django inbult auth urls and views for my project and now have finished the initial user account creation/login/reset password process.

Now, the user can log in and be redirected to the after successful login url accounts/profile/.

I have several doubts on the django login function. For convenience, I've copy paste the django inbuilt login function code below.

@sensitive_post_parameters() @csrf_protect @never_cache def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.REQUEST.get(redirect_field_name, '') if request.method == "POST": form = authentication_form(request, data=request.POST) if form.is_valid(): # Ensure the user-originating redirection url is safe. if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) # Okay, security check complete. Log the user in. auth_login(request, form.get_user()) return HttpResponseRedirect(redirect_to) else: form = authentication_form(request) current_site = get_current_site(request) context = { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context, current_app=current_app)

My questions are:

<strong>1 Is the REDIRECT_FIELD_NAME in the function set as '/profile/' in django.contrib.auth ?</strong>

I could see this variable is imported from django.contrib.auth

from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout, get_user_model

I don't have any setting for this variable, but after user successfully logged in, the page will be directed to /accounts/profile/

<strong>2 Has the login function passed the account info about the user? If yes, how can I access it?</strong>

From the code, if user successfully logged in, page will be redirected: return HttpResponseRedirect(redirect_to)

in my case, redirected to accounts/profile/ , initially the view for the url was simply a

HttpResponse("You have logged in successfully")

now when I am trying to implement the view function, I realize that no info about the user has been passed.

I've tried to print request in the view function, but there is no info about the user in the message printed in the server terminal, all I get is a long list of system settings or other info. However, the login should pass the info of who has just successfully logged in to the successful log in urls right?

Thank you very much for explaining.

Answer1:

After the login, you can access the user info by referring request.user in views and just {{user}} in templates. All you need to make sure is you're passing the <a href="https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext" rel="nofollow">RequestContext</a> in the HttpResponse for the future request.

Yes, REDIRECT_FIELD_NAME is defined in <a href="https://github.com/django/django/blob/master/django/contrib/auth/__init__.py#L12" rel="nofollow">__init__.py</a> of django.contrib.auth which is simply a "next" what you passed from the login form.

In Django, there are more than one ways to force a user to login. By decorating a view function with @login_required, by calling the build-in login view for an user defined URL and etc., Refer about the login settings variables <a href="https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url" rel="nofollow">here</a>. You'll get some more ideas.

<a href="http://www.fir3net.com/Django/django.html" rel="nofollow">Building custom login page</a>. That link gives you an example for custom login implementaion. Consider you have decorated a view with @login_required and it's corresponding URL is /login_test/. Then the {{next}} context variable in the login form will be rendered with /login_test/. So after you login,

<input type="hidden" name="next" value="{{ next }}" />

This element's value will be taken for redirecting as per the REDIRECT_FIELD_NAME. Though I suspect that that example is missing the setting of settings.LOGIN_URL to the URL login/. Never mind, it's being passed as an argument in the decorator itself.

Answer2:

To override this behavior just put following in settings.py of your app :

LOGIN_REDIRECT_URL = "/"

This will redirect to your home page. You can change this url to preferred url.

Answer3:

Once the user is redirected to accounts/profile/ the view for that link will be returned. You can access information about the currently logged in user there as per this <a href="https://stackoverflow.com/questions/1477319/in-django-how-do-i-know-the-currently-logged-in-user" rel="nofollow">post</a> by using request.user. Also tip to see what information you have access to in your views. Use import pbd; pdb.set_trace(). This pops you into a python prompt with access to all of the current variables. To see all the defined variables call locals(), though this will print out a ton of junk along with it. In the template you can <a href="https://stackoverflow.com/questions/13713077/get-user-information-in-django-templates" rel="nofollow">display</a> a "you can't access this page" message if the user isn't logged in.

Recommend

  • How to get site name in django template?
  • Error with django middleware
  • Android NFC read Tags issue. Activity starts each time on data received
  • openssl handshake failed
  • How to resolve docker host names (/etc/hosts) in containers
  • Loading Bitmap to ImageView from URL in android
  • What is the difference between a “service account” and an “installed application”?
  • IE10 strips out hashtag from the URL
  • Need code translation from VB to C#
  • Change Checkbox value without raising event
  • Synchronize windows folders
  • Is there a way to dynamically embed PDF Files in a JSP pulled from the file system?
  • Magento get URL before current
  • Retrieving specified columns from a list of csv files to create a data data frame in R
  • Prevent Tomcat from caching request during starup
  • Primefaces ManyCheckbox inside ui:repeat calls setter method only for last loop
  • using System.Speech.Synthesis with Windows10 universal app (XAML-C#)
  • Check all values in string[] for length?
  • Image map in Flex
  • Build Successful but not running on simulator
  • Django model inheritance, filtering models
  • Jquery popup on mouse over of calendar control
  • How do I signal completion of my dataflow?
  • Check for zero lines output from command over SSH
  • How to use JavaScript to determine whether a file exists in a directory?
  • Eloquent update method change created_at timestamp
  • Visual Studio 2010 debugger build correctly - compiler pdb and linker pdb not in synch?
  • How to get Eclipse Oxygen to run on Java 9
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • How to clear text inside text field when radio button is select
  • How to avoid particles glitching together in an elastic particle collision simulator?
  • Recording logins for password protected directories
  • Splitting given String into two variables - php
  • Check if a string to interpolate provides expected placeholders
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Upload files with Ajax and Jquery
  • XCode can't find symbols for a specific iOS library/framework project
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • need help with bizarre java.net.HttpURLConnection behavior