userform
class UserForm(forms.ModelForm):
confirm_password = forms.CharField(label="Confirm Password",widget=forms.PasswordInput(attrs = {'placeholder': 'Confirm Password','class':'required'}))
phone = forms.CharField(max_length = 15,widget = forms.TextInput(attrs = {'placeholder':'Enter mobile no. ','class':'required number'}))
profession = forms.CharField(max_length= 50,widget = forms.Select(choices = PROFESSION_CHOICES,attrs = {'class':'required'}))
email = forms.EmailField(label='Email address',max_length = 75,widget = forms.TextInput(attrs={'placeholder':'Enter a valid email.','class':'required email'}))
sex = forms.CharField(max_length = 20,label="I am :",widget=forms.Select(choices=SEX_CHOICES,attrs = {'class':'required'}))
password = forms.CharField(label="Password",widget=forms.PasswordInput(attrs = {'placeholder': 'Password','class':'required'}))
first_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Please enter your real name.','class':'required alphabets'}))
last_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter last name.','class':'required alphabets'}))
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
if first_name == '':
raise forms.ValidationError("This field is required.")
def clean_phone(self):
phone = self.cleaned_data['phone']
if phone == '':
raise forms.ValidationError("This field is required.")
def clean_last_name(self):
last_name = self.cleaned_data['last_name']
if last_name == '':
raise forms.ValidationError("This field is required.")
def clean_email(self):
email = self.cleaned_data.get("email")
try:
user = User.objects.get(email = email)
raise forms.ValidationError("Email already in use.")
except User.DoesNotExist:
return email
def clean_profession(self):
profession = self.cleaned_data['profession']
if profession == "":
raise forms.ValidationError("Select a valid option.")
def clean_sex(self):
sex = self.cleaned_data['sex']
if sex == "":
raise forms.ValidationError("Select a valid option.")
def save(self,*args,**kw):
user = super(UserForm,self).save(*args,**kw)
user.set_password(self.cleaned_data.get("password"))
user.first_name = self.cleaned_data.get("first_name")
user.last_name = self.cleaned_data.get("last_name")
user.email = self.cleaned_data.get("email")
user.save()
user.get_profile().phone = self.cleaned_data.get('phone')
user.get_profile().location = self.cleaned_data.get('location')
user.get_profile().profession = self.cleaned_data.get('profession')
user.get_profile().sex = self.cleaned_data.get('sex')
return user
class Meta:
model = User
fields = ('username','email','password','confirm_password','first_name','last_name','sex','phone','profession')
widgets = {
'password': forms.PasswordInput(),
}
user registration view
def register_user(request):
if request.POST:
data = request.POST.copy()
data["username"] = 'user'
rform = UserForm(data)
#form = UserProfileForm()
if rform.is_valid():
try:
user = rform.save()
user.username = "user"+str(user.id)
user.save()
user = authenticate(username = user.username,password=user.password)
#register user
login(request,user)
return redirect(index)
except:
print "Unexpected error"
raise
else:
# submit the same form again.
form = LoginForm();
sform = LoginForm()
return render_to_response('register.html',{'rform':rform,'form':form,'sform':sform},context_instance = RequestContext(request))
else:
rform = UserForm()
#form = UserProfileForm()
form = LoginForm()
sform = LoginForm()
return render_to_response('register.html',{'rform':rform,'form':form,'sform':sform},context_instance = RequestContext(request))
error
IntegrityError at /accounts/register/
auth_user.first_name may not be NULL
doubt
When i was using the normal user authentication , everything was working perfectly but when i am using it with email authentication , it gives me the above error ,
how do i get past this error , please help , and also how do i make the email field unique as in how do i add index to this field , please help
Your custom field cleaning methods (clean_*) do not return the cleaned value. From the form validation docs: https://docs.djangoproject.com/en/1.4/ref/forms/validation/
Just like the
general field clean() method, above, this method should return the
cleaned data, regardless of whether it changed anything or not.
clean_first_name does not have a return which is the same as returning None and the reason why Django is trying to insert a NULL for this field.
Related
I`m wrirting site on Django and I need to make a system for registration and authorization of work peepers, for this I use the Django AbstractUser model, registration works well, but authorization does not work, and the authenticate method returns None
Here is my JobseekerRegsiterInfo model:
class JobseekerRegisterInfo(AbstractUser):
username = first_name = last_name = None
id = models.BigAutoField(primary_key=True)
phone_number = PhoneNumberField()
email = models.EmailField(unique=True)
full_name = models.CharField(max_length=120)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['phone_number', 'full_name', 'hashed_password']
def __str__(self):
return self.full_name
My login form:
class JobseekerLoginForm(forms.Form):
email = forms.EmailField(label='Введіть ваш Email: ',
widget=forms.EmailInput(attrs={'class': 'form-control'}))
password = forms.CharField(label='Ваш пароль: ',
widget=forms.PasswordInput(attrs={'class': 'form-control'}))
def clean_email(self):
email = self.cleaned_data['email']
# if not select_field_value_from_model(JobseekerRegisterInfo, 'email', email):
if not JobseekerRegisterInfo.objects.filter(email=email):
raise forms.ValidationError('Неправильно введені email або пароль')
return email
and view function:
def jobseeker_login_view(request):
title = 'Авторизація'
context = {'title': title}
if request.method == 'POST':
form = JobseekerLoginForm(request.POST)
context['form'] = form
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(request, email=email, password=password)
print(generate_password_hash(password))
if user:
print(user)
else:
print('USER IS NONE')
else:
form_errors = form.errors.as_data()
custom_error = custom_error_service(form_errors)
context['list_first_error'] = custom_error
else:
form = JobseekerLoginForm()
context['form'] = form
return render(request, template_name='jobseeker/jobseeker_login.html', context=context)
But only USER IS NONE is displayed in the console, no matter what I do
Tell me, please, how to use authenticate correctly in my case
I need to get the selected value(s) of year from the PreceptorForm. I can get the internal_tel using post.internal_tel but I can't do that with year because it's a ManyToManyField. I need something like preceptor.year.add(post.year) but it gives me an error. What is the best way to do it?
models.py
class Year(models.Model):
year_number = models.IntegerField(choices=YEAR_CHOICES)
division = models.CharField(choices=DIVISION_CHOICES, max_length=1)
def getStudents(self):
results = Student.objects.filter(year=self)
return results
def __str__(self):
return "{}-{}".format(self.year_number, self.division)
class Preceptor(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE)
internal_tel = models.IntegerField(blank=True)
year = models.ManyToManyField(Year,blank=True,related_name='preceptores')
def getYear(self):
results = self.year.all()
return results
def __str__(self):
return "{} {}".format(self.user.first_name, self.user.last_name)
forms.py
class PreceptorForm(ModelForm):
class Meta:
model = Preceptor
fields = '__all__'
exclude = ['user']
views.py
def register_user(request):
if request.method == "POST":
form = PreceptorForm(request.POST)
username = request.POST['username']
password = request.POST['password']
sec_pass = request.POST['sec_password']
email = request.POST['email']
first_name = request.POST['first_name']
last_name = request.POST['last_name']
if form.is_valid():
if password == sec_pass:
user = User.objects.create_user(username, email, password)
user.is_active = True
user.first_name = first_name
user.last_name = last_name
user.save()
print "form"
post = form.save(commit=False)
post.user = user
preceptor = Preceptor(user=user,internal_tel=post.internal_tel)
preceptor.save()
preceptor.year.add(post.year)
preceptor.save()
return redirect('/')
else:
form = PreceptorForm()
return render(request, 'register.html', {'form': form})
I'm having this error at preceptor.year.add(post.year):
< Preceptor: 'name' > needs to have a value for field "id" before this many-to-many relationship can be used.
I made a clean_email function in my forms.py to check if the email the person is signing up with is part of a registered school.
This is the form:
class StudentRegister(UserCreationForm):
email = forms.EmailField(required = True)
def __init__(self, *args, **kwargs):
super(StudentRegister, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['placeholder'] = 'example#example.com'
self.fields['first_name'].widget.attrs['placeholder'] = 'First Name'
self.fields['last_name'].widget.attrs['placeholder'] = 'Last Name'
self.fields['password1'].widget.attrs['placeholder'] = 'Password'
self.fields['password2'].widget.attrs['placeholder'] = 'Password'
class Meta:
model = get_user_model()
fields = (
'email',
'first_name',
'last_name',
'password1',
'password2'
)
def clean_email(self):
email = self.cleaned_data.get('email')
email = email.split('#')[1]
try:
school = School.objects.get(email_domain = email)
except ObjectDoesNotExist:
raise forms.ValidationError('School not found, check your email')
return email
def save(self):
user = super(StudentRegister, self).save()
student = Student(user = user)
student.save()
return user, student
This is the view for the student registration:
def student_registration(request):
#Student Registration
if request.method == 'POST':
form = StudentRegister(request.POST)
#Gets school object from email domain.
email = form['email'].value().split('#')[1]
try:
school = School.objects.get(email_domain = email)
except ObjectDoesNotExist:
pass
if form.is_valid() and school:
user, Student = form.save()
Student.school = school
Student.save()
user.groups.add(Group.objects.get(name='Student'))
#user.is_active to stop users logging in without confirming their emails
user.is_active = False
user.save()
#Sends confirmation link.
send_confirmation_email(request, user)
args = {'email': user.email,
'link': user.Student.school.email_website,}
return render(request, 'email/token_sent.html', args)
else:
args = {'form': form,}
return render(request, 'users/students.html', args)
else:
form = StudentRegister()
args = {'form': form,}
return render(request, 'users/students.html', args)
The error that appears on the form is "Enter a valid email address." even if I enter in a valid email.
Any ideas what the problem may be?
In clean_email method you override original email with domain. Change yout code to this:
def clean_email(self):
original_email = self.cleaned_data.get('email')
email = original_email.split('#')[1]
try:
school = School.objects.get(email_domain = email)
except ObjectDoesNotExist:
raise forms.ValidationError('School not found, check your email')
return original_email
I am working on a Django project and it seems like I can not use the cleaned_data module anywhere in my program. Every time I use it, it raises a key error (saying that key doesn't exist) and when I use cleaned_data.get it just passes nothing. I can use only "form.data" (as you can see in my code) and everything works fine. I just want to know why I can't use the cleaned_data?
here is my form.py:
class RegisterationForm(forms.Form):
first_name = forms.CharField
last_name = forms.CharField
username = forms.CharField
email = forms.EmailField
password = forms.CharField
password2 = forms.CharField
def clean(self):
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password and password != password2:
raise forms.ValidationError("passwords do not match")
return self.cleaned_data
here is my view.py:
def register(request):
if request.method == 'POST':
form = RegisterationForm(request.POST)
if form.is_valid():
user_info={}
user_info['username'] = form.data['username']
user_info['first_name'] = form.data['first_name']
user_info['last_name'] = form.data['last_name']
user_info['password'] = form.data['password']
user_info['email']= form.data['email']
#salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
#usernamesalt = user_info['username']
#if isinstance(usernamesalt, unicode):
# usernamesalt = usernamesalt.encode('utf8')
user_info['activation_key'] = 1#hashlib.sha1(salt+usernamesalt).hexdigest()
form.sendEmail(user_info)
form.save(user_info)
return render_to_response('register_success.html',user_info)
else:
form_save = form
args = {}
args.update(csrf(request))
args['form'] = RegisterationForm()
return render_to_response('register.html',args)
Because you didn't call the parent class clean method to get the data first:
def clean(self):
cleaned_data = super(RegisterationForm, self).clean()
password = cleaned_data.get('password')
password2 = cleaned_data.get('password2')
if password and password != password2:
raise forms.ValidationError("passwords do not match")
Check out django doc about clean method.
If that's really your actual code, your form doesn't have any fields because you have not called any of the field definitions. It should be:
class RegisterationForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
username = forms.CharField()
email = forms.EmailField()
password = forms.CharField()
password2 = forms.CharField()
How to enable users to use other languages such as Chinese in username field using the usercreation form?
The methods I have tried:
modify the regex field of username field, failed
What it tells me: the validation is not with the field, but the user model itself
encode the incoming input using encode("utf-8")
What it tells me: the data i
client side utf transform...
This is the code in view:
def register_user(request):
currentPath = request.POST.get('currentPath', '')
currentPath = currentPath.replace("invalid/", "").replace("registered/", "")
username=request.POST.get('email')
password=request.POST.get('password1')
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
if "log" in currentPath:
return HttpResponseRedirect(currentPath)
else:
return HttpResponseRedirect('/register_success')
elif "log" in currentPath:
return HttpResponseRedirect(currentPath + "registered")
else:
form = MyRegistrationForm()
form.fields['password1'].label = "密码"
form.fields['password2'].label = "再次输入密码"
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('register.html', args)
I think the form.save() is where the problem come from... that the validator automatically validates the field no matter what and chinese characters fail the validation.
And the following is the customized registration form, I have tried to override regex field with an username field but it doesn't work.
my_default_errors = {
'required': '这个格子是必填的',
'invalid': '请输入符合要求的值',
}
class MyRegistrationForm(UserCreationForm):
error_messages = {
'duplicate_username': ("同样的用户名已经被注册了"),
'password_mismatch': ("和上次输入的不一样,请重新输入!"),
}
# this variable defines a field in the customized form, not a model datafield
username = forms.RegexField(label = "用户名(其他所有人可见,请使用英文)", required=True, max_length=30,
regex=r'^[\w.#+-\/\\]+$',
error_messages=my_default_errors,)
email = forms.EmailField(label="邮箱(用于登录)" ,required=True, max_length = 75, error_messages = my_default_errors, )
password1 = forms.CharField(label= "密码", required=True, widget=forms.PasswordInput, error_messages = my_default_errors,)
password2 = forms.CharField(label= "请再次输入", required=True, widget=forms.PasswordInput, error_messages = my_default_errors,)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def clean_email(self):
email = self.cleaned_data["email"]
try:
user = User.objects.get(email=email)
raise forms.ValidationError("这个邮箱地址已被注册,是否忘记了密码?")
except User.DoesNotExist:
return email
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
user.is_active = True # change to false if using email activation
if commit:
user.save()
return user