login_view
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request=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)
messages.info(request, f"You are now logged in as {username}")
return HttpResponseRedirect(reverse('Users:index'))
else:
messages.error(request, "Invalid username or password.")
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request = request,
template_name = "Users/login.html",
context={"form":form})
And the login html is
{% extends "Users/home.html" %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'Users:login' %}">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">log in</button>
<input type="hidden" name="next" value="{% url 'Users:index' %}" />
</form>
{% endblock content %}
I’m able to login as a admin but cannot able to register as alumini when i click register after filling the form it is not saving and not logging me in.Here is the alumini_register view
def alumini_register(request):
if request.method !='POSt':
form=AluminiSignUpForm()
else:
form=AluminiSignUpForm(data=request.POST)
if form.is_valid():
new_user=form.save()
# log the user in and then redirect to home page.
authenticated_user=authenticate(username=new_user.username,password=request.POST['password'])
login(request,authenticated_user)
return HttpResponseRedirect(reverse('Users:index'))
context={'form':form}
return render(request,'Users/alumini_register.html',context)
And sometimes it showing csrf token not defined properly when i tried to register
Here is the code for alumini_register.html
{% extends "Users/home.html" %}
{% block content %}
<form method="post" action="{% url 'Users:alumini_register' %}">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">register</button>
</form>
{% endblock content %}
And here is the code for urls.py for the app
from django.urls import path,re_path
from django.conf.urls import url
from .views import classroom
from django.contrib.auth import login
app_name='Users'
urlpatterns=[
path('',classroom.home,name='index'),
path('topics/',classroom.topics, name='topics'),
re_path(r'^topics/(?P<topic_id>\d+)/$',classroom.topic,name='topic'),
url(r'^new_topic/$', classroom.new_topic, name='new_topic'),
url(r'^new_entry/(?P<topic_id>\d+)/$',classroom.new_entry,name='new_entry'),
url(r'^edit_entry/(?P<entry_id>\d+)/$', classroom.edit_entry,name='edit_entry'),
url(r'^login/$',classroom.login_view,name='login'),
url(r'^logout/$',classroom.logout_view,name='logout'),
url(r'^alumini_register/$',classroom.alumini_register,name='alumini_register'),
url(r'^college_register/$',classroom.college_register,name='college_register'),
]