How to make Required: boolean field in model Django - python

I have a model with a field called in is_student and is_teacher Student and Teacher forms
is_teacher = models.BooleanField('teacher status', default=False)
is_student = models.BooleanField('student status', default=False)
I want to make sure this field is:
Always Checked by the user True *Required
Currently: is_teacher in TeacherApplications Model
When unchecked - it saved 0 to the form and continues. (Not good)
When checked gives me this error:
ValueError at /register/teacher invalid literal for int() with base
10: ''
Currently: is_student in StudentProfile Model
When checked gives this error
ValidationError at /register/ ["'on' value must be either True or
False."]
When unchecked it saved 0 to the form and continues. (Again, not good)
UPDATED CODE
Above errors are gone: New error each time I try to submit form after checking is_teacher/is_student
IntegrityError at /register/ NOT NULL constraint failed:
accounts_studentprofile.is_student
model
class StudentProfile(models.Model):
user = models.OneToOneField('Accounts', related_name='student_profile')
# additional fields for students
AMEB_Ratings = models.PositiveIntegerField(default=0)
is_student = models.BooleanField('student status', default=False)
class TeacherApplications(models.Model):
user = models.OneToOneField('Accounts', related_name='teacher_profile')
# additional fields for teachers
instrument = models.TextField(max_length=500, blank=True)
skill = models.CharField(max_length=30, blank=True)
experience_in_years = models.PositiveIntegerField(blank=True)
is_teacher = models.BooleanField('teacher status', default=False)
view
def registerStudent(request):
# Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
if request.method == "POST":
user_form = UserForm(request.POST)
form = StudentResistrationForm(request.POST)
if form.is_valid() and user_form.is_valid():
User = get_user_model()
username = user_form.cleaned_data['username']
email = user_form.cleaned_data['email']
password = user_form.cleaned_data['password']
new_user = User.objects.create_user(username=username, email=email, password=password)
student = form.save(commit=False)
student.user = new_user
student.save()
# Student_profile = StudentProfile()
# Student_profile.user = new_user
# Student_profile.AMEB_Ratings = request.POST['AMEB_Ratings']
# Student_profile.is_student = request.POST.get('is_student', False)
new_user.save()
# Student_profile.save()
# form.save()
return redirect('/')
else:
# Create the django default user form and send it as a dictionary in args to the reg_form.html page.
user_form = UserForm()
form = StudentResistrationForm()
# args = {'form_student': form, 'user_form': user_form }
return render(request, 'accounts/reg_form_students.html', {'form_student': form, 'user_form': user_form })
def teacherApplication(request):
# Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
if request.method == "POST":
user_form = UserForm(request.POST)
form = TeacherRegistrationForm(request.POST)
if form.is_valid() and user_form.is_valid():
User = get_user_model()
username = user_form.cleaned_data['username']
email = user_form.cleaned_data['email']
password = user_form.cleaned_data['password']
new_user = User.objects.create_user(username=username, email=email, password=password)
teacher = form.save(commit=False)
teacher.user = new_user
teacher.save()
# Teacher_profile = TeacherApplications()
# Teacher_profile.user = new_user
# Teacher_profile.instrument = request.POST['instrument']
# Teacher_profile.skill = request.POST['skill']
# Teacher_profile.experience_in_years = request.POST['experience_in_years']
# Teacher_profile.is_teacher = request.POST.get('is_teacher', False)
new_user.save()
# Teacher_profile.save()
# form.save()
return redirect('/')
else:
# Create the django default user form and send it as a dictionary in args to the reg_form.html page.
user_form = UserForm()
form = TeacherRegistrationForm()
return render(request, 'accounts/reg_form_teachers.html', {'form_student': form, 'user_form': user_form })
forms
class StudentResistrationForm(forms.ModelForm):
class Meta:
model = StudentProfile
fields = (
'AMEB_Ratings',
'is_student',
)
def save(self, commit=True):
user = super(StudentResistrationForm, self).save(commit=False)
# user.first_name = self.cleaned_data['first_name']
# user.last_name = self.cleaned_data['last_name']
user.AMEB_Ratings = self.cleaned_data['AMEB_Ratings']
if commit:
user.save()
return user
class TeacherRegistrationForm(forms.ModelForm):
class Meta:
model = TeacherApplications
fields = (
'instrument',
'skill',
'experience_in_years',
'is_teacher',
)
class UserForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ('username', 'email', 'password')

You can add this fields to StudentResistrationForm and TeacherRegistrationForm and add custom validation for it in clean_fieldname method to make it required:
StudentResistrationForm(ModelForm):
class Meta:
model = StudentRegistration
fields = (
'instrument',
'skill',
'experience_in_years',
'is_student',
)
def clean_is_student(self):
is_student = self.cleaned_data.get('is_student')
if not is_student:
raise forms.ValidationError('This field is required')
return is_student
Also in view instead of getting raw data from request.POST you can use forms to create student and teacher objects:
new_user = User.objects.create_user(username=username, email=email, password=password)
teacher = form.save(commit=False)
teacher.user = new_user
teacher.save()

Related

User model is not saving create_user instances

I have made a form having fields of personal information and login information as one
models.py
class EmployeeModel(models.Model)
employee_id = models.CharField(max_length=300,unique=True,help_text='Employee ID should not be same')
name = models.CharField(max_length=300)
username = models.CharField(max_length=50,null=True,blank=True)
email = models.EmailField(null=True,blank=True)
password = models.CharField(max_length=20,null=True,blank=True)
password_confirm = models.CharField(max_length=20,null=True,blank=True)
forms.py
class EmployeeForm(forms.ModelForm):
class Meta:
model = employeeModel
fields = ('__all__')
views.py
User = get_user_model()
def create_view(request):
if request.method == 'POST':
form = employeeForm(request.POST or None,request.FILES or None)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
User= get_user_model()
user= User.objects.create_user(username=username,email=email,password=password)
authenticate(request,username=username,email=email,password=password)
form.save()
return redirect('emp_list')
else:
form = employeeForm()
return render(request,'create_employee.html',{'form':form})
Its not showing any error but User.objects.all() shows only superuser not the users i created though this form. Those users i have created in this form are are showing up in Employee.objects.get(username='foo')
So what to do? I cant login through those non_superusers. it throws invalid login error. How to fix this?

Editing profile in django python

I am adding in some functionality that allows a user to edit their personal profile page information. When the user updates their info and hit submit they are getting a NameErrorsaying that the user is not defined. Below is how I am trying to implement the editing functionality.
forms
#this is all the information that the user is allowed to edit.
class UpdateProfile(forms.ModelForm):
username = forms.CharField(required=False)
email = forms.EmailField(required=False)
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
age = forms.IntegerField(required=False)
height = forms.IntegerField(required=False)
weight = forms.IntegerField(required=False)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'age', 'height', 'weight')
def clean_email(self):
username = self.cleaned_data.get('username')
email = self.cleaned_data.get('email')
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError('This email address is already in use. Please supply a different email address.')
return email
def save(self, commit=True):
# user = super(RegisterUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
#This is where i am trying to save the new information.
if commit:
user.save()
#This is where i am returning the user.
return user
Views
def update_profile(request):
args = {}
if request.method == 'POST':
form = UpdateProfile(request.POST, instance=request.user)
form.actual_user = request.user
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('account:profile.html'))
else:
form = UpdateProfile()
args['form'] = form
return render(request, 'account/edit_profile.html', args)

