Django request.user become AnonymousUser after redirect - django

The problem here is that request.user always turn to AnonymousUser after redirect.
I'm writing my own login method and authentication backend because I'm not using password for login.
Here's my code.
#app/view.py
def login(request):
template = 'index.html'
if request.method == "POST":
userId = request.POST.get('userId', '')
displayName = request.POST.get('displayName', '')
user = auth.authenticate(userId=userId, displayName=displayName)
if user.is_authenticated:
auth.login(request, user)
return redirect('home') ##### if change to "render(request, template, locals())", will see request.user as logged in user #####
else:
return render(request, template, locals())
else:
return HttpResponse('')
def home(request):
template = 'index.html'
user = request.user
return render(request, template, locals())
I'm checking whether the request.user is logged in by javascript. If not, use a post function to /login/ URI. The liff.getProfile() is my third party javascript function to get userId and displayName from profile.
#html.javascript
DjangoLogin="{{request.user}}";
if (DjangoLogin=="AnonymousUser"){
liff.getProfile().then(function(profile) {
userId = profile.userId;
displayName = profile.displayName;
post('/login/',{ 'userId': userId, 'displayName': displayName, 'csrfmiddlewaretoken': '{{ csrf_token }}'});
});

Related

Django: How to send username across all the pages once the user is logged in

Here is the login method in the view:
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('forum')
else:
messages.info(request, 'Username or password is wrong!')
return render(request, 'login.html')
return render(request, 'login.html')
Here is how I wrote my codes:
In the views module: I've register method and login method which both work properly.
However, I've other methods who required login in order to access them, since I redirect only a page at a time, I can't get the same username across the pages that required login before to access them.
Now the problem is, how to create another page who treats data came from the forum by conserving the same username from the loggin.
PS: In the forum, I can get the username but how to maintain the same username, is the problem
Thanks :)
If I understood the issue, you want to use user after login.
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('forum')
else:
messages.info(request, 'Username or password is wrong!')
return render(request, 'login.html')
return render(request, 'login.html')
def another_page(request, *args, **kwargs):
user = request.user
...
In every template you can get username from user object:
{% if user.is_authenticated %}
{{ user.username }}
{% endif %}
user is an object that django shares to it's templates

Django redirect not working when I submit my form

My redirect for my login page is not working correctly when I submit a form.
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form': form,
}
print(request.user.is_authenticated)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
print(request.user.is_authenticated)
login(request, user)
# Redirect to a success page.
return redirect("login")
else:
# Return an 'invalid login' error message.
print("Error")
return render(request, "content/login.html", context)
I am expecting it to redirect to same page and print an output that lets me know the authentication worked. But this is what actually happens..
Page not found(404)
Request Method: GET
Request URL:http://127.0.0.1:8000/login/POST?username=stone&password=pass
Any idea as to what is going on?
You haven't shown your template, but it looks like you have action="POST" instead of method="POST" in your form tag.
Be sure, that your template.html looks like this:
<form method="post">
{% csrf_token %}
{{ form }}
</form>
def login_user(request):
if request.user.is_authenticated():
return redirect(reverse('homepage'))
form = LoginForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
if user is not None:
login(request, user)
return redirect(reverse('homepage'))
else:
error_message = "* Password you entered is incorrect."
return render(request, "account/login.html",{
"form": form,
"error_message": error_message,
})
else:
return render(request, "account/login.html", {
"form": form,
})

Redirect to home as a logged in user after successful registration

I have a custom User model (MyUser), and a registering form (UserCreationForm) for that model. After registering the user I want it to redirect to the homepage. It is however redirecting to the homepage, but the problem is that the user is not logged in even after login() function is used in the register view, and so it is redirected back to the login page.
views.py:
#login_required(login_url='/account/login/')
def home(request):
return render(request, 'home.html')
def login_view(request):
form = LoginForm(request.POST or None)
if request.POST and form.is_valid():
user = form.login(request)
if user:
login(request, user)
return redirect("/")# Redirect to a success page.
return render(request, 'login.html', {'form': form })
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("/")
else:
form = UserCreationForm()
return render(request, 'register.html', {
'form': form
})
Its giving me an error:
AttributeError at /account/register/
'MyUser' object has no attribute 'backend'
What am I doing wrong here? Please help me how to solve this. Thank you.
Maybe, this can solve your problem.
This will authenticate and login the user after registration.
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
password = self.request.POST.get('password', None)
authenticated = authenticate(
username=user.username,
password=password
)
if authenticated:
login(request, authenticated)
return redirect("/")
else:
form = UserCreationForm()
return render(request, 'register.html', {
'form': form
})

Django : request.user not set after redirect

