Using auth.login with authentication backed(error) - django

I created an authentication backend:
from login.models import zUser
import hashlib
class AuthBackend:
def authenticate(self, username=None, password=None): #переписана функція для пошуку користувача в таблиці zusers
password = hashlib.md5(password).hexdigest() #хешування отриманого пароля в md5
try:
user = zUser.objects.get(userpass = password, login = username)
except zUser.DoesNotExist:
return None
return user
def get_user(self, user_id): #повернути користувача за id
try:
user = zUser.objects.get(id=user_id)
except zUser.DoesNotExist:
return None
return user
But in my view, where I call auth.login(request, user), I have an error:
The following fields do not exist in this model or are m2m fields: last_login
def Login(request):
if request.method == 'POST':
username = request.POST.get('username') #введений логін
password = request.POST.get('password').encode('utf-8') #введений пароль
user = auth.authenticate(username = username, password = password)
if user is not None:
user_id = getattr(user, "userid") #отримання userid користувача
auth.login(request, user)
return redirect('/')
else:
return redirect('/') #перенаправлення на головну сторінку
else:
return render_to_response('index.html', context_instance=RequestContext(request))
Then I add to settings:
AUTHENTICATION_BACKENDS = (
'login.auth_backends.AuthBackend',
'django.contrib.auth.ModelBackend'
)
But now there is other error:
Module "django.contrib.auth.ModelBackend" does not define a "ModelBackend" attribute/class
Update: Here is my zUser table
class zUser(models.Model): #модель користувача, створена по аналогії до таблиці zusers
userpass = models.CharField(max_length=50, blank=True)
telefon = models.CharField(max_length=25, blank=True)
remark = models.CharField(max_length=250, blank=True)
fio = models.CharField(max_length=50, blank=True)
userid = models.DecimalField(unique=True, max_digits=65535, decimal_places=65535, blank=True,primary_key=True)
changeonlogon = models.CharField(max_length=1, blank=True)
userlocked = models.CharField(max_length=1, blank=True)
login = models.CharField(max_length=300, blank=True)
#crypto = models.CharField(max_length=300, blank=True)
class Meta:
managed = False
db_table = 'zusers'

Related

Data from my Django form is not added to my database cause I cannot view it on the webpage

