Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm having some trouble logging in users. I have the following views and template:
views.py
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('disabled account')
else:
return HttpResponseRedirect('/invalid')
else:
return render(request, 'login_page.html', {})
login_page.html
{% block content %}
{% if form.errors %}
<p class="error"> sorry, thats not a valid username or password</p>
{% endif %}
<form action="/login/" method="post">
<label for="username">User name:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="text" name="password" value="" id="password">
<input type="submit" value="login" />
</form>
{% endblock %}
My problem is, whenever i hit submit in the login form, no matter what the values are, the page is redirected to the /invald/ url. I have a user set up using the admin function but i still keep getting this error. Does anyone know what the problem may be?
Do i need a forms.py file with anything in it?
Updated views:
def login(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('loggedin.html')
else:
return HttpResponse("Account deleted or disabled")
return render(request, "login_page.html", {'form': form})
updated form:
from django import forms
from django.contrib.auth import authenticate, login, logout, get_user_model
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("User does not exist.")
if not user.is_active:
raise forms.ValidationError("User is no longer active.")
return super(UserLoginForm, self).clean(*args, **kwargs)
updated login_page.html
{% block content %}
{% if form.errors %}
<p class="error"> sorry, thats not a valid username or password</p>
{% endif %}
<form action="{% url 'login' %}" method="post">
{{ form }}
<input type="submit" value="login" />
</form>
{% endblock %}
urls:
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login, name='login'),
url(r'^logout/', views.logout, name='logout'),
url(r'^invalid/', views.invalid_login, name='invalid_login'),
url(r'^loggedin/', views.loggedin, name='loggedin'),
url(r'^$', views.index, name='index'),
–
–
reg = User()
reg.username = request.POST['register_username']
reg.set_password(request.POST['register_password']) #like this line
reg.save()
not reg.password=request.POST['register_password']
I suggest you make a forms.py file and in here make a class like so:
from django import forms
from django.contrib.auth import authenticate, login, logout, get_user_model
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("User does not exist.")
if not user.is_active:
raise forms.ValidationError("User is no longer active.")
return super(UserLoginForm, self).clean(*args, **kwargs)
Then in your views import Login form. Create a view as such:
def my_login_view(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('someurl')
else:
return redirect('someotherurl')
return render(request, "your_template_to_process_this_view", {'form': form})
In your html template you can call the form using the convention below. For this shortcut to the url to work you need an app_name = "yourappname" at the top of your url file.
<form method="POST" action="{% url 'yourappname:name_given_to_url_in_urls_file' %}">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn-success" value="Login"/>
</form>
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.