new username is created instead of getting updated - python

I am trying to create a list of employee. I can assign username, password and email to that employee and also can update employee information where I should able to update username, password or email either. I could create an employee and also create the username and password along with update employee info but when changing the username or password or email of the employee a new user is created.
Here is what I have tried
class EmployeeForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = models.Employee
fields = ('name', 'designation', 'section', 'phone_number', 'mobile_number',
'email', 'gender', 'role', 'username', 'password', 'avatar',)
def employee(request):
form = EmployeeForm(request.POST or None)
if request.method == "POST" and form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
office_instance = OfficeSetup.objects.get(owner=request.user)
form = form.save(commit=False)
form.office = office_instance
user = User.objects.create_user(
username=username, password=password, email=email)
user.save()
form.save()
messages.success(request, 'Thank you')
return redirect('employee-list')
messages.warning(request, 'Error')
context = {
'form': form
}
return render(request, 'dashboard/hrm/employee.html', context)
Edit part
def edit_employee(request, id):
instance = get_object_or_404(Employee, id=id)
form = EmployeeForm(request.POST or None, instance=instance)
if request.method == "POST" and form.is_valid():
employee = Employee.objects.get(id=id)
prev_username = employee.username
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
office_instance = OfficeSetup.objects.get(owner=request.user)
form = form.save(commit=False)
form.office = office_instance
# change username or password or email if admin has done the changes in
# those field
try:
user_instance = User.objects.get(username=prev_username)
user_instance.username = username
user_instance.set_password(password)
user_instance.email = email
form.save()
user_instance.save()
except User.DoesNotExist:
messages.error(request, "Following User Does Not Exist!")
except:
user = User.objects.create_user(
username=username, password=password, email=email)
form.save()
user.save()
messages.success(request, "Thank you")
return redirect('employee-list')
messages.warning(request, "Error")
context = {
'form': form
}
return render(request, 'dashboard/hrm/employee.html', context)
Screenshot is to make the flow or use-case clear
UPDATED CODE
def edit_employee(request, id):
instance = get_object_or_404(Employee, id=id)
form = EmployeeForm(request.POST or None, instance=instance)
if request.method == "POST" and form.is_valid():
employee = Employee.objects.get(id=id)
prev_username = employee.username
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
office_instance = OfficeSetup.objects.get(owner=request.user)
form = form.save(commit=False)
form.office = office_instance
# change username or password or email if admin has done the changes in
# those field
user, created = User.objects.get_or_create(username=prev_username)
if created:
user.set_password(password)
user.email = email
form.save()
user.save()
return redirect('employee-list')
user.set_password(password)
user.email = email
form.save()
user.save()
return redirect('employee-list')
messages.warning(request, "Error")
context = {
'form': form
}
return render(request, 'dashboard/hrm/employee.html', context)

The get_or_create method is made for cases like this. I'd refactor to do something like this:
user, created = User.objects.get_or_create(username=username)
if created:
# Fields to only populated on creation
user.password = password
...etc...
# Fields to update on creation or update
user.email = email
...etc...
user.save()
Details here: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#get-or-create
Good luck!

Related

User creation - email field and image field not updating Postgres

In an extended user model with User and Profile created together. The user and related profile(Customer) is created but two fields 'email'(user email) field and 'photo'(image field) is not saved into database. Appreciate some fix:
views.py
def customer_register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
profile_form = CustomerProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
# Create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
# Set the chosen password
new_user.set_password(
user_form.cleaned_data['password'])
# Save the User object
new_user.save()
# Create the customer profile
customer = profile_form.save(commit=False)
customer.user = new_user
customer.save()
#Customer.objects.create(user=new_user,date_of_birth=customer.date_of_birth, photo=customer.photo, pincode=customer.pincode)
return render(request,
'registration/register_done.html',
{'new_user': new_user})
else:
messages.error(request, 'Error in creating your profile')
else:
user_form = UserRegistrationForm()
profile_form = CustomerProfileForm()
Forms.py
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label='Password',
widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat password',
widget=forms.PasswordInput)
email = forms.EmailField(label='email', widget=forms.EmailInput, required=True)
class Meta:
model = User
fields = ['username', 'first_name', 'email']
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email exists. Please change email")
class CustomerProfileForm(forms.ModelForm):
pincode = INZipCodeField(label="PIN")
date_of_birth = forms.DateField(widget=forms.DateInput(format='%d/%m/%Y'), input_formats=('%d/%m/%Y',))
photo = forms.ImageField()
class Meta:
model = Customer
fields = ['pincode','date_of_birth','photo']
I figured out the email id issue was in the form, form had to return the email in the email validation function
clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email exists. Please change email")
return email
In the views I had to add request for files(image) along with form:
profile_form = CustomerProfileForm(request.POST, request.FILES or None)
The image issue was in the registration html template. I updated the form to enctype "multipart/form-data" to take get image inputs
<form method="post" enctype="multipart/form-data" action="{% url 'customer_register' %}">
{% csrf_token %}