Register Form not saving to database: Django?

Weird issue with by registration form, not sure i am doing wrong.
I have StudentProfile Model, that I am trying to save data from StudentResistrationForm but the data is not being saved into database
ERROR: NameError at /register/ name 'StudentProfile' is not defined
Is the view logic correct? What am I missing? Ideas please
model
class Accounts(AbstractUser):
email = models.EmailField('email address', unique=True)
first_name = models.CharField('first name', max_length=30, blank=True)
last_name = models.CharField('last name', max_length=30, blank=True)
date_joined = models.DateTimeField('date joined', auto_now_add=True)
# asdd
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
class StudentProfile(models.Model):
user = models.OneToOneField('Accounts', related_name='student_profile')
# additional fields for students
AMEB_Ratings = models.PositiveIntegerField(default=0)
is_student = models.BooleanField('student status', default=False)
form
class StudentResistrationForm(forms.ModelForm):
class Meta:
model = StudentProfile
fields = (
'AMEB_Ratings',
)
def save(self, commit=True):
user = super(StudentResistrationForm, self).save(commit=False)
# user.first_name = self.cleaned_data['first_name']
# user.last_name = self.cleaned_data['last_name']
user.AMEB_Ratings = self.cleaned_data['AMEB_Ratings']
if commit:
user.save()
return user
class UserForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ('username', 'email', 'password')
view
def registerStudent(request):
# Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
if request.method == "POST":
user_form = UserForm(request.POST)
form = StudentResistrationForm(request.POST)
if form.is_valid() and user_form.is_valid():
User = get_user_model()
username = user_form.cleaned_data['username']
email = user_form.cleaned_data['email']
password = user_form.cleaned_data['password']
new_user = User.objects.create_user(username=username, email=email, password=password)
Student_profile = StudentProfile()
Student_profile.user = new_user
Student_profile.AMEB_Ratings = request.POST['AMEB_Ratings']
# Student_profile = StudentProfile.create_user(AMEB_Ratings=AMEB_Ratings)
new_user.save()
Student_profile.save()
# form.save()
# AMEB_Ratings = form.cleaned_data['AMEB_Ratings']
return redirect('/')
else:
# Create the django default user form and send it as a dictionary in args to the reg_form.html page.
user_form = UserForm()
form = StudentResistrationForm()
# args = {'form_student': form, 'user_form': user_form }
return render(request, 'accounts/reg_form_students.html', {'form_student': form, 'user_form': user_form })
Looks like you have a few typos you currently are setting your email variable to the email data then setting it to the password data. Correct this first.
email = user_form.cleaned_data['email']
password = user_form.cleaned_data['password']

