Django after login why the request.user is always anonymous? - django

I want to redirect a homepage after login in, but the request.user is always anonymous.Where the errors hide?
the code:
urls.py
urlpatterns = patterns('',
url(r'^login/$', login_view),
url(r'^main/$', main_view,name='main'),
)
i have a login form named forms.py
class LoginForm(forms.Form):
username = forms.CharField(required=True,
label='',
max_length=12,
error_messages={'required':'username'},
widget=forms.TextInput(
attrs={'placeholder':'username',
'class':'form-control'}))
password = forms.CharField(required=True,
label='',
max_length=12,
min_length=6,
error_messages={'required':'password'},
widget=forms.PasswordInput(
attrs={'placeholder':'password',
'class':'form-control'}))
def clean(self):
if not self.is_valid():
raise forms.ValidationError('username and password are required')
else:
cleaned_data = super().clean()
the view file:
def login_view(request):
if request.method == 'GET':
form = LoginForm(auto_id=False)
return render_to_response('game/login.html',
RequestContext(request, {'form': form,}))
else:
form = LoginForm(request.POST)
if form.is_valid():
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username,
password=password)
if user is not None and user.is_active:
auth.login(request, user)
return render_to_response('game/main.html',
context_instance=RequestContext(request))
else:
return render_to_response('game/login.html',
RequestContext(request,
{'form': form,'password_is_wrong':True}))
else:
return render_to_response('weapon/login.html',
RequestContext(request, {'form': form,}))
#login_required(login_url='/game/login/')
def main_view(request):
user = request.user
return render_to_response('weapon/main.html',
{'user':user},
context_instance=RequestContext(request))
login.html include:
<form class="form-signin" role="form" action="{% url 'game:main' %}" method="post">
{% csrf_token %}
<h2 class="form-signin-heading">Login in</h2>
{{ form.as_p }}
<label class="checkbox">
<input type="checkbox" value="remember-me"> remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
main.html include:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
{% if user.is_authenticated %}
{{ user.username }} Successful
{% else %}
failed
{% endif %}
</body>
</html>
Any suggestions would be much appreciated.

After login you are redirecting the user to game/main.html whereas in my opinion you should redirect user to main_view instead.
The code block in views.py should be:-
EDITED:
if user is not None and user.is_active:
auth.login(request, user)
return HttpResponseRedirect('/game/main')

The form in your login template is pointing to the main view action="{% url 'game:main' %}" not the login view, your form never gets handled.
You should point it to the same login view to handle the authentication, simply use action="." too keep it on the same URL as the login view or point it specifically using the same technique you're using already with main, i.e.
urlpatterns = patterns('',
url(r'^login/$', login_view, name='login'),
url(r'^main/$', main_view, name='main'),
)
And in your template:
action="{% url 'game:login' %}"

Related

Unable to login and redirect in django

I am unable to login and redirect to home page using the custom login view (user_login) and AuthenticationForm. However, if i login using the admin page (http://127.0.0.1:8000/admin) and then reopen login page it automaticaly redirects to home page.
There is some issue related to authentication which is not getting done from my custom login page/view .I am unable to fix this or identify resolution based on answers provided online.
There is another issue regarding the URL it is showing as
http://127.0.0.1:8000/login/?csrfmiddlewaretoken=FhHQjhGGgFDwcikpH9kl3OwQMcZisjWS2zvMHFGBU6KxGNWbamgago7FhtSs8MeN&username=admin&password=admin
However, Password and Username should not be showing in the URL if form method is post.
URL
urlpatterns = [
path("", views.index, name="index"),
path("signup/", views.user_signup, name="signup"),
path("login/", views.user_login, name="login"),
path("home/", views.homepage, name="home"),]
Views
def user_login(request):
if request.user.is_authenticated:
return redirect("/home")
else:
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("home")
else:
messages.error(request, "Invalid username or password.")
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(
request=request,
template_name="socialapp/login.html",
context={"login_form": form},
)
def homepage(request):
return render(request=request, template_name="socialapp/home.html")
Login HTML
<form action="{% url 'login' %}" id="login-form" method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
{% csrf_token %}
{{ login_form|crispy }}
<button type="submit" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800" value="Submit">Login</button>
</form>
Home HTML
{% block main %}
<div class="flex flex-col min-h-screen justify-center items-center ">
<h1>Welcome to Home</h1>
</div>
{% endblock main %}
Settings
LOGIN_URL = "/login"
LOGIN_REDIRECT_URL = "/home"
You need to check login in else part
def SigninView(request):
if request.method == 'POST':
form = AuthenticationForm(request, data=request.POST)
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username,password=password)
if user is None:
messages.error(request,'Please Enter Correct Credinatial')
return redirect('/signin/')
else:
login(request,user)
messages.info(request,'Login Successful')
return redirect('/dashboard/')
else:
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
form = AuthenticationForm()
return render(request,'signin.html',{'form':form})

