KeyError: 'password1': password1 = self.cleaned_data['password1'] - python

I am trying to implement registration in Django and faced with error:
forms.py line 17, in clean_password
KeyError: 'password1': password1 = self.cleaned_data['password1']
How can I solve the error?
Full code of the application located here (branch Login-version-2-site ): https://github.com/mascai/reg_app/tree/Login-version-2-site
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.dispatch import Signal
from .utilities import send_activation_notification
class AdvUser(AbstractUser):
is_activated = models.BooleanField(default=True, db_index=True,
verbose_name='Пpoшeл активацию?')
send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?')
class Meta(AbstractUser.Meta):
pass
user_registrated = Signal(providing_args=['instance'])
def user_registrated_dispatcher(sender, **kwargs):
send_activation_notification(kwargs['instance'])
user_registrated.connect(user_registrated_dispatcher)
forms.py
class RegisterUserForm(forms.ModelForm):
email = forms.EmailField(required=True, label="Email address")
password1 = forms.CharField(label="Password", widget=PasswordInput,
help_text=password_validation.password_validators_help_text_html())
password2 = forms.CharField(label="Password", widget=PasswordInput,
help_text=password_validation.password_validators_help_text_html())
def clean_password(self):
password1 = self.cleaned_data['password1']
if password1:
password_validation.validate_password(password1)
return password1
def clean(self):
super().clean()
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')}
raise ValidationError(errors)
else:
return self.cleaned_data
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data['password1'])
user.is_active = False
user.is_activated = False
if commit:
user.save()
user_registrated.send(RegisterUserForm, isinstance=user)
return user
class Meta:
model = AdvUser
fields = ('username', 'email', 'password', 'password2',
'first_name', 'last_name', 'send_messages')
urls.py
from .views import BBLoginView, BBLogoutView, profile, RegisterUserView, RegisterDoneView, user_activate
urlpatterns = [
path('', views.post_list, name='post_list'),
path('accounts/login/', BBLoginView.as_view(), name='login'),
path('accounts/profile/', profile, name='profile'),
path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
path('accounts/register/done', RegisterDoneView.as_view(), name='register_done'),
path('accounts/register/', RegisterUserView.as_view(), name='register'),
path('accounts/register/activate/<str:sign>/', user_activate, name='register_activate'),
]
views.py
def post_list(request):
return render(request, 'blog/post_list.html', {})
class BBLoginView(LoginView):
template_name = 'blog/login.html'
class BBLogoutView(LoginRequiredMixin, LogoutView):
template_name = 'blog/logout.html'
#login_required
def profile(request):
return render(request, 'blog/profile.html')
class RegisterUserView(CreateView):
model = AdvUser
template_name = 'blog/register_user.html'
form_class = RegisterUserForm
success_url = '/register_done'
class RegisterDoneView(TemplateView):
template_name = "blog/register_done.html"
def user_activate(request, sign):
try:
username = signer.unsign(sign)
except:
return render(request, 'blog/bad_signature.html')
user = get_object_or_404(AdvUser, username=username)
if user.is_activated:
template = 'blog/user_is_activated.html'
else:
template = 'blog/activation_done.html'
user.is_active = True
user.is_activated = True
user.save()
return render(request, template)

In a Django form every clean_<field_name> can safely handle only <field_name>, there is no guarantee that another field is available in cleaned_data at that point, it's available only if it has been already cleaned.
Since what you want to do is to clean password1, rename clean_password to clean_password1.

Related

How can I save the username in the database as an email?>

