form_invalid() missing 1 required positional argument: 'form' - python

Hi how are I having a problem with my django user authentication since I am using AbstractBaseUser
Model
from Apps.grupo.models import Grupo
from Apps.empresa_area.models import Empresa_area
from Apps.archivos.models import Archivos
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
Group,
)
class UserManager(BaseUserManager):
def create_user(self, email, password=None, is_staff=False, is_admin=False):
if not email:
raise ValueError("Usuuario tiene email")
if not password:
raise ValueError("usuario debe tener contraseƱa")
user_obj = self.model(
email =self.normalize_email(email)
)
user_obj.set_password(password)
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.active = is_active
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_staff=True
)
return user
def create_superuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_staff=True,
is_admin=True,
)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=200, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
celular = models.CharField(max_length=20)
saludo = models.CharField(max_length=10)
grupo = models.ForeignKey(Grupo, null=True, blank=True, on_delete=models.CASCADE)
archivo = models.ForeignKey(Archivos, null=True, blank=True, on_delete=models.CASCADE)
fec_creacion = models.DateTimeField(auto_now=False, auto_now_add=False)
empresa_area_id = models.ForeignKey(Empresa_area, null=True, blank=True, on_delete=models.CASCADE)
cargo = models.ManyToManyField(Group)
USERNAME_FIELD = 'email'
REQUIRED_FILES = []
objects = UserManager()
class Meta:
verbose_name = ('user')
verbose_name_plural = ('users')
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(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.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
In this model is giving the permissions to validate me by email also I have in this view where user authentication is generated
view
from django.contrib.auth import (
get_user_model,
authenticate,
login,
logout,
)
from django.views.generic import CreateView, FormView
from django.utils.http import is_safe_url
from django.shortcuts import render, redirect
from .forms import Login
User = get_user_model()
class LoginView(FormView):
form_class = Login
succes_url = '/'
template_name = 'Login.html'
def form_valid(self, form):
request = self.request
next_post = request.POST.get('next')
next_ = request.GET.get('next')
password = form.cleaned_data.get("password")
email = form.cleaned_data.get("email")
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
try:
del request.session['email']
except:
pass
return super(LoginView, self).form_invalid()
It is validating but it is generating the following error
form_invalid() missing 1 required positional argument: 'form'

You need to pass the form parameter to the super class call to form_invalid i.e
return super(LoginView, self).form_invalid(form)

Related

Seperate login for custom user and django admin in Django

I'm currently working on a django project and I have a custom user model in my django app. Custom user authentication is working perfectly, but the issue I'm facing is whenever I'm logging into admin account in the django admin site, it logs out the previous user(let say, user2) and admin being logged in.
How Can I separate their login, so that admin site logins don't interfere with my website login?
Here is my code attached:
Custom User model and its manager:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class CustomerManager(BaseUserManager):
def create_user(self, email, username, name, password=None):
if not email:
raise ValueError('Users must have an email address to register')
if not username:
raise ValueError('Users must have an username address to register')
if not name:
raise ValueError('Users must enter their name to register')
user = self.model(
email = self.normalize_email(email),
username = username,
name=name,
)
user.set_password(password)
user.save(using = self._db)
return user
def create_superuser(self, email, username, name, password=None):
user = self.create_user(
email = self.normalize_email(email),
username = username,
name=name,
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Customer(AbstractBaseUser):
# user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
email = models.EmailField(max_length=254, null=True, unique=True)
username = models.CharField(max_length=40, unique=True)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=10, null=True)
address = models.CharField(max_length=500, null=True)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(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)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'name']
objects = CustomerManager()
def __str__(self):
return self.name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
Login View:
def loginUser(request):
if request.user.is_authenticated:
return redirect('home')
else:
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Email or Password didn\'t match!')
context = {}
return render(request, 'accounts/login.html', context)
Logout View:
#login_required(login_url='login')
def logoutUser(request):
logout(request)
return redirect('login')
User Profile View:
#login_required(login_url='login')
def userProfile(request, email):
customer = Customer.objects.filter(email=email).first()
context = {'customer':customer}
return render(request, 'accounts/profile.html', context)
CreateUserForm and LoginForm:
class CreateUserForm(UserCreationForm):
class Meta:
model = Customer
fields = ['username', 'email', 'name', 'password1', 'password2']
# fields = '__all__'
class LoginForm(forms.ModelForm):
password = forms.CharField(label='password', widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ['email', 'password']
def clean(self):
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(email=email, password=password):
raise forms.ValidationError('Incorrect Login')
When User3 is logged in and admin is not logged in:
As soon as admin logged in:
User3 automatically logs out and admin logs in..

Django Manager isn't available

AttributeError at /register/
Manager isn't available; 'auth.User' has been swapped for 'accounts.Account'
I'm trying to create a registration form but getting the AttributeError.
How can to avoid the error?
Here is the code in of my custom model in
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have a username')
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
about = models.TextField(('about'), max_length=500, blank=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)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = MyAccountManager()
def __str__(self):
return self.email
# For checking permissions. to keep it simple all admin have ALL permissons
def has_perm(self, perm, obj=None):
return self.is_admin
# Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY)
def has_module_perms(self, app_label):
return True
views.py
from django.shortcuts import render
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from .forms import *
from django.contrib.auth import get_user_model
def register_view(request, *args, **kwargs):
form = CreateUserForm(request.POST or None)
if form.is_valid():
user = form.save(commit=True)
user.set_password(form.cleaned_data.get('password1'))
context = {
'form':form,
'btn_label':'Register',
'title':'Register'
}
return render(request, 'auth/auth.html', context)
I updated the setting.py file and set the following link to the Account model in accounts app
settings.py
AUTH_USER_MODEL = 'accounts.Account'
Traceback
Exception Type: AttributeError at /register/
Exception Value: Manager isn't available; 'auth.User' has been swapped for 'accounts.Account'

Django - user uploaded images not appearing in media/images folder

When I complete the profile of a test user, it adds the name of the uploaded file to the DB, and I am able to access the user's profile image file name with {{ user.profile.profile_pic }}, however the image does not appear in my_project/media/images. Thanks for any advice.
Here are the relevant files, I can add more if needed:
settings.py (last two lines)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
accounts/models.py
from django.db import models
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, password=None, is_staff=False, is_superuser=False, is_active=True, is_confirmed=False):
if not email:
raise ValueError("Users must have an email address.")
if not password:
raise ValueError("Users mush have a password.")
user_obj = self.model(email = self.normalize_email(email))
user_obj.set_password(password) #also to change password
user_obj.staff = is_staff
user_obj.admin = is_superuser
user_obj.active = is_active
user_obj.confirmed = is_confirmed
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, email, password=None):
user = self.create_user(email, password=password, is_staff=True)
return user
def create_superuser(self, email, password=None):
user = self.create_user(email, password=password, is_staff=True, is_superuser=True)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=255,unique=True)
USERNAME_FIELD = 'email'
active = models.BooleanField(default=False)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
confirmed = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(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.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
#property
def is_confirmed(self):
#confirmed email address
return self.confirmed
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
#extend extra data, i.e. name, location, ect.
first_name = models.TextField(max_length=16)
profile_pic = models.ImageField(upload_to = 'images/')
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
accounts/views.py
def complete_setup(request):
user_id = request.user.id
if request.method == 'POST':
#handle form data
#and redirect to home or whatever they were looking at
user = User.objects.get(pk=user_id)
user.profile.first_name = request.POST["first_name"]
user.profile.profile_pic = request.POST["image"]
user.save()
return redirect('home')
else:
#serve form
#only serve if profile not complete
if request.user.is_authenticated:
print("user is logged in...")
try:
name = request.user.profile.name
print("user has completed profile")
return render(request, 'home')
except:
return render(request, 'accounts/complete-setup.html')
else:
print("user is not logged in")
return redirect('login')
instead of user.profile.profile_pic = request.POST["image"] use this
`user.profile.profile_pic = request.FILES["image"]`
also, hope yo have add enctype="multipart/form-data" in your form tag like this:
<form method="post" enctype="multipart/form-data">
add this in urls.py
urlpatterns = [
# urls
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Getting an error 'function' object has no attribute '_meta' django 2.0

trying to use login and registration with Django custom user using AbstractUserModel
Now getting this error during makemigrations
I am using Django 2.0.7 and python 3.6.6
models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class UserManager(BaseUserManager):
def create_user(self,email,full_name,password=None,is_active =
True,is_staff=False,is_admin=False):
if not email:
raise ValueError("Put an email address")
if not password:
raise ValueError("Input a password")
if not full_name:
raise ValueError("You must add your fullname")
user= self.model(
email=self.normalize_email(email),
fullname=full_name
)
user.set_password(password)
user.staff = is_staff
user.admin = is_admin
user.active = is_active
user.save(using=self._db)
return user
def create_staffuser(self,email,full_name,password=None):
user = self.create_user(
email,
full_name=full_name,
password=password,
is_staff=True
)
return user
def create_superuser(self,email,full_name=None,password=None):
user = self.create_user(
email,
full_name=full_name,
password=password,
is_staff=True,
is_admin=True
)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=50,unique=True)
full_name = models.CharField(max_length=200,blank=True
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name']
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
if self.full_name:
return self.full_name
return self.email
def has_perm(self, perm, obj = None):
return True
def has_module_perms(self, app_level):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
User = get_user_model
class UserAdminChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'full_name','password', 'active', 'admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class LoginForm(forms.Form):
email = forms.EmailField(label='email')
password = forms.CharField(widget=forms.PasswordInput)
class RegisterForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation',
widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email','full_name',)
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(RegisterForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.active = True #send confirmation email
if commit:
user.save()
return user
views.py
from django.shortcuts import render, redirect
from django.views.generic import CreateView, FormView
from django.http import HttpResponse
from .forms import RegisterForm,LoginForm
from django.contrib.auth import authenticate,get_user_model,login
from django.utils.http import is_safe_url
# from django.contrib.auth.models import User
# from django.contrib.auth.decorators import login_required
# Create your views here.
class LoginView(FormView):
form_class = LoginForm
template_name = 'login.html'
success_url = '/' #will be the profile view
def form_valid(self):
request = self.request
next_ = request.GET.get('next')
next_post = request.POST.get('next')
redirect_path = next_ or next_post or None
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
user = authenticate(username=email, password=password)
if user is not None:
login(request, user)
try:
del request.session[]
except:
pass
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
else:
return redirect("/")
return super(LoginView,self).form_invalid()
class RegisterView(CreateView):
form_class = RegisterForm
template_name = 'registratiion.html'
success_url = '/login/'
I am sorry if I have posted anything unnecessary...
if you have any better solution please help me out...
You have missed out the parentheses to call the get_user_model method. It should be:
from django.contrib.auth import get_user_model
User = get_user_model()

"AnonymousUser" Error When Non-Admin Users Log In - Django

When I try to login users registered through my AbstractBaseUser model I get the error:
'AnonymousUser' object has no attribute '_meta'
Which highlights the code:
login(request, user)
However, if the user is an admin there is no problem, leaving me to believe that the problem isn't with the 'login_view', but a problem with how the user is tagged (so to speak) when they are registered with AbstractBaseUser.
Any help would be much appreciated!
Here is my code:
Models.py
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin
)
class UserManager(BaseUserManager):
def create_user(self, first_name, last_name, email, password=None, is_active=True, is_staff=False, is_admin=False):
if not first_name:
raise ValueError("Users must enter their first name")
if not last_name:
raise ValueError("Users must enter their last name")
if not email:
raise ValueError("Users must enter an email")
if not password:
raise ValueError("Users must enter a password")
user_obj = self.model(
first_name = first_name,
last_name = last_name,
email = self.normalize_email(email),
)
user_obj.set_password(password) #set and change password?
user_obj.admin = is_admin
user_obj.staff = is_staff
user_obj.active = is_active
user_obj.save(using=self._db)
return user_obj
def create_superuser(self, first_name, last_name, email, password=None):
user = self.create_user(
first_name,
last_name,
email,
password=password,
is_staff=True,
is_admin=True
)
return user
class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
email = models.EmailField(max_length=255, unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
active = models.BooleanField(default=True) #can login
staff = models.BooleanField(default=False) #staff not superuser
admin = models.BooleanField(default=False) #superuser
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = UserManager()
def __str__(self):
return self.email
def get_first_name(self):
return self.email
def get_last_name(self):
return self.email
def get_short_name(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.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
Forms.py
from django import forms
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth.models import User, Group
User = get_user_model()
class UserAdminCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
def save(self, commit=True):
user = super(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserAdminChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'password', 'admin')
def clean_password(self):
return self.initial["password"]
class LoginForm(forms.Form):
username = forms.CharField(label='Email')
password = forms.CharField(widget=forms.PasswordInput)
Views.py
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
from django.shortcuts import redirect
from .forms import UserAdminCreationForm, LoginForm
def register_view(request):
form = UserAdminCreationForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
password = form.cleaned_data.get('password')
user.set_password(password)
user.save()
user.groups.add(Group.objects.get(name='customers'))
login(request, user)
context = {
"form": form,
}
return render (request, "register.html", context)
def login_view(request):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
login(request, user)
context = {
"form": form,
}
return render (request, "login.html", context)
Try using the methods that the BaseClass provides. That will prevent you from making unexpected errors.
You can use super() for that purpose.

Categories

Resources