Specifically, after authentication and redirect, request.user is an anonymous user.
login (view function)
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
#django.contrib.auth.login
Login(request, form.get_user())
str = reverse('cm_base.views.index')
return HttpResponseRedirect(str)
else:
# Their password / email combination must have been incorrect
pass
else:
form = LoginForm()
return render_to_response('cm_base/login.html',
{"DEBUG": True,
'form' : form
},
context_instance=RequestContext(request))
in the index view, I removed the login_required decorator and tested the request.user object
def index(request):
test = request.user.is_authenticated()
return render_to_response('cm_base/index.html',
{"DEBUG": True,
"user": request.user,},
context_instance=RequestContext(request))
Test returns false.
Fix
I ended up just calling the index view directly. I am still confused as to why the user object was lost when I called HttpResponseRedirect.
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST) # Not shown in this example
if form.is_valid():
Login(request, form.get_user())
str = reverse('cm_base.views.index')
return index(request)
else:
# Their password / email combination must have been incorrect
pass
else:
form = LoginForm()
A lot of things going on here that shouldn't be. First, you don't need to pass request.user, its available by default as long as you are using RequestContext, which you are.
Login() this method, what exactly is it doing? Django provides a built-in login method that you should be using if you are using the default authentication backend.
You are also not checking if a user is enabled or disabled.
Here is a different version of your code, adapted from the example in the documentation:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
def login_view(request):
form = LoginForm(request.POST or {})
ctx = {'form': form}
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username, password)
if not user:
ctx['errors'] = 'Invalid Login'
return render(request, 'login.html', ctx)
if not user.is_active:
ctx['errors'] = 'User is locked'
return render(request, 'login.html', ctx)
login(request, user)
return redirect('home')
else:
return render(request, 'login.html', ctx)
What auth backend are you using? If it is something other than the ModelBackend make sure your get_user method is correct. It sounds as if the auth middleware is sending a different identifier (like the pk instead of a username) than the one you are looking for in your get_user method.
This was the fix
<link rel="icon" href="{{ STATIC_URL }}img/favicon.ico" />
This file was missing from the static directory. The resulting 404 was breaking the user session.

Django Creating custom URL for user profile

I have an app which allows users to create a profile and log in.
When a user login , he is redirected to 127.0.0.1:8000/profile/
The problem is , I want to customize the URL by adding the user's username to the end of URL e.g example 127.0.0.1:8000/profile/michael
This is a similar question to mine
Django - after login, redirect user to his custom page --> mysite.com/username
"get the username and then do a HttpResponseRedirect to the custom URL."
I just can't seem to figure out how could I pass a username as an argument for HttpResponseRedirect to process into a the custom URL properly.
return HttpResponseRedirect('/profile/?username=%s' % (username, request.path))
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
person = Person.objects.get(user=request.user)
return render(request,'profile.html',{'person':person})
my URL
url(
r'^profile/$',
'pet.views.Profile',
name = 'Profile'
),
NEW
my views.py
def LoginRequest(request):
if request.user.is_authenticated():
username = User.objects.get(username=request.user)
url = reverse('Profile', kwargs = {'username': username.username})
return HttpResponseRedirect(url)
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
Person = authenticate(username=username, password=password)
if Person is not None:
login(request, Person)
username= User.objects.get(username=request.user)
url = reverse('Profile', kwargs = {'username': username.username})
return HttpResponseRedirect(url)
return render(request, 'login.html',{'form': LoginForm()})
url(
r'^login/$',
'pet.views.LoginRequest',
name = 'LoginRequest'
),
url(
r'^profile/(?P<username>\w+)/$',
'pet.views.Profile',
name = 'Profile'
),
def Profile(request,username):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
board = Board.objects.filter(user=request.user)
person = Person.objects.get(user__username=username)
return render(request,'profile.html',{'board':board ,'person':person})
This would be the proper regex for your redirect URL, ie. don't modify the one you have.
url(r'^profile/(?P<username>\w+)/$', 'pet.views.myprofileview', name="detail_profile")
And then to pass an argument to the redirect:
url = reverse('detail_profile', kwargs={'username': profile.firstname})
return HttpResponseRedirect(url)
This leads to also having to define a new view:
def myprofileview(request, username):
person = Person.objects.get(user = request.user)
return render(request,'profile.html',{'person':person})
This would eliminate two behaviours in one view, which I find to be very nice!
We do it this way because it's a string that HttpResponseRedirect accepts so we have to build it accordingly.
This will make a redirect to the myprofileview view and "style", if you could call it that, your url /profile/michael/.
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:Profile',
kwargs={'username': request.user.username}))
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
Person = authenticate(username=username, password=password)
if Person is not None:
login(request, Person)
return HttpResponseRedirect(reverse('world:Profile',
kwargs={'username': username}))
return render(request, 'login.html',{'form': LoginForm()})