Django Edit Profile View not saving new email value

I am (attempting to) implement the ability for a user to edit and update their email address on their profile page. I am getting no errors when doing this end to end but the new email is not being saved to the DB.
Everything seems to be working, even the redirect to the profile page in the edit_profile function, but the save() doesn't seem to be working, the users email doesn't update and when I am redirected back to the profile page, the email is still the current value.
Thanks!
Model:
class CustomUser(AbstractUser):
email = models.EmailField(_('email address'), unique=True)
is_pro = models.BooleanField(default=False)
is_golfer = models.BooleanField(default=False)
def __str__(self):
return self.email
Form
class EditProfileForm(forms.Form):
email = forms.EmailField(
label='', widget=forms.TextInput(attrs={'class': 'form-field'}))
View
#login_required
def edit_profile(request):
if request.method == "POST":
form = EditProfileForm(request.POST)
if form.is_valid():
email = form.cleaned_data["email"]
user = CustomUser.objects.get(id=request.user.id)
user.save()
return redirect("typeA", username=user.username)
else:
form = EditProfileForm()
return render(request, "registration/edit_profile.html", {'form': form})
URLS
urlpatterns = [
path('type_a_signup/', ASignUpView.as_view(), name='a_signup'),
path('type_b_signup/', BSignUpView.as_view(), name='b_signup'),
path('login/', LoginView.as_view(), name='login'),
path('password_reset', PasswordResetView.as_view(), name='password_reset'),
path('typea/<username>/', typeA, name='typeA'),
path('typeb/<username>/', typeB, name='typeB'),
path('login_success/', login_success, name='login_success'),
path('edit_profile/', edit_profile, name='edit_profile'),
]
Template
<div class="container">
<div class="form-container">
<h2>Edit profile</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div>
{{ form.email.label_tag }}
<input type="text" class="form-control {% if form.email.errors %}is-invalid{% endif %}" id="id_email"
name="email" value='{{ form.email.value|default:user.email }}'>
{% if form.email.errors %}
<div>{{ form.email.errors }}</div>
{% endif %}
</div>
<button type="submit">Submit</button>
</form>
<br>
</div>
You never set the email field of the object. You should set this with:
#login_required
def edit_profile(request):
if request.method == "POST":
form = EditProfileForm(request.POST)
if form.is_valid():
email = form.cleaned_data["email"]
user = request.user
user.email = email # 🖘 set the email field
user.save()
return redirect("typeA", username=user.username)
else:
form = EditProfileForm()
return render(request, "registration/edit_profile.html", {'form': form})
You should only redirect in case the form is successful. If it is not, Django will rerender the form with the errors.

{ % include tag %} including only one object from another template

guys i need a small help
here is my views.py
def signup(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
verification=VerificationForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
username = userObj['username']
email = userObj['email']
password = userObj['password']
return HttpResponseRedirect('/index/verification/')
# if
if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()):
User.objects.create_user(username, email, password)
user = authenticate(username = username, password = password)
login(request, user)
return HttpResponseRedirect('/')
else:
raise forms.ValidationError('Looks like a username with that email or password already exists')
else:
raise forms.ValidationError('a valid')
else:
form = UserRegistrationForm()
verification = VerificationForm()
return render(request, 'question/signup.html',context= {'verification':verification,'form' : form})
here you can see i have declared two context variables one is form and the other one is verification now i want to use
now this is my signup.html
{% extends 'question/index.html '%}
{% block body_block %}
<div class="conrainer">
<form method="POST">
{% csrf_token %} {{ form.as_p }}
<button type="submit">Submit</button>
</form>
facebook auth
</div>
{% endblock %}
now i have used form variable in this page
and i want to use verification varible in another page as django views are not made to use two templates in a single view
after searching a lot in online forums i came to know about {% include tag %}
after trying to use that tag after going through documentation
this is how my verification.html is
{% include 'question/signup.html' with obj=verification only%}
<div class="container">
<form method="post">{% csrf_token %}
<p>{{verification.as_p}}</p>
<p>{{obj.as_p}}</p>
<input type="submit" name="verify" value="" action='.' align='center'name='submit'>
</form>
</div>
here is my urls.py file
urlpatterns = [
# url(r'^/',views.home,name='home'),
url(r'^home/',Home,name='home'),
url(r'^ques/',Create.as_view(success_url="/index/home/"),name='ques'),
url(r'^signup/',signup,name='signup'),
# url(r'^signup/',MyFormView.as_view(),name='signup'),
url(r'^verification/',TemplateView.as_view(template_name="question/verification.html")),
url(r'^logout/$', auth_views.logout,name='logout'),
url(r'^search/',Search,name='search'),
url(r'^accounts/', include('allauth.urls')),
# url(r'^verify/',verificationView,name='signup'),
# CreateView.as_view(model=myModel, success_url=reverse('success-url'))
]
but after trying it so many ways either obj or verification shows up in the site is there any way where i can only get the context object instead of getting the subit button and all from my signup.html using INCLUDE any kind of help is appreciated

