I am creating user authentication form, on entering data and submitting, I get this error:
AttributeError at /register/
'RegistrationForm' object has no attribute 'username'
at ` username=form.username,
I have checked all the solutions with the same problem and applied them but no one is solving it(like that is_valid()). how do I get it right? here is the code:
from django.http import HttpResponse
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.clean_data['username'],
password=form.clean_data['password1'],
email=form.clean_data['email'])
return HttpResponseRedirect('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form})
return render_to_response(
'registration/register.html',
variables)
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')
def main_page(request):
return render_to_response(
'main_page.html', RequestContext(request))
def user_page(request, username):
try:
user = User.objects.get(username=username)
except:
raise Http404('Requested user not found.')
bookmarks = user.bookmark_set.all()
template = get_template('user_page.html')
variables = RequestContext(request, {
'username': username,
'bookmarks': bookmarks
})
output = template.render(variables)
return HttpResponse(output)
forms.py
import re
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(
label='Password',
widget=forms.PasswordInput()
)
password2 = forms.CharField(
label='Password (Again)',
widget=forms.PasswordInput())
def clean_password2(self):
if 'password1' in self.clean_data:
password1 = self.clean_data['password1']
password2 = self.clean_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
username = self.clean_data['username']
if not re.search(r'^\w+$', username):
raise forms.ValidationError('Username .')
try:
User.objects.get(username=username)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('Username is already taken.')
Its cleaned_data, not clean_data:
username = form.cleaned_data['username']
Do this for other form data as well, like password1 and email.
Some background in the reason for this can be found in Django documentation. Basically, the methods are called clean_fieldname but after cleaning the data is in cleaned_fieldname. Note the distinction.
Related
I'm trying to create a superuser but it's giving the above error.
And I can't exactly find at which line I'm getting the error.
views.py
from django.shortcuts import render
from django.contrib.auth import authenticate,login,logout
from .models import *
from django.http import HttpResponseRedirect
from django.urls import reverse
from .form import *
from django.db import IntegrityError
# Create your views here.
def index(request):
if not myUser.is_authenticated:
message = "signed in as {Customer.first_name}"
else :
message = "please sign in"
return render(request, "auctions/index.html",{
"listings": Listings.objects.all(),
"message":message
})
def login_view(request):
if request.method == "POST":
form = loginForm()
email = request.POST["email"]
password = request.POST["password"]
user = authenticate(request,username=email,password=password)
if user is not None:
login(request,email,password)
return HttpResponseRedirect(reverse('index'))
else:
return render(request, "auctions/login.html",{
"form": form ,
"message": "username/password not valid"
})
return render(request, "auctions/login.html",{
"form": loginForm()
})
def logout_view(request):
logout(request)
return render(request, "auctions/login.html")
def register(request):
if request.POST == "POST":
form = registerForm()
email = request.POST["email"]
# check passwords are same
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render (request, "auctions/register.html",{
"form": form,
"message": "Passwords does not match"
})
# Attempt to create new user
try:
user = myUser.objects.create_user(email,password)
user.save()
except IntegrityError:
return render(request, "auctions/register.html", {
"form":form,
"message": "Username is already taken"
})
login(request,user)
return HttpResponseRedirect(reverse('index'))
return render(request, "auctions/register.html", {
"form": registerForm()
})
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser,BaseUserManager
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class myUserManager(BaseUserManager):
"""
custom user model manager where email is unique indentifiers for authenticaton
instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff',True)
extra_fields.setdefault('is_superuser',True)
extra_fields.setdefault('is_active',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 myUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = myUserManager()
def __str__(self):
return f'{self.email}'
class Listings(models.Model):
listing_name = models.CharField(max_length=50)
price = models.IntegerField()
date_listed = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
item_image = models.ImageField()
description = models.TextField(max_length=200, default="Description Not Available")
def __str__(self):
return f'{self.listing_name}'
I even tried deleting files inside migrations and remigrating them but it still shows the same error.
Thanks and I really appreciate your efforts in helping me
The function django.contrib.auth.login is defined as def login(request, user, backend=None). You pass it the wrong arguments (login(request,email,password)).
Your view should be:
def login_view(request):
if request.method == "POST":
form = loginForm()
email = request.POST["email"]
password = request.POST["password"]
user = authenticate(request,username=email,password=password)
if user is not None:
login(request, user) # ← here
return HttpResponseRedirect(reverse('index'))
else:
return render(request, "auctions/login.html",{
"form": form ,
"message": "username/password not valid"
})
return render(request, "auctions/login.html",{
"form": loginForm()
})
Also in your create_user method you write self.model(email, **extra_fields) but that's incorrect. Your method should be:
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
I'm trying to create an "Edit Profile" form in the fronted. What happens is that my form(i'm not 100% sure) tries to create a user instead of finding the current user and update his profile. So I think that's the issue. Checked many questions here but none was clear enough. The fields I'm trying to edit are email(to be checked if email already exisit), Name, user type, and password.
below is the code for forms.py
class ProfileForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('full_name', 'active', 'admin','email','user_type')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(ProfileForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
# user.active = False # send confirmation email
if commit:
user.save()
return user
code for views.py
def profile(request):
user = User.objects.filter(email = request.user)
# form = ProfileForm(user.values().first())
if request.method == 'POST' :
form = ProfileForm(request.POST)
if form.is_valid():
form.save(commit=True)
form = ProfileForm(user.values().first())
# print(user)
context = {
'object_list': user,
'form': form
}
return render(request, 'userpanel/profile.html',context)
Thanks in advance
You didn't pass instance argument to the form. Without instance it will try to create new object. It should be like this:
form = ProfileForm(request.POST, instance=user)
Also you don't need to query user with this: user = User.objects.filter(email = request.user). Just add login_requred decorator to ensure user is authenticated and use request.user:
from django.contrib.auth.decorators import login_required
#login_required
def profile(request):
if request.method == 'POST' :
form = ProfileForm(request.POST, instance=request.user)
I'm using a view to create new users in Django. And then I have another view to log them in.
But when I create a user, and I try to log in with authenticate(username=username_post, password=password_post), I get None, so it displays in the template 'Wrong username or password.'.
In my database, I see new registers every time I create a new user. However, as the password is encrypted, I can't say if the problem is the login view, or the register view.
However, the super user that I created through the command line after I first installed django, is able to login with no problem, so that makes me thing that the problem is when I create the user.
These are my Login and Register views:
class Login(View):
form = LoginForm()
message = None
template = 'settings/blog_login.html'
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
return redirect('settings:index')
return render(request, self.template, self.get_context())
def post(self, request, *args, **kwargs):
username_post = request.POST['username']
password_post = request.POST['password']
user = authenticate(username=username_post, password=password_post)
if user is not None:
login(request, user)
return redirect('settings:index')
else:
self.message = 'Wrong username or password.'
return render(request, self.template, self.get_context())
def get_context(self):
return {'form': self.form, 'message': self.message}
class Register(CreateView):
success_url = reverse_lazy('settings:login')
model = User
template_name = 'settings/blog_register.html'
form_class = RegisterForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.set_password(self.object.password)
self.object.save()
return HttpResponseRedirect(self.get_success_url())
And these are my forms:
class LoginForm(forms.Form):
username = forms.CharField(max_length=20, label='Username')
password = forms.CharField(label='Password', widget=forms.PasswordInput())
class RegisterForm(forms.ModelForm):
username = forms.CharField(max_length=20, label='Username')
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(),
error_messages={'required': 'Required field.',
'unique': 'Username already used.',
'invalid': 'Not valid username.'})
password2 = forms.CharField(label='Retype password', widget=forms.PasswordInput(),
error_messages={'required': 'Required field.'})
email = forms.EmailField(error_messages={'required': 'Required field.',
'invalid': 'Invalid email.'})
def clean(self):
clean_data = super(RegisterForm, self).clean()
password1 = clean_data.get('password1')
password2 = clean_data.get('password2')
if password1 != password2:
raise forms.ValidationError('Passwords are different.')
return self.cleaned_data
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if email and User.objects.filter(email=email).exclude(
username=username).exists():
raise forms.ValidationError('Email already used.')
return email
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'email')
Please, let me know if you need more info.
You don't have a field called 'password' in your form - you just have 'password1' and 'password2' - so nothing is saved to the model object's actual password field. So, when you do self.object.set_password(self.object.password), you're actually setting a blank password.
Instead, you should get the value from your form's password1 field:
self.object.set_password(self.form.cleaned_data['password1'])
I'm trying to create a simple user registration in Django and I get this error. I've looked it up here on stackoverflow: 'AnonymousUser' object has no attribute 'backend', Django Register Form 'AnonymousUser' object has no attribute 'backend' and tried calling authentication before login. But I keep getting this error.
Can anyone please help me with this?
Here is the traceback
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/Users/harisaghadi/Dropbox/Senior Project/Django Tutorials/mysite/meddy1/views.py" in signup_user
51. login(request, new_user)
File "/Library/Python/2.7/site-packages/django/contrib/auth/__init__.py" in login
85. request.session[BACKEND_SESSION_KEY] = user.backend
File "/Library/Python/2.7/site-packages/django/utils/functional.py" in inner
214. return func(self._wrapped, *args)
Exception Type: AttributeError at /meddy1/signup/
Exception Value: 'AnonymousUser' object has no attribute 'backend'
Here is my forms.py
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Please enter a valid email address so we can reach you.'}))
username = forms.RegexField(label=_("Username"), max_length=30,
regex=r'^[\w.#+-]+$',
help_text=_("Required. 30 characters or fewer. Letters, digits and "
"#/./+/-/_ only."),
error_messages={
'invalid': _("This value may contain only letters, numbers and "
"#/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ("username",)
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(
self.error_messages['duplicate_username'],
code='duplicate_username',
)
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',
)
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
userProfile = DoctorSeeker(user=user, name=name, email=email)
userProfile.save()
return user
views.py
def index(request):
return HttpResponse("Welcome to Meddy")
# -------------------- Authentication ----------------------
def signup(request):
return render(request, 'meddy1/signup.html', {})
#csrf_exempt
def signup_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST,request.FILES)
if form.is_valid():
new_user = authenticate(username=request.POST['username'],password=request.POST['password1'])
login(request, new_user)
return HttpResponseRedirect(reverse('index'))
else:
form = UserCreationForm()
return render(request, "meddy1/signup.html", {'form': form,'usersignup':True})
def login_user(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username,password=password)
if user:
return render(request, 'meddy1/index.html')
else:
return HttpResponseRedirect('/')
def logout_user(request):
logout(request)
return HttpResponseRedirect('/')
models.py
class DoctorSeeker(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
user = models.ForeignKey(User, unique=True)
def __unicode__(self):
return u"%s %s" % (self.name, self.email)
Since you found the similar posts, i take it, you understand, that your authenticate does not really authenticate anything. It fails for some reason.
I understand that the view you are showing us is trying to accomplish 2 things- create user and log him in? Right? Since its name is signup_user.
Well. You have UserCreationForm, but you do not save it. So you cant really authenticate an user, that does not yet exist in the system. Save your form first, then call authenticate.
Edit : I am unable to load a image, but here is a link : https://plus.google.com/113782760013016224132/posts/3kcamT13yNP
Using Django. This is my first question.
I keep getting the error: Profile() got an unexpected keyword argument 'name'. I dont really understand why I am getting this error. It was working yesterday and now its all weird. Help would be much appreciated.
My forms.py is:
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
verifyPass = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = Profile
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken, please select another username.")
def clean(self):
password = self.cleaned_data.get('password', None)
verifyPass = self.cleaned_data.get('verifyPass', None)
if password != verifyPass:
#self.cleaned_data['password'] != self.cleaned_data['verifyPass']:
raise forms.ValidationError("Please try again, the passwords did not match.")
return self.cleaned_data
views.py:
def UserRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile')
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username = form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'])
user.save()
users = Profile(user=user, name=form.cleaned_data['name'], date_of_birth=form.cleaned_data['date_of_birth'])
users.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
else:
''' user is not submitting the form, show them a blank registration form '''
form = RegistrationForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = LoginUserForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
users = authenticate(username = username, password = password)
if users is not None:
login(request, users)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html', {'form' : form}, context_instance = RequestContext(request))
else:
return render_to_response('login.html', {'form' : form}, context_instance = RequestContext(request))
else:
''' user is not submitting the form, show the login form '''
form = LoginUserForm()
context = {'form': form}
return render_to_response('login.html', context, context_instance=RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/')
def Profile(request):
render_to_response('profile.html')
def home(request):
return render_to_response("home.html")
class LoginUserForm(forms.Form):
username = forms.CharField(label=(u'User Name'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
models.py:
class Profile(models.Model):
user = models.OneToOneField(User)
date_of_birth = models.DateField()
name = models.CharField(max_length=100)
def __str__(self):
return self.name