I am trying to build a project management system and have to add client to my database. For this I have created a form as below
forms.py
class AddClientForm(forms.Form):
email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"}))
password = forms.CharField(label="Password", max_length=50, widget=forms.PasswordInput(attrs={"class":"form-control"}))
first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"}))
phone = forms.CharField(label="Phone", max_length=15, widget=forms.TextInput(attrs={"class":"form-control"}))
#For Displaying Projects
try:
projects = Projects.objects.all()
project_list = []
for project in projects:
single_project = (project.id, project.project_name)
project_list.append(single_project)
except:
project_list = []
#For Displaying Contracts
try:
contracts = Contracts.objects.all()
contract_list = []
for contract in contracts:
single_contract = (contract.id, contract.contract_name)
contract_list.append(single_contract)
except:
contract_list = []
project_name = forms.ChoiceField(label="Project", choices=project_list, widget=forms.Select(attrs={"class":"form-control"}))
contract_id = forms.ChoiceField(label="Contract", choices=contract_list, widget=forms.Select(attrs={"class":"form-control"}))
location = forms.ChoiceField(label="Location", choices=States, widget=forms.Select(attrs={"class":"form-control"}))
Then i have created the following views.py
def add_client(request):
form = AddClientForm()
context = {
"form": form
}
return render(request, 'admintemplate/add_client_template.html', context)
def add_client_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect('add_client')
else:
form = AddClientForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
phone = form.cleaned_data['phone']
location = form.cleaned_data['location']
project_id = form.cleaned_data['project_name']
contract_id = form.cleaned_data['contract_id']
try:
user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3)
user.clients.location = location
user.client.primaryphone = phone
project_obj = Projects.objects.get(id=project_id)
user.clients.project_id = project_obj
contract_obj = Contracts.objects.get(id=contract_id)
user.clients.contract_id = contract_obj
user.clients.save()
messages.success(request, "Client Added Successfully!")
return redirect('add_client')
except:
messages.error(request, "Failed to Add Client!")
return redirect('add_client')
else:
return redirect('add_client')
And my models.py is as follows
class Clients(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
primaryphone = models.CharField(max_length=15, unique=True)
location = models.CharField(max_length=30, choices=States)
project_id = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=1)
contract_id = models.ForeignKey(Contracts, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
I am not sure why the data is not being saved in the clients model. ANy help would be appreciated.

Django only authenticates superuser

I am new in Django.
I have a problem with authenticate(). It only authenticates the superuser.
For any other user it returns None.
I use "user_id" field instead of "username" field.
I don't want to use Django forms.
this is my models.py.
models.py
class UserProfileManager(BaseUserManager):
def create_user(self, user_id, first_name, last_name, user_class, password = None):
user = self.model(first_name = first_name, last_name = last_name , user_id = user_id, user_class = user_class)
user.set_password(password)
user.save(using = self._db)
return user
def create_superuser(self, user_id, first_name, last_name , password = None):
user = self.create_user(user_id, first_name, last_name, None, password = password)
user.is_superuser = True
user.is_staff = True
user.save(using = self._db)
return user
class UserProfile(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length = 255)
last_name = models.CharField(max_length = 255)
user_id = models.IntegerField(unique = True, null = True)
user_class = models.ForeignKey(Class, on_delete = models.PROTECT, default = None, unique = False, null = True)
is_active = models.BooleanField(default = True)
is_staff = models.BooleanField( default = False)
objects = UserProfileManager()
USERNAME_FIELD = 'user_id'
# REQUIRED_FIELDS = ['first_name', 'last_name']
def get_short_name(self):
return self.first_name
def get_full_name(self):
return '{} {}'.format(self.first_name, self.last_name)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
this is my views.py.
views.py
class HomeView(TemplateView):
template_name = 'user_profile/home.html'
def post(self, request, *args, **kwargs):
if request.method == 'POST':
user_id = request.POST.get('user_id')
password = request.POST.get('password')
print('id :', user_id, '\npassword : ',password)
user = authenticate(user_id = user_id , password = password)
print(user)
if user is not None :
if user.is_active:
login(request,user)
return redirect('user_profile:home')
else:
return render(request, 'user_profile/not_active.html')
else:
return render(request, 'user_profile/not_valid.html')
else:
return render(request, 'user_profile/home.html')
because the users are not active. And username_field puts the email or username or another unique field except id

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'

'NoneType' object is not iterable after PyInstaller app creation on a Mac

I have a working piece of code which runs fine.
Here's the model:
class Therapist(models.Model):
user = models.OneToOneField(User)
SEX_CHOICES = (
('M','male'),
('F','female'),
)
sex = EncryptedCharField(choices = SEX_CHOICES, blank=False, max_length=20, verbose_name = "Płeć")
company = models.ManyToManyField(Company, blank=True, verbose_name = "Firma")
subscription = models.ForeignKey(Subscription, blank=False, verbose_name = "Abonament")
uuid = models.UUIDField(primary_key=False, editable=False, default=uuid.uuid4, null=True, blank=True)
def __unicode__(self):
return '%s %s' % (self.user.first_name, self.user.last_name)
def __str__(self):
return '%s %s' % (self.user.first_name, self.user.last_name)
The form:
class MyRegistrationForm(forms.Form):
SEX_CHOICES = (
('F', 'kobieta'),
('M', 'mężczyzna'),
)
first_name = forms.CharField(label="Imię")
last_name = forms.CharField(label="Nazwisko")
user_email = forms.EmailField(label="Adres e-mail")
user_sex = forms.ChoiceField(label="Wybierz swoją płeć", choices = SEX_CHOICES)
username = forms.CharField(label="Nazwa użytkownika")
password1 = forms.CharField(label="Wpisz hasło", widget = PasswordInput())
password2 = forms.CharField(label="Powtórz hasło", widget = PasswordInput())
def clean_username(self):
username = self.cleaned_data['username']
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# this is to verify if any user exists at all. If yes - do not allow other users to be created!
if Therapist.objects.all().exists():
raise forms.ValidationError(_(u'Jakiś użytkownik już istnieje, a Twoja wersja programu nie pozwala na tworzenie więcej niż 1 użytkownika. Wersje dla więcej niż jednego terapeuty dostępne pod kontakt#zapiszsesje.pl'), code='invalid')
else:
return username
raise forms.ValidationError(u'Użytkownik o nazwie "%s" już istnieje.' % username)
def clean_user_email(self):
email = self.cleaned_data['user_email']
try:
user = User.objects.get(email =email)
except User.DoesNotExist:
return email
raise forms.ValidationError(u'Użytkownik o takim adresie email już istnieje.')
& the view:
def myRegistrationView(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username = form.cleaned_data['username'],
email = form.cleaned_data['user_email'],
password = form.cleaned_data['password1'],
first_name = form.cleaned_data['first_name'],
last_name = form.cleaned_data['last_name']
)
user.save()
subscription = Subscription(
expired_on = datetime.datetime.now() + datetime.timedelta(days = 90)
)
subscription.save()
therapist = Therapist(
user = user,
sex = form.cleaned_data['user_sex'],
subscription = subscription,
)
therapist.save()
return HttpResponseRedirect(reverse('registration_gotowe'))
else:
form = MyRegistrationForm()
param = {
'form':form
}
return render(request, 'registration/registration_form.html', param)
When I package the app using a Mac and PyInstaller the app works fine until I get to that view and try to register creating a User, Subscription and Therapist. In that moment I get a
TypeError at /konto/register/
'NoneType' object is not iterable error ...
The same code works fine on Windows before and after the PyInstaller compilation to an exe file. Apart from that the app seems to work fine without any errors.
If I comment out the part of the code where the Therapist is created in the view:
therapist = Therapist(
user = user,
sex = form.cleaned_data['user_sex'],
subscription = subscription,
)
therapist.save()
the app 'works' fine - this error does not occur....
What am I missing?

django - can't work out the views to assign a new item

I've this in my views and trying to get new truck_name assigned to a new Product.
When user with truck_name as None and no instance of Product, the script goes to
try:
truck_name = Product.objects.get(user=request.user)
and skips to the except:
#login_required
def profile_edit(request):
owner = TruckOwnerStatus.objects.get(user=request.user)
truck_form = RegisterTruckForm()
i = owner.id
print i
try:
truck_name = Product.objects.get(user=request.user)
if request.method == 'GET':
if truck_name is not None:
truck_form = RegisterTruckForm(instance=truck_name)
else:
truck_form = RegisterTruckForm()
context = {
'truck_form': truck_form,
'truck_name': truck_name,
}
return render(request, 'accounts/profile_edit.html', context)
elif request.method == 'POST':
if truck_name is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES, instance=truck_name)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
#once clicked save
if truck_form.is_valid():
truck_name = truck_form.save(commit=False)
truck_name.product = Product.objects.get(user=request.user)
truck_form.save_m2m()
truck_name.save()
messages.success(request, "Successfully Saved!!")
return HttpResponseRedirect('/')
return render_to_response('accounts/profile_edit.html', {'truck_form': truck_form}, context_instance=RequestContext(request))
except:
print "hii"
if request.method == 'POST':
truck_form = RegisterTruckForm(request.POST, request.FILES)
truck_owner = request.user
if truck_owner is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES, instance=truck_owner)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
if truck_form.is_valid():
truck_owner = truck_form.save(commit=False)
truck_owner.profile = Product.objects.create(user=request.user)
truck_form.save_m2m()
truck_owner.profile.save()
messages.success(request, "Successfully Saved!!")
return HttpResponseRedirect('/')
else:
messages.error(request, "Please recheck")
# return render(request, context, 'accounts/profile_edit.html',)
context = {"truck_form": truck_form}
return render(request, 'accounts/profile_edit.html', context)
It does the job of saving the form but does not assign the truck_name from the form to the request user. Hence nothing gets assigned to the new Product
I tried putting
truck_name = Product.objects.get(user=request.user) in the except but it returns an error because there is no instance of Product for this user and therefore no truck_name.
I can see the entry in admin but can't view it because there is no truck_name. But if I were to run the entire profile_edit for the same user and fill the the form, the truck_name gets assigned.
How do I get it assigned?
Below is my Product model.
class Product(models.Model):
user = models.OneToOneField(User)
owner_name = models.CharField(max_length=120)
email = models.EmailField(max_length=120)
contact_number = models.IntegerField(max_length=15, null=True, blank=True)
foodtruck_name = models.CharField(max_length=120)
logo = models.ImageField(upload_to='foodtruck/logo/', null=True, blank=True)
slogan = models.TextField(max_length=250, null=True, blank=True)
about_us = models.TextField(max_length=500, null=True, blank=True)
operating_state = models.CharField(max_length=120, choices=STATE_CHOICES)
bsb = models.IntegerField(max_length=15, null=True, blank=True)
account_number = models.IntegerField(max_length=15, null=True, blank=True)
availability_link = models.CharField(max_length=300, null=True, blank=True)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
update_defaults = models.BooleanField(default=False)
def __unicode__(self):
return self.foodtruck_name
class Meta:
unique_together = ('foodtruck_name', 'slug')
def get_price(self):
return self.price
def get_absolute_url(self):
return reverse("single_product", kwargs={"slug": self.slug})