Register Page instantly buffering

When I tried to register in my site, it's instantly buffering,
The server is working properly and others were coded finely.
The urls.py
urlpatterns = [
#Login Page
url(r"^login/$", login, {'template_name':'users/login.html'},
name='login'),
#Logout Page
url(r"^logout/$", views.logout_view, name="logout"),
# Registration Page
url(r"^register/$", views.register, name='register'),
]
The views.py
def register(request):
"""Register a new user."""
if request.method != "POST":
#display blank register form.
form = UserCreationForm()
else:
# process completed form.
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
# Log the user in and then redirect to home page
authenticate_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(request, authenticate_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form': form}
return render(request, 'users/register.html', context)
Double checked I am in the right views.py
The register.html is:
{% extends "learning_logs/base.html" %}
{% block content %}
<form action="{% url "users:register" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">log in</button>
<input type="hidden" name="next" value="{% url "learning_logs:index" %}">
</form>
{% endblock content %}
Where might be the problem live?

django login Exception Value: 'unicode' object is not callable

I'm attempting to setup a login using django and bootstrap found here and here
my views.py
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
else:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
else:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
else:
form = LoginForm()
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
my urls.py
from core.views import LoginRequest, LogoutRequest, ContactRequest
urlpatterns = patterns('',
url(r'^login/$', 'LoginRequest'),
url(r'^logout/$', 'LogoutRequest'),
my forms.py
class LoginForm(forms.Form):
email = forms.CharField(label=(u'Email'), max_length=30)
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False), max_length=30)
And the snippet from my index.html -
{% if user.is_authenticated %}
<li><a href={% url 'dashboard' %}>Dashboard</a></li>
{% else %}
<li class="dropdown">
<a class="dropdown-toggle" href="#" data-toggle="dropdown">Login<strong class="caret"></strong></a>
<div class="dropdown-menu" style="padding: 15px; padding-bottom: 10px;">
<form action='/login/' method="POST">
{% csrf_token %}
{% if form.errors %}
{{ form.errors}}
{% endif %}
<label for="id_email">Login:</label>
<input type="text" name="email" id="id_email">
<br />
<label for="id_password">Pass:</label>
<input type="password" name="password" id="id_password">
<br />
<input class="btn btn-primary" type="submit" value="Login" />
<input type="hidden" name="next" value="{{ '/dashboard' }}" />
</form>
</div>
</li>
{% endif %}
As soon as I hit "login" I get the following traceback -
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
Exception Type: TypeError at /login/
Exception Value: 'unicode' object is not callable
In your urls file, you need to remove the string around the view names.
Like this:
urlpatterns = patterns('',
url(r'^login/$', LoginRequest), #Shred the quotes
url(r'^logout/$', LogoutRequest), #Shred the quotes
Note that the new django recommended way is:
from core import views
urlpatterns = patterns('',
url(r'^login/$', views.LoginRequest),
url(r'^logout/$', views.LogoutRequest),
Also, you can simplify your view like this:
def LoginRequest(request):
redirect_to = request.META.get('HTTP_REFERER', '/')
if request.user.is_authenticated():
return HttpResponseRedirect(redirect_to)
form = LoginForm()
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(redirect_to)
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
Also, / needs to be something like: /index.html - depends on where the template is located.