1๐
โ
As I understand, in simplest case you need something like this.
from django import forms
from django.contrib.auth import authenticate
class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=254)
password = forms.CharField(widget=forms.PasswordInput)
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is None:
raise forms.ValidationError('invalid_login')
return self.cleaned_data
Now view:
from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
def user_login(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
login(request, form.get_user())
# if you use named views you can use reverse here:
# redirect_url = reverse('post_list')
# Or even if you want to return back to previous url:
# referrer = request.META['HTTP_REFERER']
# if referrer:
# redirect_url = referrer.split('/', 3)[3]
redirect_url = '/post-list/' # it's 'success page'
return HttpResponseRedirect(redirect_url)
else:
form = AuthenticationForm(request)
return TemplateResponse(request, 'login.html', {'form': form})
And now you can use login_required
decorator for your POST views (create/update/delete), for example:
from django.contrib.auth.decorators import login_required
@login_required(login_url='/accounts/login/')
def post_delete(request, id=None):
...
Simplest example for login form (template):
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
Username: {{ form.username }} {{ form.username.errors }}<br>
Password: {{ form.password }} {{ form.password.errors }}<br>
{{ form.errors }}<br>
<input type="submit" value="login" />
</form>`
๐คMark Mishyn
Source:stackexchange.com