Login problem

I have created the users from admin page and when I’m trying to login. It is not working


Here is the users and when I’m trying to login it is not working out.

The login view and html files are as follows and also I’m unable to register using aluminiregister there also the same problem.Can anyone help me out to find the mistake what I’ve done .

please, help me, It’s a multiple user type and i have a registered alumini (which i’ve created using admin page bcoz i’m unable to register using the alumini register page) and when i’m trying to login after clicking login .It’s not logging me in and sometimes it’s showing csrf_token not defined properly though i’ve defined it

When you want to post code here, please don’t post images. They’re hard to read and impossible to quote lines.

When posting source code, enclose it between lines consisting of only three backtick - ` characters. That means you’ll have one line of ```, then your code, then another line of ```. This preserves the formatting of the code making it a lot easier to read - especially with statements where indentation is critical.

example:

# The line above this is ```
def function(self):
    return self
# The line after this is ```

Ken

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'),

]

sorry I’m new here and I’ll not repeat it again.
Please look at my issue

The ‘t’ in your conditional above should be a capital T. (It should be POST, not POSt.)

If that’s not the issue, then I think we also need to see the AlumniSignUpForm.

Ken

Thank you ,Sir for your instant response .
That was the error .
This community is really amazing

hi have you got solution for your problem, i am also having same issue, i am unable to authenticate normal user in website

def userlogin(request):
if request.method == “POST”:
fm = AuthenticationForm(request=request, data=request.POST)
if fm.is_valid():
username = fm.cleaned_data.get(‘username’)
password = fm.cleaned_data.get(‘password’)
user = authenticate(request,username=username, password=password)
if user is not None:
login(request, user)
return redirect(‘/jobseekersprofile/’)
else:
fm = AuthenticationForm()
return render(request, ‘jobglobel/userlogin.html’, {‘form’: fm})

Your issue, as described in the other thread, is that you are not creating your users properly. Your code as described here is not the problem.

models.py

from django.contrib.auth.models import BaseUserManager, AbstractBaseUser,PermissionsMixin
from django.conf import settings


class jobglobeluserManager(BaseUserManager):
    use_in_migrations = True
    username = None
    def create_user(self, email=None, password=None, **extra_fields):
        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)  
        extra_fields.setdefault('is_superuser', True)  
        extra_fields.setdefault('is_active', True)
        extra_fields.setdefault('is_admin', True)


        if extra_fields.get('is_staff') is not True:  
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:  
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(email, password, **extra_fields)


    

class jobglobeluser(AbstractBaseUser,PermissionsMixin):
    joined_on = models.DateTimeField(auto_now_add=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    useris = models.CharField(max_length=30,null=True)
    FirstName = models.CharField(max_length=20)
    LastName = models.CharField(max_length=20)
    email = models.CharField(unique=True,max_length=100)


    objects = jobglobeluserManager()
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    
    

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True