AttributeError: 'auth.User' has been swapped for 'accounts.Accounts'? How?

So I have a Accounts model that extends AbstractUser model.
I Also have StudentProfile and TeacherApplications that have a
one to one relation with Accounts.
I ALSO have two forms for teacher and student to fill out.
Requirement: Enable students/teachers to register via their forms.
Issue: In the student/teacher form I am asking for fields that the User model needs such as email, username, first and last name etc.. However I am getting this:.
Error: 1
AttributeError at /register/ Manager isn't available; 'auth.User' has
been swapped for 'accounts.Accounts'
Error 2
Student_profile.save()
^ TabError: inconsistent use of tabs and spaces in indentation
ISSUE: I need to register the user with user fields otherwise User fields would be null and generate error as well.. But is the best approach? Or what am I doing wrong?
models
class Accounts(AbstractUser):
email = models.EmailField('email address', unique=True)
first_name = models.CharField('first name', max_length=30, blank=True)
last_name = models.CharField('last name', max_length=30, blank=True)
date_joined = models.DateTimeField('date joined', auto_now_add=True)
# asdd
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
class StudentProfile(models.Model):
user = models.OneToOneField('Accounts', related_name='student_profile')
# additional fields for students
AMEB_Ratings = models.PositiveIntegerField(default=0)
is_student = models.BooleanField('student status', default=False)
class TeacherApplications(models.Model):
user = models.OneToOneField('Accounts', related_name='teacher_profile')
# additional fields for teachers
instrument = models.TextField(max_length=500, blank=True)
skill = models.CharField(max_length=30, blank=True)
experience_in_years = models.PositiveIntegerField(blank=True)
is_teacher = models.BooleanField('teacher status', default=False)
forms
class StudentResistrationForm(forms.ModelForm):
class Meta:
model = StudentProfile
fields = (
# 'username',
'first_name',
'last_name',
'email',
'date_joined',
# 'password1',
# 'password2',
'AMEB_Ratings',
'is_student',
)
def save(self, commit=True):
user = super(StudentResistrationForm, self).save(commit=False)
# user.first_name = self.cleaned_data['first_name']
# user.last_name = self.cleaned_data['last_name']
user.AMEB_Ratings = self.cleaned_data['AMEB_Ratings']
if commit:
user.save()
return user
class TeacherRegistrationForm(forms.ModelForm):
class Meta:
model = TeacherApplications
fields = (
'instrument',
'skill',
'experience_in_years',
'is_teacher',
)
views
def registerStudent(request):
# Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
if request.method == "POST":
user_form = UserForm(request.POST)
form = StudentResistrationForm(request.POST)
if form.is_valid() and user_form.is_valid():
User = get_user_model()
username = user_form.cleaned_data['username']
email = user_form.cleaned_data['email']
email = user_form.cleaned_data['password']
new_user = User.objects.create_user(username=username, email=email, password=password)
Student_profile = StudentProfile()
Student_profile.user = new_user
Student_profile.AMEB_Ratings = request.POST['AMEB_Ratings']
# Student_profile = StudentProfile.create_user(AMEB_Ratings=AMEB_Ratings)
new_user.save()
Student_profile.save()
# form.save()
# AMEB_Ratings = form.cleaned_data['AMEB_Ratings']
return redirect('../home/')
else:
# Create the django default user form and send it as a dictionary in args to the reg_form.html page.
user_form = UserForm()
form = StudentResistrationForm()
args = {'form_student': form, 'user_form': user_form }
return render(request, 'accounts/reg_form_students.html', args)
def teacherApplication(request):
# # Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
# if request.method == "POST":
# form = TeacherRegistrationForm(request.POST)
# if form.is_valid():
# instrument = form.cleaned_data['instrument']
# skill = form.cleaned_data['skill']
# experience_in_years = form.cleaned_data['experience_in_years']
# is_teacher = form.cleaned_data['is_teacher']
# form.save()
# return redirect('../home/')
# else:
# # Create the django default user form and send it as a dictionary in args to the reg_form.html page.
# user_form = UserForm()
# form = StudentResistrationForm()
# return render(request, 'accounts/reg_form_teachers.html', {'form_student': form, 'user_form': user_form })
pass
I think you should change your model to something like this, I mean that Student and Teacher should inherit from account, so you dont need is_teacher and is_student anymore.
class StudentProfile(Accounts):
AMEB_Ratings = models.PositiveIntegerField(default=0)
class TeacherApplications(Accounts):
instrument = models.TextField(max_length=500, blank=True)
skill = models.CharField(max_length=30, blank=True)
experience_in_years = models.PositiveIntegerField(blank=True)
For your second error, I have to say the problem is indention and you should replace your tabs with 4 spaces.
Also I need your urls.py file to figure out it completely, I think problem might be there.
this link might be useful
Manager isn't available; User has been swapped for 'pet.Person'

