User is not authenticating - python

I am trying to create a simple login page. But user is always returned as none.
Here's my login.html
<form method = 'POST'>
{% csrf_token %}
<div class="body"></div>
<div class="name">
<div>Chili<span>Pili</span></div>
</div>
<br>
<div class="login">
<input type="text" placeholder="Username" name="username"><br>
<input type="password" placeholder="Password" name="password"><br>
<input type="submit" value="Login">
</div>
</form>
my login function in view.py
def login(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username = username, password = password)
if user is not None:
login(user)
print (user)
messages.success(request, "You have successfully Logged In.")
return redirect('index')
else:
messages.error(request, "You have entered invalid credentials. Please try again")
return redirect('login')
else:
return render(request, 'main/login.html')
models.py:
class users(models.Model):
_id = models.AutoField
name = models.CharField(max_length = 100)
username = models.CharField(max_length = 100)
email = models.EmailField(max_length=254)
hpassword = models.CharField(max_length = 255)
category = models.CharField(max_length=50, default= "teacher")
def __str__(self):
return self.name
return self.username
return self.email
return self.category
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = [username, hpassword]
The keeps returning as none and only else statement gets executed. I am not able to understand what is going wrong here

try
def loginview(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
...
else:
...
the reason why you are getting that error is login(request,user) is recuring back to login view method rather thatn using auth login method.... change login view method name to "loginview" that will be fine.

Related

customer registration not showing in django admin

Trying to create customer registration form for ecommerce website . No errors while submitting the form, but details are not shown in django admin . Here are required codes :
models.py
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
full_name = models.CharField(max_length=200)
address = models.CharField(max_length=200, null=True, blank=True)
joined_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.full_name
urls.py
urlpatterns = [path("register",views.register, name="register")]
forms.py
class CustomerRegistrationForm(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
email = forms.CharField(widget=forms.EmailInput())
class Meta:
model = Customer
fields = ["username", "password", "email", "full_name", "address"]
def clean_username(self):
uname = self.cleaned_data.get("username")
if User.objects.filter(username=uname).exists():
raise forms.ValidationError(
"Customer with this username already exists.")
return uname
views.py
def register(request):
form = CustomerRegistrationForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
email = form.cleaned_data.get("email")
user = User.objects.create_user(username, email, password)
form.instance.user = user
return redirect("/")
return render(request,"register.html",{'form':form})
register.html
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<h3>Customer Registration Form</h3><hr>
<form action="" method="POST">
{% csrf_token %}
{{form|crispy}}
<button class="btn btn-primary" >Register as a Customer</button>
</form>
<p> Already have an account? Login here</p>
</div>
</div>
</div>
Thank you in advance:)
In your view, you're creating Users, not Customers.
If you're starting a new project, I would suggest using a custom user model.
If that's not possible, you need to save the form first to generate a Customer instance and then connect it with the appropriate User model:
def register(request):
form = CustomerRegistrationForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
email = form.cleaned_data.get("email")
customer = form.save(commit=False)
user = User.objects.create_user(username, email, password)
customer.user = user
customer.save()
form.instance.user = user
return redirect("/")
return render(request,"register.html",{'form':form})

Custom user creation form always invalid in Django

I am working on building a new Django Website and am trying to make an abstract base class and using forms to fill it out. I thought I was doing it correctly, but whenever I try to fill out the form it is always invalid. I am wondering if anyone can help me with this problem. All of the other help I find online does not help me. Here is my code. Thanks
My forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = Profile
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
def __init__(self, regLinkModel):
super(CustomUserCreationForm, self).__init__()
self.linkInfo = regLinkModel
def save(self, commit=True):
user = super(CustomUserCreationForm, self).save(commit=False)
user.username = self.cleaned_data['username']
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['fname']
user.last_name = self.cleaned_data['lname']
user.password1 = self.cleaned_data['password1']
user.password2 = self.cleaned_data['password2']
if commit:
user.save()
return user
My Models.py
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, password):
if not email:
raise ValueError("User needs email address")
if not username:
raise ValueError("User needs username")
if not first_name:
raise ValueError("User needs first name")
if not last_name:
raise ValueError("User needs last name")
user = self.model(
email=self.normalize_email(email),
password = password,
username =username,
first_name = first_name,
last_name = last_name,
)
user.set_password(password1)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password, first_name, last_name):
user = self.create_user(
email=self.normalize_email(email),
password = password,
username =username,
first_name = first_name,
last_name = last_name,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def count_total_profiles(self):
return Profile.objects.filter(license_id= self.id).count()
def count_active_profiles(self):
return Profile.objects.filter(license_id= self.id).filter(is_active=True).count()
def is_expired(self):
return timezone.now() > self.expire_date
def __repr__(self):
return self.name
class Profile(AbstractBaseUser):
email =models.EmailField(verbose_name='email', max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True, default=" ")
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
first_name = models.CharField(max_length=30, default=" ")
last_name = models.CharField(max_length=30, default=" ")
password1 = models.CharField(max_length=20,default= " ")
password2 = models.CharField(max_length=20,default= " ")
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'password1', 'password2']
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
My view.py
def regUser(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
print(form)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("/")
else:
return redirect("/youdiditwrong")
My HTML code
<HTML>
<head>
<title>Create a User</title>
</head>
<body>
<h1>User: </h1>
<form action="" method="POST">
{% csrf_token %}
First Name: <input type="text" name="fname"/><br/>
Last Name: <input type="text" name="lname"/><br/>
Username: <input type="text" name ="username"/><br/>
Email:<input type="text" name="email"/><br/>
Password:<input type="text" name="password1"/><br/>
Confirm Password:<input type="text" name="password2"/><br/>
<input type="submit" value="Post"/>
</form>
</body>
</html>
I think your code should look something like this, you have to add the jinja2 in the html, so that you can use the form you created
<HTML>
<head>
<title>Create a User</title>
</head>
<body>
<h1>User: </h1>
<form action="" method="POST">
{% csrf_token %}
<!-- This is the first option
{{ form.first_name }}
{{ form.last_name }}
{{ form.username }}
{{ form.email }}
{{ form.password }}
{{ form.password2 }}
-->
<!-- This is second option
{{ form.as_ul }}
-->
<input type="submit" value="Post"/>
</form>
</body>
</html>
views.py
def regUser(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
print(form)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("/")
else:
return redirect("/youdiditwrong")
else: # if the method is not POST
return render(request, "page with the html",
{"form": CustomUserCreationForm()}

Django : NoReverseMatch at when changing password using form

I'm trying to make form and method which allows users to change their password. When user type their password into two inputs than form will check if those are same and update db. However I got this error and I couldn't solve it.
error message
NoReverseMatch at /blog/password_change/blue/
Reverse for 'profile' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'blog/profile/(?P<username>[-\\w.]+)/$']
urls.py
url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'),
url(r'^profile/(?P<username>[-\w.]+)/$', views.profile, name='profile'),
views.py
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect(reverse('blog:profile'))
else:
return redirect(reverse('blog:profile'))
else:
form = PasswordChangeForm(user=request.user)
return HttpResponseRedirect('/blog/')
profile.html. this is the template.
<form class="form-horizontal" role="form" action="{% url'blog:password_change' user.username %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="password1">new password</label>
<div class="row">
<input type="password" name="password1" id="password1"/></div>
<div class="row">
<label for="password2">password check</label></div>
<div class="row">
<input type="password" name="password2" id="password2"/></div>
<div class="row">
<button type="submit" class="button-primary">change password</button></div>
views.py
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect(reverse('blog:profile'))
else:
return redirect(reverse('blog:profile'))
else:
form = PasswordChangeForm(user=request.user)
return HttpResponseRedirect('/blog/')
This is forms.py
class PasswordChangeForm(forms.ModelForm):
error_messages = {
'password_mismatch': ("The two password fields didn't match."),
}
password1 = forms.CharField(
label=("Password"),
strip=False,
widget=forms.PasswordInput,
help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
label=("Password confirmation"),
widget=forms.PasswordInput,
strip=False,
help_text=("Enter the same password as before, for verification."),
)
class Meta:
model = User
fields = ("username",)
field_classes = {'username': UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self._meta.model.USERNAME_FIELD in self.fields:
self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True})
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
self.instance.username = self.cleaned_data.get('username')
password_validation.validate_password(self.cleaned_data.get('password2'), self.instance)
return password2
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
As your error states, you need an argument for your username in profile url, which you don't provide at all.
For example:
return redirect(reverse('blog:profile'))
should be
return redirect(reverse('blog:profile', args=[form.user.get_username()]))
You must pass username to reverse().
username = form.user.get_username()
reverse('blog:profile', kwargs={'username':username})

form.is_valid() always returns false

I have tried all the solutions given on SO but was not able to slve this
view.py
def signup(request):
form = SignupForm(request.GET)
print("%s"%request.GET['hobby'])
form.errors
#h=SignupForm(request.POST)
if form.is_valid():
email = request.GET['email']
location = request.GET['location'] users=User(username=username,email=email,password=request.GET['password'],location=location)
user_profile = request.user.profile
user_profile.location = location
user_profile.save()
form.save()
return HttpResponseRedirect('mtweet/')
return render(request,'mtweet/signup.html',{'SignupForm':form})
form.py
class SignupForm(UserCreationForm):
username=forms.CharField(label = " Username",required=True)
email = forms.EmailField(label = "Email",required=True)
password = forms.CharField(widget = forms.PasswordInput,required=True)
location=forms.CharField(label="Location",required=False)
class Meta:
model = User
fields = ("username", "email","location")
signup.html
<div id="register">
<form method="post" action="{% url 'mtweet.views.signup' %}">
{% csrf_token %}
<table>
{{ SignupForm.as_p}}
</table>
<input type="submit" value="Submit" />
</form>
</div>
There are a few problems with your code; let me try and re-write it:
class SignupForm(forms.Form):
username=forms.CharField(label = " Username",required=True)
email = forms.EmailField(label = "Email",required=True)
password = forms.CharField(widget=forms.PasswordInput,required=True)
location=forms.CharField(label="Location",required=False)
def signup(request):
form = SignupForm(request.POST, request.FILES)
if form.is_valid():
email = form.cleaned_data['email']
location = form.cleaned_data['location']
password = form.cleaned_data['password']
username = form.cleaned_data['username']
user = User.objects.create_user(username, email, password)
user.save()
user_profile = user.profile
user_profile.location = location
user_profile.save()
return HttpResponseRedirect('mtweet/')
else:
return render(request,'mtweet/signup.html',{'SignupForm':form})
return render(request,'mtweet/signup.html',{'SignupForm':SignupForm()})

Login in Django 1.5

I use MyUser model in Django 1.5 with e-mail login:
model:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
last_name=models.CharField(max_length=30)
first_name=models.CharField(max_length=30)
second_name=models.CharField(max_length=30, blank=True)
post=models.CharField(max_length=30, blank=True)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['last_name','first_name','second_name','post', ....]
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.is_admin
I tried method with from django.contrib.auth.views import login:
urls:
(r'^login/$', login, {'template_name': 'enter.html'}),
view: nothing.
It works for superuser from classic User model, not for MyUser.
Then I tried:
view:
def login_view(request):
username = request.POST['email']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect("/n1.html")# Redirect to a success page.
else:
return HttpResponseRedirect("/account/invalid/")# Return a 'disabled account' error message
template:
{% if form.errors %}
<p>Something is wrong</p>
{% endif %}
<form action="" method="post">
{% csrf_token %}
<label for="email">Login:</label>
<input type="text" name="email" value="" id="email"/>
<label for="password">Password:</label>
<input type="password" name="password" value="" id="username">
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{next|escape}}" />
</form>
urls:
(r'^login/$', login_view, {'template_name': 'enter.html'}),
But I got error login_view() got an unexpected keyword argument 'template_name'
What am I doing wrong?
login_view() got an unexpected keyword argument 'template_name' means that your view function should have template_name parameter:
def login_view(request, template_name):
'your code'
If you don't need it, don't pass it in urls.py:
(r'^login/$', login_view),
Upd.
Your login_view handles your POST method. You can re-write it this way to render form on GET
def login_view(request):
if request.method == 'POST':
username = request.POST['email']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect("/n1.html")
return HttpResponseRedirect("/account/invalid/")
form = LoginForm()
return render(request, 'enter.html', {'login_form': LoginForm})

Categories