I cannot login to any account, because I receive an error:
Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.(for an admin user)
And
Please enter a correct email and password. Note that both fields may be case-sensitive.
That happens after I update a profile through the profile-detail page. It just throws me to the login page after I press the Update button on the profile-update page.
Here is all the related code:
models.py
class Customer(AbstractUser):
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
customer_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
username = models.CharField(max_length=30, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(validators=[validators.EmailValidator()], unique=True)
description = models.TextField(max_length=1000,blank=True, null=True)
gender = models.CharField('Gender', max_length=10, choices=Gender.choices,
default='Male', null=True)
featured_img = models.ImageField(verbose_name='A profile image',
upload_to='profiles',
default='products/profile_default.jpg')
password = models.CharField(max_length=100, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return f'{self.email} {self.username} {self.customer_id}'
#staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def exists(self):
if Customer.objects.filter(email=self.email):
return True
return False
class Meta:
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
# unique_together = ['email']
class Profile(models.Model):
# USERNAME_FIELD = 'email'
profile_id = models.AutoField(primary_key=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True, null=True)
user = models.ForeignKey(Customer, on_delete=models.CASCADE,
related_name="customer", null=True)
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
# unique_together = ['email']
def __str__(self):
return f' {self.profiled}'
managers.py
class UserManager(BaseUserManager):
def create_user(self, email, first_name=None, description=None, gender=None, featured_img=None, username=None, last_name=None, phone=None, password=None):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
user = self.model(
email=self.normalize_email(email),
)
user.first_name = first_name
user.username = username
user.last_name = last_name
user.password = make_password(password) # change password to hash
user.phone = phone
user.featured_img = featured_img
user.description = description
# user.profile = profile
user.gender = gender
user.admin = False
user.staff = True
user.active = True
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
user = self.model(
email=self.normalize_email(email)
)
user.username = username
user.password = make_password(password) # chang password to hash
user.admin = True
user.staff = True
user.active = True
user.save(using=self._db)
return user
views.py
#csrf_exempt
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST or None)
email = request.POST['email']
if Customer.get_customer_by_email(email=email) == False:
if form.is_valid():
user = form.save(commit=False)
# account = authenticate(request,
# username=email,
# password=request.POST['password'])
user.username = user.username.lower()
user.save()
login(request, user,
backend='allauth.account.auth_backends.AuthenticationBackend')
messages.success(request, 'The account was successfully created!!!')
return redirect(reverse_lazy('products:products'))
messages.error(request, f'{form.errors}')
return redirect(reverse_lazy('user-auth:register'))
return redirect(reverse_lazy('user-auth:login'))
form = SignUpForm()
context = {'form': form, 'user': request.user}
return render(request, 'auth/register/register.html', context)
class ProfileDetailView(
DetailView):
context_object_name = 'customer'
template_name = 'auth/profile_detail.html'
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['user'] = self.request.user
return context
class UpdateProfileView(LoginRequiredMixin,
UpdateView):
template_name = 'auth/profile_update.html'
form_class = ProfileUpdateForm
context_object_name = 'customer'
def get_success_url(self):
success_url = reverse_lazy('user-auth:profile-detail',
kwargs={'pk': self.request.user.customer_id})
return success_url
#method_decorator(ensure_csrf_cookie, name='dispatch')
def post(self, request, *args, **kwargs):
profile = self.get_object()
form = ProfileUpdateForm(instance=profile)
# if request.method == 'POST':
form = ProfileUpdateForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
if profile:
form.save()
messages.success(request, 'Successfully updated!')
return redirect(self.get_success_url())
messages.error(request, 'Profile does not exist!')
return redirect(reverse_lazy('user-auth:signup'))
messages.error(request, 'Invalid data!')
return render(request, self.template_name, self.get_context_data())
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
# def get(self, request, *args, **kwargs):
# context = {}
# context["form"] = ProfileUpdateForm(instance=self.get_object())
# context['user'] = request.user
# return render(request, self.template_name, context)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = ProfileUpdateForm(instance=self.get_object())
context['user'] = self.request.user
return context
class DeleteProfileView(LoginRequiredMixin,
DeleteView):
context_object_name = 'customer'
template_name = 'auth/profile_confirm_delete.html'
def get_success_url(self):
success_url = reverse_lazy('user-auth:profile-detail',
kwargs={'pk': self.request.user.customer_id})
return success_url
def post(self, request, *args, **kwargs):
self.request = request
if self.get_object:
messages.success(request, 'Profile deleted successfully!')
return super().delete(request, *args, **kwargs)
messages.success(request, 'Profile does not exist!')
return redirect(reverse_lazy('user-auth:signup'))
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
signals.py
#receiver(post_save, sender=Customer)
def create_profile(sender, instance, created, **kwargs):
user = instance
if created:
print(user)
Profile.objects.create(
user=user
)
#receiver(pre_save, sender=Customer)
def update_profile(sender, instance, **kwargs):
# print(instance)
profile = instance
if profile.customer_id is not None:
Profile.objects.update(user=profile)
#receiver(post_delete, sender=Customer)
def delete_profile(sender, instance, **kwargs):
user = instance
customer = Customer.objects.filter(email=user.email).first()
if user and customer:
# profile.delete()
customer.delete()
print('Not exists...')
forms.py
class SignUpForm(UserCreationForm):
class Meta:
model = Customer
fields = ('username','phone', 'first_name', 'last_name', 'email', 'featured_img')
# def __init__(self, *args, **kwargs):
# super(SignUpForm, self).__init__(*args, **kwargs)
# for name, field in self.fields.items():
# field.widget.attrs.update({'class': 'input'})
class ProfileUpdateForm(forms.ModelForm):
password1 = forms.CharField(
label="Password",
strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
help_text=password_validation.password_validators_help_text_html(),
required=False
)
password2 = forms.CharField(
label="Password confirmation",
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
strip=False,
help_text="Enter the same password as before, for verification.",
required=False
)
class Meta:
model = Customer
fields = ('username', 'phone', 'first_name', 'last_name', 'email', 'featured_img', 'description', 'gender')
def save(self, commit=True):
customer = super().save(commit=False)
email = self.cleaned_data.get('email')
customer.email = email.lower()
# customer.password = customer.set_password(self.cleaned_data['password1'])
if commit:
if customer.exists():
super(ProfileUpdateForm, self).save()
return customer
urls.py
from django.contrib.auth import views as auth_views
app_name = 'user-auth'
urlpatterns = [
path('register/', views.signup, name='register'),
path('accounts/login/', auth_views.LoginView.as_view(
template_name='auth/login/login.html',
success_url='products/'),
name='login'
),
path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
path('profile-detail/<int:pk>/', views.ProfileDetailView.as_view(), name='profile-detail'),
path('profile-update/<int:pk>/', views.UpdateProfileView.as_view(),
name='profile-update'),
path('profile-delete/<int:pk>/', views.DeleteProfileView.as_view(),
name='profile-delete'),
]
I have tried to delete my database and fill it in once again. Then I tried to find out why the email or password dis incorrect. Maybe they are wrong in the database. But I have no idea what's going on.
I have a register user form which is doing all the validation as expected. However, it is not saving. I am not able to figure out the reason. How do I debug it ? Any help ? I am a newbie to forms and formviews any good document with example would really help me.
class RegisterForm(forms.ModelForm):
phone_number = forms.IntegerField(required=True)
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
country_code = forms.IntegerField()
#schools = school.objects.all()
#school_name = forms.ModelChoiceField(queryset=school.objects.distinct())
MIN_LENGTH = 4
class Meta:
model = User
fields = ['username','country_code','phone_number', 'password1', 'password2',
'full_name' ]
def clean_phone_number(self):
phone_number = self.data.get('phone_number')
print(phone_number)
if User.objects.filter(phone_number=phone_number).exists():
raise forms.ValidationError(
_("Another user with this phone number already exists"))
if len(phone_number) == 10 and phone_number.isdigit():
pass
else:
raise forms.ValidationError(
_("Invalid Phone Number"))
return phone_number
def save(self, *args, **kwargs):
print("saving")
user = super(RegisterForm, self).save(*args, **kwargs)
user.set_password(self.cleaned_data['password1'])
print('Saving user with country_code', user.country_code)
user.save()
return user
Views.py
class RegisterView(SuccessMessageMixin, FormView):
template_name = 'register-2.html'
form_class = RegisterForm
success_message = "One-Time password sent to your registered mobile number.\
The verification code is valid for 10 minutes."
def form_valid(self, form):
full_name=self.request.POST["full_name"]
user = form.save()
print(user.id)
username = self.request.POST['username']
password = self.request.POST['password1']
user = authenticate(username=username, password=password)
kwargs = {'user': user}
self.request.method = 'POST'
print("User created")
The print in clean_phone_number works however, save does not work
I had issue in the my form. One of the field was disabled and the value was not captured because of that.
However to identify that I used
def form_invalid(self,form):
# Add action to invalid form phase
messages.error(self.request, form.errors)
return self.render_to_response(self.get_context_data(form=form))
Basically i am sending email to user with password and username. I can get the username using self.cleaned_data.get('email'). But the problem is that i dont know how to get password from view which i am setting random password in views. So please help me to get that random password from views.py to forms.py in def send_email
Forms.py
class UserRegisterForm(forms.ModelForm):
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
class Meta:
model = User
fields = ['first_name','last_name', 'email']
def send_email(self):
name = self.cleaned_data.get('first_name')
username = self.cleaned_data.get('email')
to_email = self.cleaned_data.get('email')
password1 = # Get Password from view
Views.py
def register(request):
if request.method == 'POST':
ur_form = UserRegisterForm(request.POST)
pr_form = UserProfileForm(request.POST, request.FILES)
user_role = 0
if ur_form.is_valid() and pr_form.is_valid():
new_user = ur_form.save(commit=False)
new_user.username = new_user.email
password = User.objects.make_random_password() # Pass This to Form send_email
new_user.set_password(password)
new_user.save()
Pass the random password to the form at the time of form initialization and handle that in your UserRegisterForm form by overriding the __init__() method
Try this
# form.py
class UserRegisterForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self._pwd = kwargs.pop('pwd', None)
super().__init__(*args, **kwargs)
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
class Meta:
model = User
fields = ['first_name', 'last_name', 'email']
def send_email(self):
name = self.cleaned_data.get('first_name')
username = self.cleaned_data.get('email')
to_email = self.cleaned_data.get('email')
password1 = self._pwd # access your password from view
# views.py
def register(request):
if request.method == 'POST':
random_password = generate_your_random_password() # generate password here
ur_form = UserRegisterForm(request.POST, pwd=random_password)
pr_form = UserProfileForm(request.POST, request.FILES)
user_role = 0
if ur_form.is_valid() and pr_form.is_valid():
new_user = ur_form.save(commit=False)
new_user.username = new_user.email
new_user.set_password(random_password) # set the random password here
new_user.save()
# your code ....
class CustomAccount(models.Model):
user = models.OneToOneField("auth.User")
role = models.CharField(max_length = 50, default = 'student', choices=APPROVAL_CHOICES)
balance = models.FloatField( default = 0 )
timezone = models.CharField(max_length = 200)
def __str__(self):
return self.user.username +" ["+ self.role + "]"
class CustomAccountForm(forms.ModelForm):
username = forms.CharField(max_length=30 )
email = forms.EmailField(max_length=255 )
password1 = forms.CharField(label= "Password",widget=forms.PasswordInput())
password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput , help_text="Enter the same password as above, for verification.")
def save(self, commit= True):
user = User.objects.create_user(username = self.cleaned_data['username'], email = self.cleaned_data['email'] , password = self.cleaned_data['password1'])
user.save()
self.user = user
return super(CustomAccountForm, self).save(commit=commit)
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("A user with that username already exists.")
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError("The two password fields didn't match.")
return password2
def clean_email(self):
email = self.cleaned_data["email"]
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError("A user with that emailaddress already exists.")
class Meta:
model = CustomAccount
exclude = ['balance','user']
I want to create Custom account in Django Admin section using single form which has fields of auth.User and CustomAccount Model. I have getting error IntegrityError at /admin/mylogin/customaccount/add/
NOT NULL constraint failed: mylogin_customaccount.user_id
Since you are getting a not null error, I think you need to specify that the field is not required. Here is an example from one of my apps. This says that the form field is not required.
class arunModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
myuser = kwargs.pop('user', None)
super(arunModelForm, self).__init__(*args, **kwargs)
self.fields['nanoadded'].required = False
self.fields['response'].required = False
I also include this in my models so that my model fields can be null, like this:
class arun(models.Model):
auser = models.CharField(max_length=50, null=True)
adate = models.DateField(null=True)
atime = models.TimeField(null=True)
If I still get not null errors after I do both of these things, I fill the field with a place holder value to allow me to further investigate the problem.
You have removed the user from the form and in the save method, you have assigned self.user in save method. So when saving the form, the user attribute is not used for CustomAccountForm and the user field for CustomAccount is None.
Your save method should look like:
def save(self, commit= True):
user = User.objects.create_user(username =self.cleaned_data['username'], email = self.cleaned_data['email'] , password = self.cleaned_data['password1'])
user.save()
obj = super(CustomAccountForm, self).save(commit=False)
obj.user = user
obj.save()
i need to create group seekers and user register he has to automatically add to seekers
models.py
class Seeker(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField()
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
forms.py
this is the default user for storing the userid & password for my application
class RegistrationForm(ModelForm):
username = forms.CharField(label = (u'User Name'))
email = forms.EmailField(label =(u'Email Address'))
password = forms.CharField(label = (u'Password'),widget = forms.PasswordInput(render_value = False))
password1 = forms.CharField(label =(u'Verify Password'),widget = forms.PasswordInput(render_value = False))
class Meta:
model = Seeker
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username = username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken,please select another.")
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['password1']:
raise forms.ValidationError("The Password did not match please try again.")
return self.cleaned_data
views.py
i am using default user for creating the user
def SeekersRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username = form.cleaned_data['username'], email = form.cleaned_data['email'], password =form.cleaned_data['password'])
user.save()
seekers = Seeker(user =user, name = form.cleaned_data['name'],birthday = form.cleaned_data['birthday'])
seekers.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html',{'form':form},context_instance = RequestContext(request))
else:
'''user is not submitting the form, show them a blank registration form'''
form = RegistrationForm()
context = {'form':form}
return render_to_response('register.html',context,context_instance = RequestContext(request))
Use signals
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def add_user_to_specific_group(instance, created, **kwargs):
if created:
# assign user to group