Can we edit the user profile without using forms.py in django?

How to create view for the registered user to edit there profile in the user dashboard using django ? Please provide the view .
I have created the register profile without using the forms.py , Now I want to create the userprofile edit only without using forms.py. And Is it possible to submit the data again to the
database.
(Dont use forms.py)
Accounts/views.py
def register(request):
if request.method == 'POST':
#get form values
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password2 = request.POST['password2']
#Check if passwords match
if password == password2:
#check username
if User.objects.filter(username = username).exists():
messages.error(request,'That username is taken')
return redirect('register')
else:
if User.objects.filter(email=email).exists():
messages.error(request,'That email is being used')
return redirect('register')
else:
#looks good
user = User.objects.create_user(username = username, password = password, email = email, first_name = first_name, last_name = last_name)
#login after register
# auth.login(request, user)
# messages.success(request, 'You are now logged in')
# return redirect('index')
user.save()
messages.success(request, 'You are now registered and can log in')
return redirect('login')
else:
messages.error(request,'passwords do not match')
return redirect('register')
else:
return render(request, 'accounts/register.html')
I don't think there is a possible way to edit profile and change a password in the same view without use forms.py, but the django.contrib.auth.forms has a PasswordChangeForm and a UserChangeForm which you can use.
Se more in documentation: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/
In your views.py
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
def edit_profile(request):
if request.method == "POST":
form = UserChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
messages.info(request, "Ok")
return redirect("main:homepage")
else:
messages.error(request, "Error")
return redirect("main:edit_profile")
else:
form = UserChangeForm(instance=request.user)
return render(request, "main/edit-profile.html", {'form': form})
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
messages.info(request, "ok")
update_session_auth_hash(request, form.user)
return redirect("main:edit_profile")
else:
messages.error(request, "error")
return redirect("main:change_password")
else:
form = PasswordChangeForm(user=request.user)
return render(request, "main/change-password.html", {'form': form})

How to make Required: boolean field in model Django

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()

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 })

Profile() got an unexpected keyword argument 'name'

Edit : I am unable to load a image, but here is a link : https://plus.google.com/113782760013016224132/posts/3kcamT13yNP
Using Django. This is my first question.
I keep getting the error: Profile() got an unexpected keyword argument 'name'. I dont really understand why I am getting this error. It was working yesterday and now its all weird. Help would be much appreciated.
My forms.py is:
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))
verifyPass = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = Profile
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 username.")
def clean(self):
password = self.cleaned_data.get('password', None)
verifyPass = self.cleaned_data.get('verifyPass', None)
if password != verifyPass:
#self.cleaned_data['password'] != self.cleaned_data['verifyPass']:
raise forms.ValidationError("Please try again, the passwords did not match.")
return self.cleaned_data
views.py:
def UserRegistration(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()
users = Profile(user=user, name=form.cleaned_data['name'], date_of_birth=form.cleaned_data['date_of_birth'])
users.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))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = LoginUserForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
users = authenticate(username = username, password = password)
if users is not None:
login(request, users)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html', {'form' : form}, context_instance = RequestContext(request))
else:
return render_to_response('login.html', {'form' : form}, context_instance = RequestContext(request))
else:
''' user is not submitting the form, show the login form '''
form = LoginUserForm()
context = {'form': form}
return render_to_response('login.html', context, context_instance=RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/')
def Profile(request):
render_to_response('profile.html')
def home(request):
return render_to_response("home.html")
class LoginUserForm(forms.Form):
username = forms.CharField(label=(u'User Name'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
models.py:
class Profile(models.Model):
user = models.OneToOneField(User)
date_of_birth = models.DateField()
name = models.CharField(max_length=100)
def __str__(self):
return self.name

Categories