Django - how to save my hashed password

I'm trying to save my hashed password in my database, but It keeps saving my plaintext password
Models:
class StudentRegistration(models.Model):
email = models.EmailField(max_length=50)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
password = models.CharField(max_length=100, default="", null=False)
prom_code = models.CharField(max_length=8, default="", null=False)
gender = (
("M","Male"),
("F","Female"),
)
gender = models.CharField(max_length=1, choices=gender, default="M", null=False)
prom_name = models.CharField(max_length=20, default="N/A")
prom_year = models.IntegerField(max_length=4, default=1900)
school = models.CharField(max_length=50, default="N/A")
def save(self):
try:
Myobj = Space.objects.get(prom_code = self.prom_code)
self.prom_name = Myobj.prom_name
self.prom_year = Myobj.prom_year
self.school = Myobj.school_name
super(StudentRegistration, self).save()
except Space.DoesNotExist:
print("Error")
Views:
def register_user(request):
args = {}
if request.method == 'POST':
form = MyRegistrationForm(request.POST) # create form object
if form.is_valid():
clearPassNoHash = form.cleaned_data['password']
form.password = make_password(clearPassNoHash, None, 'md5')
form.save()
form = MyRegistrationForm()
print ('se salvo')
else:
print ('Error en el form')
else:
form = MyRegistrationForm()
args['form'] = form #MyRegistrationForm()
return render(request, 'register/register.html', args)
I've printed the hashed result so I know it is hashing but not saving that.
Am I using the make_password wrong? or is there any better way to protect my passwords?
--------------------------UPDATE:(The Solution)----------------------------
Remember In settings.py:
#The Hasher you are using
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
Models.py:
#Import and add the AbstractBaseUser in your model
class StudentRegistration(AbstractBaseUser, models.Model):
Views.py:
if form.is_valid():
user = form.save(commit=False)
clearPassNoHash = form.cleaned_data['password']
varhash = make_password(clearPassNoHash, None, 'md5')
user.set_password(varhash)
user.save()
Use Django set_password in the documentation
https://docs.djangoproject.com/en/1.9/ref/contrib/auth/
You also need to get your model object from the form using form.save(commit=False)
if form.is_valid():
# get model object data from form here
user = form.save(commit=False)
# Cleaned(normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# Use set_password here
user.set_password(password)
user.save()
Save the object first, without committing to DB, then update password before a final save. Make sure your imports are all correct.
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST) # create form object
if form.is_valid():
new_object = form.save(commit=False)
new_object.password = make_password(form.cleaned_data['password'])
new_object.save()
messages.success(request, "Form saved.")
return redirect("somewhere")
else:
messages.error(request, "There was a problem with the form.")
else:
form = MyRegistrationForm()
return render(request, 'register/register.html', { 'form': form })

Categories