Not able to authenticate user in Django? - django

I have a custom User model with which I want to validate. The model is use like this:
class GalaxyUser(AbstractBaseUser):
#id = models.IntegerField(primary_key=True)
#identifier = models.CharField(max_length=40, unique=True, db_index=True)
username = models.CharField(max_length=90, unique=True, db_index=True)
create_time = models.DateTimeField(null=True, blank=True)
update_time = models.DateTimeField(null=True, blank=True)
email = models.CharField(max_length=225)
#password = models.CharField(max_length=120)
external = models.IntegerField(null=True, blank=True)
deleted = models.IntegerField(null=True, blank=True)
purged = models.IntegerField(null=True, blank=True)
form_values_id = models.IntegerField(null=True, blank=True)
disk_usage = models.DecimalField(null=True, max_digits=16, decimal_places=0, blank=True)
#last_login = models.TextField(max_length=255)
objects = UserManager()
USERNAME_FIELD = 'email'
class Meta:
db_table = u'galaxy_user'
I have custom Authentication Backend:
class AuthBackend:
def authenticate(self, username=None, password=None):
if '#' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = User.objects.get(**kwargs)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
My login_backend function in the views look like this:
def login_backend(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
password = hashlib.sha1(password).hexdigest()
user = authenticate(username=username, password=password)
state = "Username or Password Incorrect!"
if user is not None:
login(request, user)
return HttpResponseRedirect('/overview/')
else:
return render_to_response('login_backend.html', {'state':state}, context_instance=RequestContext(request))
else:
return render_to_response('login_backend.html', context_instance=RequestContext(request))
Despite entering the correct username and password I am not able to login. What's the problem?
Edit:
url(r'^overview/', 'fileupload.views.show_files')
#login_required(login_url='/login_backend/')
def show_files(request):
try:
log_id = request.user.id
username = request.user.username
b = File.objects.filter(users_id=log_id, flag='F', flag_r='S') # Get the user id from session .delete() to use delete
total_files = File.objects.filter(users_id=log_id, flag='F').count()
total_size = File.objects.filter(users_id=log_id, flag='F')
a = [str(i.size) for i in total_size]
x = [convert_byte(i) for i in a]
if request.GET:
if request.GET.getlist('page'):
page = request.GET.getlist('page')
page = ''.join(page)
page = int(page)
else:
page = 1
if request.GET.getlist('limit'):
limit = request.GET.getlist('limit')
limit = ''.join(limit)
limit = int(limit)
else:
limit = 4
if request.GET.getlist('page2'):
page2 = request.GET.getlist('page2')
page2 = ''.join(page2)
page2 = int(page2)
else:
page2 = 1
if request.GET.getlist('limit2'):
limit2 = request.GET.getlist('limit2')
limit2 = ''.join(limit2)
limit2 = int(limit2)
else:
limit2 = 4
else:
page = 1
limit = 4
page2 = 1
limit2 = 4
ten = ''
twenty = ''
fifty = ''
hundred = ''
two_hundred = ''
if limit == 10:
ten = 'selected'
if limit == 20:
twenty = 'selected'
if limit == 50:
fifty = 'selected'
if limit == 100:
hundred = 'selected'
if limit == 200:
two_hundred = 'selected'
ten2 = ''
twenty2 = ''
fifty2 = ''
hundred2 = ''
two_hundred2 = ''
if limit2 == 10:
ten2 = 'selected'
if limit2 == 20:
twenty2 = 'selected'
if limit2 == 50:
fifty2 = 'selected'
if limit2 == 100:
hundred2 = 'selected'
if limit2 == 200:
two_hundred2 = 'selected'
if total_size == None:
total_size = 0
total_size = humansize(sum(x))
current_file = Queue.objects.filter(user_id=log_id)
current_time = (time.time())
x = [i.time_overview for i in current_file]
y = [str(i) for i in x]
durations = [current_time - float(i) for i in y]
test = [i.size for i in current_file]
testi = [str(i) for i in test]
size_overs = [int(i) for i in testi]
email_notify = [i.flag_email for i in current_file]
email_notify = [str(i) for i in email_notify]
zero = [i.replace('0', '') for i in email_notify]
one = [i.replace('1', 'checked') for i in zero]
j = [i.file_session for i in current_file]
k = [str(i) for i in j]
s = ['/home/zurelsoft/files/'+i+'*' for i in k]
a = [os.path.getsize(f) for i in s for f in glob.glob(i+'*')]
change_size = [int(k) for k in a]
queue_count = Queue.objects.filter(user_id=log_id).count()
recent_count = File.objects.filter(users_id=log_id, flag='F', flag_r='S').count()
return render_to_response('overview.html', {'queue_count':queue_count, 'recent_count':recent_count, 'page2':page2, 'limit2':limit2, 'ten2':ten2, 'twenty2':twenty2, 'fifty2':fifty2, 'hundred2':hundred2, 'two_hundred2':two_hundred2, 'ten':ten, 'twenty':twenty, 'fifty':fifty, 'hundred':hundred, 'two_hundred':two_hundred, 'page':page, 'limit':limit, 'email_notify':one, 'change_size':change_size, 'duration':durations, 'size_over':size_overs, 'overview':current_file, 'overview_files': b, 'total_files':total_files, 'total_size':total_size, 'username': username}, context_instance=RequestContext(request))
except OSError:
return render_to_response('overview.html', {'overview_files': b, 'total_files':total_files, 'total_size':total_size, 'username': username}, context_instance=RequestContext(request))

You shouldn't be hashing the submitted password in the view. The backend does that for you when you call the User.check_password method.

Change in your view
def login_backend(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
#password = hashlib.sha1(password).hexdigest()
#user = authenticate(username=username, password=password)
state = "Username or Password Incorrect!"
if user is not None:
login(request, user)
return HttpResponseRedirect('/overview/')
else:
return render_to_response('login_backend.html', {'state':state}, context_instance=RequestContext(request))
else:
return render_to_response('login_backend.html', context_instance=RequestContext(request))

Related

The form does not save the written address to database

In Django, I want to build a form that collects shipping addresses from users! Then save them to database
There is views.py starts with defining a function "is_valid_form(values)"
def is_valid_form(values):
valid = True
for field in values:
if field == '':
valid = False
return valid
class EnCheckoutView(View):
def get(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
form = CheckoutForm()
context = {
'form': form,
'couponform': CouponForm(),
'order': order,
'DISPLAY_COUPON_FORM': True
}
shipping_address_qs = Address.objects.filter(user=self.request.user, address_type='S', default=True)
if shipping_address_qs.exists():
context.update({
'default_shipping_address': shipping_address_qs[0]
})
return render(self.request, 'en-checkout-page.html', context)
except ObjectDoesNotExist:
messages.info(self.request, 'You do not have an active order.')
return redirect('core:en-checkout')
def post(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
except ObjectDoesNotExist:
messages.warning(self.request, 'You do not have an active order')
return redirect('core:en-order-summary')
form = CheckoutForm(self.request.POST or None)
if form.is_valid():
use_default_shipping = form.cleaned_data.get("use_default_shipping")
if use_default_shipping:
print('Using the default shipping address')
address_qs = Address.objects.filter(user=self.request.user, default=True)
if address_qs.exists():
shipping_address = address_qs[0]
order.shipping_address = shipping_address
order.save()
else:
messages.info(self.request, 'No default shipping address available')
return redirect('core:en-checkout')
else:
print('User is entering a new shipping address')
customer_name = form.cleaned_data.get('customer_name')
phone = form.cleaned_data.get('phone')
email = form.cleaned_data.get('email')
shipping_address1 = form.cleaned_data.get('shipping_address1')
shipping_address2 = form.cleaned_data.get('shipping_address2')
en_shipping_country = form.cleaned_data.get('en_shipping_country')
shipping_zip = form.cleaned_data.get("shipping_zip")
if is_valid_form([customer_name, phone, shipping_address1]):
shipping_address = Address(
user=self.request.user,
customer_name=customer_name,
phone=phone,
email=email,
street_address=shipping_address1,
apartment_address=shipping_address2,
country=en_shipping_country,
zip=shipping_zip,
address_type='S'
)
shipping_address.save()
order.shipping_address = shipping_address
order.save()
set_default_shipping = form.cleaned_data.get('set_default_shipping')
if set_default_shipping:
shipping_address.default = True
shipping_address.save()
else:
messages.info(self.request, 'Please ***fill in the required shipping address fields')
en_payment_option = form.cleaned_data.get('en_payment_option')
if en_payment_option == 'S':
return redirect('core:en-payment', en_payment_option='Pay with credit card')
elif en_payment_option == 'P':
return redirect('core:ar-delivery', en_payment_option='Cash on delivery')
else:
messages.warning(self.request, 'Invalid payment option selected')
return redirect('core:en/checkout')
Why this form does not save the address to the database?
I could have posted forms.py, html template, and models.py, but I guess that will explain the problem.
forms.py
EN_PAYMENT_CHOICES = (
('S', 'Pay with credit card'),
('P', 'Cash on delivery')
)
class CheckoutForm(forms.Form):
customer_name = forms.CharField(max_length=100, required=True)
phone = forms.IntegerField(required=True)
email = forms.EmailField()
shipping_address1 = forms.CharField(required=True)
shipping_address2 = forms.CharField(required=False)
ar_shipping_country = CountryField(blank_label='(اختار البلد)').formfield(
required=False,
widget=CountrySelectWidget(attrs={
'class': 'custom-select d-block w-100',
}))
en_shipping_country = CountryField(blank_label='(Choose a country)').formfield(
required=False,
widget=CountrySelectWidget(attrs={
'class': 'custom-select d-block w-100',
}))
shipping_zip = forms.CharField(required=False)
set_default_shipping = forms.BooleanField(required=False)
use_default_shipping = forms.BooleanField(required=False)
payment_option = forms.ChoiceField(
widget=forms.RadioSelect, choices=PAYMENT_CHOICES)
en_payment_option = forms.ChoiceField(
widget=forms.RadioSelect, choices=EN_PAYMENT_CHOICES)
models.py
class Address(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
customer_name = models.CharField(max_length=100, null=True)
phone = models.IntegerField(null=True)
email = models.EmailField(null=True)
street_address = models.CharField(max_length=250)
apartment_address = models.CharField(max_length=250)
country = CountryField(multiple=False, null=True)
zip = models.CharField(max_length=100)
address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES)
default = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class Meta:
verbose_name_plural = 'Addresses'

Unable to add new users to my database through Django registration form

The code works well but when trying to add a new user to the site it logs in as the superuser only.
Model
class RegistrationForm(forms.Form):
username = forms.CharField(label = 'Username', max_length = 30)
first_name = forms.CharField(label = 'First name', max_length = 30,widget=forms.TextInput(attrs={'class' : 'Name'}))
last_name = forms.CharField(label = 'Last name', max_length = 30,widget=forms.TextInput(attrs={'class' : 'Name'}))
email1 = forms.EmailField(label = 'email', required = True,widget=forms.TextInput(attrs={'class' : 'email'}))
email2 = forms.EmailField(label = 'Re-enter email',widget=forms.TextInput(attrs={'class' : 'email'}))
password1 = forms.CharField(label= "Password", widget = forms.PasswordInput(attrs={'class' : 'password1'}))
birthday = forms.DateField(label = 'Birthday',widget=forms.TextInput(attrs={'class' : 'birthday'}))
class Meta:
model = User
fields = ('username', 'email', 'password1','password2')
def save(self, commit = True):
user = super(RegistrationForm, self).save(commit = False)
user.email1 = self.cleaned_data['email1']
user.email2 = self.cleaned_data['email2']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.birthday = self.cleaned_data['birthday']
if commit:
user.save()
return user
def clean_username(self):
email1 = self.cleaned_data['email1']
if not re.search(r"(^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email1):
raise forms.ValidationError('Use a real email address eg. something#example.com.')
try:
user.objects.get(email1 = email1)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('email is already in use.')
def clean_username(self):
username = self.clean_data['username']
if not re.search(r'^\w+$', username):
raise forms.ValidationError('Username can only contain alphanumeric characters and the underscore.')
try:
user.objects.get(username = username)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('Username is already taken.')
Views
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
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:
args = {}
args.update(csrf(request))
args['form'] = RegistrationForm()
print(args)
return render(request, 'registration/register.html', args)

Want to add another field to form and database django

I tried adding another field (pin) in forms.py and models.py
The error i got was
"FieldError at /student/signup/
Cannot resolve keyword 'pin' into field. Choices are: date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_infos, user_permissions, username"
forms.py
class RegisterForm(forms.Form):
GRADE_CHOICES = (
(9,'9'), (10,'10'), (11,'11'), (12,'12') ,
)
curr_year = date.today().year
GRAD_YEAR_CHOICES = (
(curr_year,curr_year), (curr_year+1,curr_year+1), (curr_year+2,curr_year+2), (curr_year+3,curr_year+3) ,
)
first_name = forms.CharField(max_length = 25)
last_name = forms.CharField( max_length = 25)
emailid = forms.EmailField()
passwd1 = forms.CharField(max_length=100,widget=forms.PasswordInput)
passwd2 = forms.CharField(max_length=100,widget=forms.PasswordInput)
gradyear = forms.ChoiceField( choices=GRAD_YEAR_CHOICES)
grade = forms.ChoiceField( choices=GRADE_CHOICES)
pin = forms.IntegerField()
def clean(self):
cleaned_data = super(RegisterForm, self).clean()
print cleaned_data
if cleaned_data['passwd1'] != cleaned_data['passwd2']:
raise forms.ValidationError({'passwd1':['Password do not match']})
if User.objects.filter(email=cleaned_data['emailid']).count():
raise forms.ValidationError({'emailid':['Email already taken ']})
if User.objects.filter(pin=cleaned_data['pin']).count():
raise forms.ValidationError({'pin':['Pin already taken ']})
return cleaned_data
views.py
def signup(request):
print "signup"
if request.method == 'POST':
print "post signup"
form = RegisterForm(request.POST)
try:
if form.is_valid():
print form.cleaned_data
u = User.objects.create_user(form.cleaned_data['emailid'], form.cleaned_data['emailid'], form.cleaned_data['passwd1'] )
ui = UserInfo()
ui.user = u
ui.class_of = form.cleaned_data['gradyear']
ui.grade = form.cleaned_data['grade']
ui.balance = 0
print "Hi"
ui.pin = form.cleaned_data['pin']
print ui.pin
u.first_name = form.cleaned_data['first_name']
u.last_name = form.cleaned_data['last_name']
u.save()
ui.save()
user = authenticate(username=form.cleaned_data['emailid'], password=form.cleaned_data['passwd1'])
login(request,user)
print "after login in signup"
return redirect("/")
else:
print "error"
print form.errors
except:
raise
print "error here"
print form.errors
pass
#return render(request, 'student/register.html', {'form': form})
else:
form = RegisterForm()
return render(request, 'student/register.html', {'form': form})
models.py:
class UserInfo(models.Model):
user = models.OneToOneField(User, related_name='user_infos')
class_of = models.IntegerField()
#username = user.username
#fname = user.fname
#lname = user.last_name
#email = user.email
#Staff = user.is_staff
pub_date = models.DateTimeField( auto_now=True)
grade = models.IntegerField()
balance = models.DecimalField(max_digits=6, decimal_places=2)
pin = models.IntegerField()
#first_name = models.CharField(max_length = 25)
I don't think not be doing this right. Is there any way to add another column in a database another way?
You have "pin" field in your UserInfo model, but in forms.py you are trying to filter User model:
if User.objects.filter(pin=cleaned_data['pin']).count():
User model does not have "pin" field, so you are getting that error message.
Also I suggest you to learn and start using ModelForms: https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/

Problems Saving Data to Database

this is my views.py
def signup(request):
print "signup"
if request.method == 'POST':
print "post signup"
form = RegisterForm(request.POST)
try:
if form.is_valid():
print form.cleaned_data
u = User.objects.create_user(form.cleaned_data['emailid'], form.cleaned_data['emailid'], form.cleaned_data['passwd1'] )
ui = UserInfo()
ui.user = u
ui.class_of = form.cleaned_data['gradyear']
ui.grade = form.cleaned_data['grade']
ui.balance = 0
ui.save()
and in my forms.py i have:
class RegisterForm(forms.Form):
GRADE_CHOICES = (
(9,'9'), (10,'10'), (11,'11'), (12,'12') ,
)
curr_year = date.today().year
GRAD_YEAR_CHOICES = (
(curr_year,curr_year), (curr_year+1,curr_year+1), (curr_year+2,curr_year+2), (curr_year+3,curr_year+3) ,
)
first_name = forms.CharField(max_length = 25)
last_name = forms.CharField( max_length = 25)
emailid = forms.EmailField()
passwd1 = forms.CharField(max_length=100,widget=forms.PasswordInput)
passwd2 = forms.CharField(max_length=100,widget=forms.PasswordInput)
gradyear = forms.ChoiceField( choices=GRAD_YEAR_CHOICES)
grade = forms.ChoiceField( choices=GRADE_CHOICES)
def clean(self):
cleaned_data = super(RegisterForm, self).clean()
if cleaned_data['passwd1'] != cleaned_data['passwd2']:
raise forms.ValidationError({'passwd1':['Password do not match']})
if User.objects.filter(email=cleaned_data['emailid']).count():
raise forms.ValidationError({'emailid':['Email already taken ']})
return cleaned_data
why does everything print to the database except first_name and last_name??? (username, email, grade, gradyear, and password all save)
EDIT: This is my UserInfo
class UserInfo(models.Model):
user = models.OneToOneField(User, related_name='user_infos')
class_of = models.IntegerField()
#username = user.username
#fname = user.fname
#lname = user.last_name
#email = user.email
#Staff = user.is_staff
pub_date = models.DateTimeField( auto_now=True)
grade = models.IntegerField()
balance = models.DecimalField(max_digits=6, decimal_places=2)
#first_name = models.CharField(max_length = 25)
In the code provided, you never save first_name and last_name for User or UserInfo.
In def signup(request):, right after this line:
u = User.objects.create_user(form.cleaned_data['emailid'], form.cleaned_data['emailid'], form.cleaned_data['passwd1'] )
Try including this:
u.first_name = form.cleaned_data['first_name']
u.last_name = form.cleaned_data['last_name']
u.save()

django modelform saving issues

views.py
if pform.is_valid():
user = pform.save()
forms.py
class UserProfileForm(forms.ModelForm):
sex = forms.CharField(max_length = 20,label="I am :",widget=forms.Select(choices=SEX_CHOICES,attrs = {'class':''}),required = False)
first_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Please enter your real name.','class':''}),required = False)
last_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter last name.','class':''}),required = False)
location = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter your current location','class':''}),required = False)
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
if first_name == '':
raise forms.ValidationError("This field is required.")
return first_name
def clean_phone(self):
phone = self.cleaned_data['phone']
if phone == '':
raise forms.ValidationError("This field is required.")
return phone
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
if last_name == '':
raise forms.ValidationError("This field is required.")
return last_name
def clean_profession(self):
profession = self.cleaned_data['profession']
if profession == "":
raise forms.ValidationError("Select a valid option.")
return profession
def clean_sex(self):
sex = self.cleaned_data['sex']
if sex == "":
raise forms.ValidationError("Select a valid option.")
return sex
def __init__(self,*args,**kw):
super(UserProfileForm,self).__init__(*args,**kw)
self.phone = self.instance.get_profile().phone
self.profession = self.instance.get_profile().profession
self.sex = self.instance.get_profile().sex
self.location = self.instance.get_profile().location
def save(self,*args,**kw):
self.instance.first_name = self.cleaned_data.get("first_name")
self.instance.last_name = self.cleaned_data.get("last_name")
self.instance.get_profile().sex = self.cleaned_data.get("sex")
self.instance.get_profile().location = self.cleaned_data.get("location")
self.instance.get_profile().profession = self.cleaned_data.get("profession")
self.instance.get_profile().phone = self.cleaned_data.get("phone")
self.instance.save()
return self.instance
class Meta:
model = User
fields = ('first_name','last_name','phone','sex','profession','location')
#exclude = ('email')
doubt
everything is working fine but y am i not able to save the information to the user profile , when i use the self.instance.get_profile().phone = self.cleaned_data.get('#some_field') , because when i am retrieving the data its not showing up in m form , please help , thanks in advance
If I understood you well, then you get data from the form and can't save it to the users profile. To fix this, you need do save user profile too:
def save(self,*args,**kw):
self.instance.first_name = self.cleaned_data.get("first_name")
self.instance.last_name = self.cleaned_data.get("last_name")
profile = self.instance.get_profile()
profile.sex = self.cleaned_data.get("sex")
profile.location = self.cleaned_data.get("location")
profile.profession = self.cleaned_data.get("profession")
profile.phone = self.cleaned_data.get("phone")
profile.save()
self.instance.save()
return self.instance
You shouldn't use a # when fetching the field. Do this instead:
self.cleaned_data.get('some_field')