I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much!
model.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email_confirmed = models.BooleanField(default=False)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
# Sign Up Form
class SignUpForm(UserCreationForm):
# first_name = forms.CharField(max_length=30, required=False, help_text='Optional')
# last_name = forms.CharField(max_length=30, required=False, help_text='Optional')
email = forms.EmailField(max_length=254, help_text='Enter a valid email address')
class Meta:
model = User
fields = [
'username',
'password1',
'password2',
]
views.py
from django.contrib import messages
from django.contrib.auth.models import Group
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.template.loader import render_to_string
from .token import AccountActivationTokenGenerator, account_activation_token
from django.shortcuts import render, redirect
from .forms import *
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model, login
from django.utils.http import urlsafe_base64_decode
from django.views.generic import View, UpdateView
from django.contrib.auth.decorators import login_required
from .decorators import *
from django.urls import reverse_lazy
from django.utils.encoding import force_str
#unauthenticatedUser
def Example_login(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return redirect('Example_dashboard')
else:
messages.info(request, 'Username OR password is incorrecct')
context = {}
return render(request, 'accounds/templates/Example_login.html', context)
def reset_passwrd(request):
return render(request, "reset_password.html")
#login_required(login_url='login')
def Example_dashboard(request):
form = MembersForm()
current_user = request.user
name = current_user.username.split(".")[0]
context = {'form': form, "cunrrent_user": name}
return render(request, 'example_dashboard.html', context)
def Login(request):
if request.method == 'POST':
email = request.POST.get('Benutzername')
password = request.POST.get('Passwort')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return redirect('Example_dashboard')
else:
messages.info(request, 'Username OR password is incorrecct')
return render(request, "login.html")
def logoutUser(request):
logout(request)
return redirect('login')
def registrierung(request):
return render(request, "registrierung.html")
#unauthenticatedUser
def Example_register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
#username = form.cleaned_data.get('usernname')
group = Group.objects.get(name='studends')
user.groups.add(group)
messages.success(request, 'Account was created' )
return redirect('login')
contex = {'form' : form}
return render(request, 'exampl_register.html',contex)
# Sign Up View
class SignUpView(View):
form_class = SignUpForm
template_name = 'signup.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False # Deactivate account till it is confirmed
user.save()
current_site = get_current_site(request)
subject = 'Activate Your MySite Account'
message = render_to_string('account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
messages.success(request, ('Please Confirm your email to complete registration.'))
return redirect('login')
return render(request, self.template_name, {'form': form})
class ActivateAccount(View):
def get(self, request, uidb64, token, *args, **kwargs):
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.profile.email_confirmed = True
user.save()
login(request, user)
messages.success(request, ('Your account have been confirmed.'))
return redirect('login')
else:
messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.'))
return redirect('login')
I Need your help
If you want to use email instead of the default username, you have to overwrite the default User model with the custom one
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
# Use the email for logging in
email = models.EmailField(max_length=254, unique=True)
USERNAME_FIELD = 'email'

Django Login with Email or Phone Number

I have been trying to find a solution of a problem in Django for a very long time. The problem is I am trying to develop a login system than can use either email or phone number to authenticate user.
Well, that can be done using by creating a custom user model . I have tested this. It works.
First steps
The first thing you need to do is create a new Django project. Make sure you don't run migrations because there are still a few things we need to do before then.
After creating your new Django project, create a new app called accounts with the following command:
python manage.py startapp accounts
Creating the User Model
By default, the User model provided by Django has a username field, and an email field. However, we also need a phone number field. In order to add this field, we need to extend the Django user model. In the accounts app's models.py file, type in the following code:
models.py
phone_validator = RegexValidator(r"^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$", "The phone number provided is invalid")
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=100, unique=True)
phone_number = models.CharField(max_length=16, validators=[phone_validator], unique=True)
full_name = models.CharField(max_length=30)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
# is_translator = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'phone_number'
REQUIRED_FIELDS = ['email', 'full_name']
def __str__(self):
return self.email
#staticmethod
def has_perm(perm, obj=None, **kwargs):
return True
#staticmethod
def has_module_perms(app_label, **kwargs):
return True
#property
def is_staff(self):
return self.is_admin
Register the model with the admin
admin.py
class UserAdmin(BaseUserAdmin):
form = UserChangeForm
add_form = UserCreationForm
list_display = ('email', 'phone_number', 'full_name', 'is_active', 'is_admin')
list_filter = ('is_active', 'is_admin')
fieldsets = (
(None, {'fields': ('full_name', 'email', 'phone_number', 'password')}),
('Permissions', {'fields': ('is_active', 'is_admin', 'is_superuser', 'last_login', 'groups', 'user_permissions')}),
)
add_fieldsets = (
(None, {'fields': ('full_name', 'phone_number', 'email', 'password1', 'password2')}),
)
search_fields = ('email', 'full_name')
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions')
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
is_superuser = request.user.is_superuser
if is_superuser:
form.base_fields['is_superuser'].disabled = True
return form
admin.site.register(User, UserAdmin)
forms.py
class UserLoginForm(forms.Form):
email = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
for login costumer in login.html
views.py
import random
from .backends import EmailPhoneUsernameAuthenticationBackend as EoP
class UserLoginView(View):
form_class = UserLoginForm
template_name = 'accounts/login.html'
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('core:home')
return super().dispatch(request, *args, **kwargs)
def get(self, request):
form = self.form_class
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = EoP.authenticate(request, username=cd['email'], password=cd['password'])
if user is not None:
login(request, user)
messages.success(request, 'You have successfully logged in!', 'success')
return redirect('core:home')
else:
messages.error(request, 'Your email or password is incorrect!', 'danger')
return render(request, self.template_name, {'form': form})
Writing a Custom Backend
backends.py
from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model
from django.db.models import Q
User = get_user_model()
class EmailPhoneUsernameAuthenticationBackend(object):
#staticmethod
def authenticate(request, username=None, password=None):
try:
user = User.objects.get(
Q(phone_number=username) | Q(email=username)
)
except User.DoesNotExist:
return None
if user and check_password(password, user.password):
return user
return None
#staticmethod
def get_user(user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Update the settings (3 Options)
settings.py
INSTALLED_APPS = [
...
# Third-party apps
'accounts.apps.AccountsConfig',
...
]
AUTH_USER_MODEL = 'accounts.User'
AUTHENTICATION_BACKENDS = [
'accounts.backends.EmailPhoneUsernameAuthenticationBackend'
]
I hope your problem will be solved and others will use it.
Well that can be done using by creating a custom user model . This is the only way known to me to achieve the result.
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
def get_profile_image_filepath(self , filepath):
return 'profile_images/' + str(self.pk) + '/profile_image.png'
def get_default_profile_image():
return "dummy_image.png"
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)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
profile_image = models.ImageField(max_length=255,
upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image)
hide_email = models.BooleanField(default=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = MyAccountManager()
def __str__(self):
return self.username
def get_profile_image_filename(self):
return str(self.profile_image)[str(self.profile_image).index('profile_images/' + str(self.pk) + "/"):]
# 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
This is the custom user model and this will login via the email of the user .
You have to define in the settings.py for the user auth model .
In settings.py add this
AUTH_USER_MODEL = "user_app.Account"
replace the "user_app" with the app in whose models.py this model is stored .
And also you need to tell to the admin to do so .
go to admin.py of the app and add this .
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from account.models import Account
class AccountAdmin(UserAdmin) :
list_display = ("email" , "username" , "date_joined" , "last_login" , "is_admin" , "is_staff")
search_fields = ("email" , "username")
readonly_fields = ("id" , "date_joined" , "last_login")
filter_horizontal = ()
list_filter = ()
fieldsets = ()
admin.site.register(Account , AccountAdmin)
Another way of achieving the result is to take email or phone number credential and password from the user and then in the views find out the username and then log the user in..
Create a form and then create a save method to do this , or diectly do it in the views.
Like this :
def loginView(request) :
if request.POST :
email = request.POST.get("email")
password = request.POST.get("password")
user = User.objects.get(email = email)
if user.check_password(password) :
login(request, user)
return redirect("home")

Unknown field(s) (model) specified for User

I am build project ,when i run python manage.py makemigrations
i got this error
File "/mnt/c/Users/ZAKARIA/Desktop/project/Accounts/admin.py", line 45, in <module>
class UpdateUserForm(forms.ModelForm):
File "/mnt/c/Users/ZAKARIA/Desktop/project/env/lib/python3.8/site-packages/django/forms/models.py", line 327, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (is_staff) specified for User
** Here is my code for models.py**
import datetime
from django.core.mail import send_mail
from distutils.command.upload import upload
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils import timezone
from phonenumber_field.modelfields import PhoneNumberField
from .managers import UserManger
GENDER_MALE = "m"
GENDER_FEMALE = "f"
OTHER = "o"
GENDER_CHOICES = (
(GENDER_MALE, "Male"),
(GENDER_FEMALE, "Female"),
(OTHER, "Other"),
)
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
picture = models.ImageField(
upload_to='images/users', null=True, verbose_name="")
is_active = models.BooleanField(default=True)
#is_staff = models.BooleanField(default=False)
phone = PhoneNumberField()
is_admin = models.BooleanField(default=False)
#credits =models.PositiveIntegerField(default=100)
linkedin_token = models.TextField(blank=True, default='')
expiry_date = models.DateTimeField(null=True, blank=True)
objects = UserManger()
USERNAME_FIELD = 'email'
REQURTED_FIELDS = []
def get_full_name(self):
full_name = '%S %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def __str__(self):
return self.email
def has_perm(self, prem, obj=None):
"Does the user have a specific permission?"
return True
def has_module_perm(self, app_label):
"Does the user have permissions to view the app `app_label`?"
return True
#property
def is_staff(self):
"Is the user a member of staff"
return self.is_admin
"""#property
def is_out_of_credits(self):
"Is the user out of credits"
return self.credits > 0
#property
def has_sufficient_credits(self,cost):
return self.credits - cost >= 0
"""
#property
def linkedin_signed_in(self):
return bool(self.linkedin_token) and self.expiry_date > timezone.now()
** Here is my code for manangers.py **
from django.contrib.auth.base_user import BaseUserManager
class UserManger(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, phone, password, **extra_fields):
if not email:
raise ValueError('Users must hava an email address')
user = self.model(
email.self.normalize_email(email),
phone=phone,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, phone, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, phone, password, **extra_fields)
def create_superuser(self, email, phone, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must hava is_superuser=True.')
return self._create_user(email, phone, password, **extra_fields)
** Here is my code for admin.py**
from pyexpat import model
import django
from django.contrib import admin
from django import forms
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
class AddUserForm(forms.ModelForm):
"""
new User Form . Requires password confirmation.
"""
password1 = forms.CharField(
label='Password', widget=forms.PasswordInput
)
password2 = forms.CharField(
label='Confirm password', widget=forms.PasswordInput
)
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'gender')
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 do not match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UpdateUserForm(forms.ModelForm):
"""
Update User Form ,Doesn't allow changing password in the Admin
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = (
'email', 'password', 'first_name', 'gender', 'last_name', 'is_active',
'is_staff'
)
def clean_password(self):
return self.initial["password"]
class UserAdmin(BaseUserAdmin):
form = UpdateUserForm
add_form = AddUserForm
list_display = ('email', 'first_name', 'last_name',
'gender', 'is_staff')
list_filter = ('is_staff',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {
'fields': ('first_name', 'last_name', 'gender')}),
('Permissions', {'fields': ('is_active', 'is_staff')}),
)
add_fieldsets=(
(
None,
{
'classes':('wide',),
'fields':(
'email','first_name', 'last_name', 'gender','password1','password2'
)
}
),
)
search_fields=('email','first_name','last_name')
ordering =('email','first_name','last_name')
filter_horizontal = ()
admin.site.register(User, UserAdmin)
** Here is my code for forms.py**
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UserCreationForm
from Accounts.models import User
class UserRegistrationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
UserCreationForm.__init__(self, *args, *kwargs)
self.fields['gender'].required = True
self.fields['first_name'].label = "First Name :"
self.fields['last_name'].label = "Last Name :"
self.fields['email'].label = "Email :"
self.fields['password1'].label = "Password"
self.fields['password2'].label = " Confirm Password"
self.fields['gender'].label = "Gender"
self.fields['phone'].label = "Phone"
self.fields['date_of_birth'].label = "Date Of Birth"
self.fields['first_name'].widget.attrs.update(
{
'placeholder': 'Enter First Name',
}
)
self.fields['last_name'].widget.attrs.update(
{
'placeholder': 'Enter Last Name',
}
)
self.fields['email'].widget.attrs.update(
{
'placeholder': 'Enter Email',
}
)
self.fields['password1'].widget.attrs.update(
{
'placeholder': 'Enter Password',
}
)
self.fields['password2'].widget.attrs.update(
{
'placeholder': 'Confirm Password',
}
)
self.fields['phone'].widget.attrs.update(
{
'placeholder': 'Enter Phone',
}
)
self.fields['date_of_birth'].widget.attrs.update(
{
'placeholder': 'Enter Date Of Birth',
}
)
class Meta:
model = User
fields = ['first_name', 'last_name', 'email', 'phone',
'password1', 'password2', 'gender', 'date_of_birth']
def clean_gender(self):
gender = self.cleaned_data.get('gender')
if not gender:
raise forms.ValidationError("Gender is required")
return gender
def save(self, commit=True):
user = UserCreationForm.save(self, commit=False)
user.role = "user"
if commit:
user.save()
return user
class UserLoginForm(forms.Form):
email = forms.EmailField(
widget=forms.EmailInput(attrs={'placeholder': 'Email', })
)
password = forms.CharField(
strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'Password', }))
def clean(self, *args, **kwargs):
email = self.cleaned_data.get("email")
password = self.cleaned_data.get('password')
if email and password:
self.user = authenticate(email=email, password=password)
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
raise forms.ValidationError("User Does not exist")
if not user.check_password(password):
raise forms.ValidationError("Password is not Match")
if not user.is_active:
raise forms.ValidationError("User is not Active")
return super(UserLoginForm, self).clean(**args, **kwargs)
def get_user(self):
return self.user
** Here is my code for views.py**
from django.shortcuts import render
from django.contrib import messages, auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, get_list_or_404
from django.urls import reverse, reverse_lazye
from matplotlib.style import context
from Accounts.forms import *
def get_success_urls(request):
"""
Handle Success Url After Login
"""
if 'next' in request.GET and request.GET['next'] != '':
return request.GET['netx']
else:
return reverse('jobs:home')
def user_registration(request):
"""
Handle user registration
"""
form = UserRegistrationForm(request.POST or None)
if form.is_valid():
form = form.save()
return redirect('Accounts:login')
context = {
'form': form
}
return render(request, 'accounts/user-registeration.html', context)
def user_logIn(request):
"""
Provides users to logIn
"""
form = UserLoginForm(request.POST or None)
if request.user.is_authenticated:
return redirect('/')
else:
if request.method == 'POST':
if form.is_valid():
auth.login(request, form.get_user())
return HttpResponseRedirect(get_success_urls(request))
context = {
'form': form,
}
def user_logOut(request):
"""
Provide the ability to logout
"""
auth.logout(request)
messages.success(request, 'You are Successfully logged out')
return redirect('Accounts:login')
I already took out all of the is_staff attribute in admin.py and still got an error.
Refactored it many times to check if the problem is in different areas of my code.
can any one help me to solve this problem
Double check this is correct:
fields = (
'email', 'password', 'first_name', 'gender', 'last_name', 'is_active',
'is_staff'
the is_staff field, is that an actual field of your user model ?

KeyError: 'instance': send_activation_notification(kwargs['instance'])

I am trying to implement registration in Django and faced with error:
models.py", line 20, in user_registrated_dispatcher
send_activation_notification(kwargs['instance'])
KeyError: 'instance'
I submitted registration form then received this error message.
How can I solve the error?
Could you recommend good tutorial about registration with email in Django?
Full code of the application located here (branch Login-version-2-site ): https://github.com/mascai/reg_app/tree/Login-version-2-site
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.dispatch import Signal
from .utilities import send_activation_notification
class AdvUser(AbstractUser):
is_activated = models.BooleanField(default=True, db_index=True,
verbose_name='Пpoшeл активацию?')
send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?')
class Meta(AbstractUser.Meta):
pass
user_registrated = Signal(providing_args=['instance'])
def user_registrated_dispatcher(sender, **kwargs):
send_activation_notification(kwargs['instance'])
user_registrated.connect(user_registrated_dispatcher)
forms.py
class RegisterUserForm(forms.ModelForm):
email = forms.EmailField(required=True, label="Email address")
password1 = forms.CharField(label="Password", widget=PasswordInput,
help_text=password_validation.password_validators_help_text_html())
password2 = forms.CharField(label="Password", widget=PasswordInput,
help_text=password_validation.password_validators_help_text_html())
def clean_password1(self):
password1 = self.cleaned_data['password1']
if password1:
password_validation.validate_password(password1)
return password1
def clean(self):
super().clean()
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')}
raise ValidationError(errors)
else:
return self.cleaned_data
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data['password1'])
user.is_active = False
user.is_activated = False
if commit:
user.save()
user_registrated.send(RegisterUserForm, isinstance=user)
return user
class Meta:
model = AdvUser
fields = ('username', 'email', 'password', 'password2',
'first_name', 'last_name', 'send_messages')
urls.py
from .views import BBLoginView, BBLogoutView, profile, RegisterUserView, RegisterDoneView, user_activate
urlpatterns = [
path('', views.post_list, name='post_list'),
path('accounts/login/', BBLoginView.as_view(), name='login'),
path('accounts/profile/', profile, name='profile'),
path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
path('accounts/register/done', RegisterDoneView.as_view(), name='register_done'),
path('accounts/register/', RegisterUserView.as_view(), name='register'),
path('accounts/register/activate/<str:sign>/', user_activate, name='register_activate'),
]
views.py
def post_list(request):
return render(request, 'blog/post_list.html', {})
class BBLoginView(LoginView):
template_name = 'blog/login.html'
class BBLogoutView(LoginRequiredMixin, LogoutView):
template_name = 'blog/logout.html'
#login_required
def profile(request):
return render(request, 'blog/profile.html')
class RegisterUserView(CreateView):
model = AdvUser
template_name = 'blog/register_user.html'
form_class = RegisterUserForm
success_url = '/register_done'
class RegisterDoneView(TemplateView):
template_name = "blog/register_done.html"
def user_activate(request, sign):
try:
username = signer.unsign(sign)
except:
return render(request, 'blog/bad_signature.html')
user = get_object_or_404(AdvUser, username=username)
if user.is_activated:
template = 'blog/user_is_activated.html'
else:
template = 'blog/activation_done.html'
user.is_active = True
user.is_activated = True
user.save()
return render(request, template)
You passed isinstance=user instead of instance=user when you send the signal inside the save method.
(Note, all this seems like a lot of work. There's already a general post_save signal you could use; but actually there doesn't seem to be much reason to use a signal at all. Why not just send the notification directly?

Django + Angular 405 Method not allowed thinkster.io tutorial

I am going through thinkster.io tutorial about Django and AngularJS. I am about half way of tutorial, but I am getting the error 405 Method not allowed for my POST request of user registration. I tried all sugestions but none of them seems to work ( I also tried to copying whole code from tutorial ). Here is my code:
views.py
from django.shortcuts import render
from rest_framework import permissions, viewsets
from authentication.models import Account
from authentication.permissions import IsAccountOwner
from authentication.serializers import AccountSerializer
class AccountViewSet(viewsets.ModelViewSet):
lookup_field = 'username'
queryset = Account.objects.all()
serializer_class = AccountSerializer
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
if self.request.method == 'POST':
return (permissions.AllowAny(),)
return (permissions.IsAuthenticated(), IsAccountOwner(),)
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
Account.objects.create_user(**serializer.validated_data)
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
return Response({
'status': 'Bad request',
'message': 'Account could not be created with received data.'
}, status=status.HTTP_400_BAD_REQUEST)
serializers.py
from django.contrib.auth import update_session_auth_hash
from rest_framework import serializers
from authentication.models import Account
class AccountSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True, required=False)
confirm_password = serializers.CharField(write_only=True, required=False)
class Meta:
model = Account
fields = ('id', 'email', 'username', 'created_at', 'updated_at',
'first_name', 'last_name', 'tagline', 'password',
'confirm_password',)
read_only_fields = ('created_at', 'updated_at',)
def create(self, validated_data):
return Account.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.username = validated_data.get('username', instance.username)
instance.tagline = validated_data.get('tagline', instance.tagline)
instance.save()
password = validated_data.get('password', None)
confirm_password = validated_data.get('confirm_password', None)
if password and confirm_password and password == confirm_password:
instance.set_password(password)
instance.save()
update_session_auth_hash(self.context.get('request'), instance)
return instance
permissions.py
from rest_framework import permissions
class IsAccountOwner(permissions.BasePermission):
def has_object_permission(self, request, view, account):
if request.user:
return account == request.user
return False
urls.py
from django.conf.urls import patterns, url, include
from thinkster_django_angular_boilerplate.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = patterns(
'',
# ... URLs
url(r'^/api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
models.py
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.db import models
class AccountManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError('Users must have a valid email address.')
if not kwargs.get('username'):
raise ValueError('Users must have a valid username.')
account = self.model(
email=self.normalize_email(email), username=kwargs.get('username')
)
account.set_password(password)
account.save()
return account
def create_superuser(self, email, password, **kwargs):
account = self.create_user(email, password, **kwargs)
account.is_admin = True
account.save()
return account
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
first_name = models.CharField(max_length=40, blank=True)
last_name = models.CharField(max_length=40, blank=True)
tagline = models.CharField(max_length=140, blank=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __unicode__(self):
return self.email
def get_full_name(self):
return ' '.join([self.first_name, self.last_name])
def get_short_name(self):
return self.first_name
I think the problem is with Django code, because AngularJS seems to not throw any errors and I can see that request is coming to the django. I am using python3.4, Django 1.8.3, and Django-rest-framework 3.1.

Categories