How to create user base on data from form? - django

forms.py
'''
class AddUserForm(forms.Form):
username = forms.CharField(label='Login', min_length=1)
password = forms.CharField(label='Password', widget=forms.PasswordInput)
repeat_password = forms.CharField(label='Repeat password', widget=forms.PasswordInput)
name = forms.CharField(label="First name", min_length=1, validators=[check_first_upper_letter_validator])
surname = forms.CharField(label="Last name",validators=[check_first_upper_letter_validator])
email = forms.CharField(validators=[EmailValidator()])
'''
views.py
'''
class AddUserView(View):
def get(self, request):
form = AddUserForm()
return render(request, 'exercises/form.html', {'form': form}) def post(self, request):
form = AddUserForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=...., email=....., password=....)
user.save()
return HttpResponse("OK")
else:
return render(request, 'exercises/form.html', {'form': form})
'''
How to get data from form for username, email etc.?

After django validates a form (which happens when you call form.is_valid()) a dictionary is added to your form called cleaned_data which allows you to access your form data.
So, after form.is_valid() in your view you can access the name entered by form.cleaned_data['name'], the email by form.cleaned_data['email'] and so on.

Related

django form is not valid but validation not working

When I submit form it doesn't show any validation error and form is not valid
views.py
def institute(request):
context = {}
if request.POST and request.FILES:
form = InstituteForm(request.POST, request.FILES)
context['form'] = form
if form.is_valid():
form.save()
messages.add_message(
request, messages.SUCCESS, "Successfully Added Institute Information")
return redirect('accounts:profile')
else:
context['form'] = InstituteForm()
return render(request, 'institute.html',context)
according to forms.py it should return email or phone validation error but there is no errors in template
and form data is saving in database
forms.py
class InstituteForm(forms.ModelForm):
class Meta:
model = Institute
fields = '__all__'
exclude = ('create', 'update', 'admin')
def clean_phone(self):
phone = self.cleaned_data['phone']
emp = Employee.objects.filter(phone=phone).count()
ins = Institute.objects.filter(phone=phone).count()
if emp > 0 or ins:
raise ValidationError('This Phone Number is already used, try new one')
return phone
def clean_email(self):
email = self.cleaned_data.get('email')
emp = Employee.objects.filter(email=email).count()
ins = Institute.objects.filter(email=email).count()
if ins > 0 or emp:
raise ValidationError('This email is already used, try new one')
return email

The set_password() method isn't encrypting the password in a custom Django user model

I am saving these details in a custom user model stored in MySQL, but the password is not getting encrypted; it is being saved in plain text.
def regauth(request):
if request.method == "POST":
form = UserAuth(data=request.POST)
# user_form = UserAuth(data=request.POST)
if form.is_valid():
try:
messages.info(request, 'inside try')
user = form.save()
user.set_password(form.password)
user.save()
return redirect('login_url')
except:
messages.info(request, 'inside exception')
return render(request, 'registration/registration.html', {'form': form})
else:
user_form = UserAuth()
return render(request, 'registration/registration.html', {'form': user_form})
Forms.py
class UserAuth(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = RegAuth
fields = "__all__"
How can I make sure the set_password() method gets called properly to encrypt the password?
Try this:
Saving with commit=False gets you a model object, then you can add your extra data and save it.
...
if form.is_valid():
user = form.save(commit=False) # <---
user.set_password(form.cleaned_data.get('password')) # <---
user.save()
...

RelatedObjectDoesNotExist Error

Here is the model. I have created my own user model
class Profile(models.Model):
user = models.OneToOneField(User)
favorite_food = models.CharField(max_length=100)
def set_password(self, raw_password):
self.user.set_password(raw_password)
Here is the view:
class UserFormView(View):
form_class = UserForm
template_name = 'templates/core/profile_form.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
return render(request, self.template_name, {'form': form})
Here is UserForm
class UserForm(forms.ModelForm):
username = forms.CharField(max_length=10)
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Profile
fields = ['username', 'password', 'favorite_food']
Where seems to be the problem here? It also says that Profile has no user I have tried changing it to AbstractUser however, it also displays about an error about reverse accessor
Try to exclude user from form and add save method to the form:
class ProfileForm(forms.ModelForm):
username = forms.CharField(max_length=10)
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Profile
fields = ['username', 'password', 'favorite_food']
exclude = ['user']
def save(self, user = None, force_insert=False, force_update=False, commit=False):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
profile = super(ProfileForm, self).save(commit=commit)
if user:
profile.user = user
profile.set_password(password)
profile.save()
return profile
In you view:
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
profile = form.save(user = request.user, commit=False)

Username and password authentication in django

I need to validate username and password in django app, below are the details
view is,
class HomeView(TemplateView):
template_name = 'home.html'
template_name2 = 'Logout.html'
def get(self,request):
form = LoginForm()
posts=users_data.objects.all()
args = {'form': form, 'posts': posts}
return render(request, self.template_name, args)
return render(request,self.template_name, {'form':form})
#template_name2 = 'Welcome.html'
def post(self,request):
form = LoginForm(request.POST)
if form.is_valid():
#text=form.cleaned_data['post']
username = forms.cleaned_data.get("Username")
password = forms.cleaned_data.get("Password")
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("This user does not exist")
return render(request, self.template_name1)
else:
form.save()
return render(request, self.template_name2)
else:
return render(request, self.template_name1)
after entering username and password it is giving me error and doing nothing. I am stuck at this point . Requesting for help.
my form is,
from django import forms
from login.models import *
from django.contrib.auth import authenticate,login,logout,get_user_model
user=get_user_model()
class SignupForm(forms.ModelForm):
class Meta:
model=users_data
fields=('Name','Email','Username','Password')
class LoginForm(forms.ModelForm):
class Meta:
model=users_data
fields=('Username','Password')
def clean(self):
username = self.cleaned_data.get("Username")
password = self.cleaned_data.get("Password")
user=authenticate(username=username,password=password)
if not user:
raise forms.ValidationError("This user does not exist")
You can use get user input from LoginForm this code blog.
username = form.cleaned_data.get("Username")
password = form.cleaned_data.get("Password")

Django KeyError at /register/

I have a registration that let users register and i'm having difficulty fixing it.
The problem is when a user submits a single field instead of the whole form for example an email . I get this error
KeyError at /register/
password
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
File "C:\Python26\Lib\site-packages\django\forms\forms.py" in _get_errors
115. self.full_clean()
File "C:\Python26\Lib\site-packages\django\forms\forms.py" in full_clean
271. self._clean_form()
File "C:\Python26\Lib\site-packages\django\forms\forms.py" in _clean_form
299. self.cleaned_data = self.clean()
File "C:\o\17\mysite\pet\forms.py" in clean
31. if self.cleaned_data['password'] != self.cleaned_data['password1']:
Exception Type: KeyError at /register/
Exception Value: password
I tried to fix this solution using if . If user has a submitted a username or any other required field , process the form otherwise redisplay the original form.
but I still get the same error.
This is my edited views.py (at the bottom of the page is my original RegistrationForm)
def PetRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:HappyLand'))
if request.method =='POST':
form = UserRegistration(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
if username:
email=form.cleaned_data['email']
if email:
password=form.cleaned_data['password']
if password:
user = User.objects.create_user(
username=form.cleaned_data['username'],
email=form.cleaned_data['email'],
password=form.cleaned_data['password']
)
user.is_active = True
user.first_name = form.cleaned_data['name']
user.save()
person = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password']
)
Person.objects.create(user_id=user.id,
name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])
login(request, person)
return HttpResponseRedirect(reverse('world:HappyLand'))
return render(request, 'register.html', {'form': UserRegistration()})
How can I fix this error and also how could I display an error message on the other fields that the user didn't fill out like "Error Missing Field , Please Fill this Field".
def PetRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:HappyLand'))
if request.method =='POST':
form = UserRegistration(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.is_active = True
user.first_name = form.cleaned_data['name']
user.save()
person = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password']
)
Person.objects.create(user_id=user.id,
name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])
login(request, person)
return HttpResponseRedirect(reverse('world:HappyLand'))
return render(request, 'register.html', {'form': UserRegistration()})
My forms.py
class UserRegistration(forms.Form):
username = forms.CharField()
name = forms.CharField()
email = forms.EmailField()
birthday = forms.DateField(widget=extras.SelectDateWidget(years=range(1950, 2012)))
password = forms.CharField(
widget=forms.PasswordInput(render_value=False)
)
password1 = forms.CharField(
label=(u'Verify Password'),
widget = forms.PasswordInput(render_value=False)
)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(
"That user is already taken , please select another ")
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['password1']:
raise forms.ValidationError("The password does not match ")
return self.cleaned_data
My models.py
class Person(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100, blank=True)
birthday = models.DateField(blank=True,null=True)
def __unicode__(self):
return self.name
Problem is with your clean(). In clean(), you are trying to access field password on form's cleaned_data. password will only be available on cleaned_data if the user has filled this field. So, you must check that password is there in cleaned_data before trying to access it.
Changing your clean():
def clean(self):
if 'password' in self.cleaned_data and 'password1' in self.cleaned_data and self.cleaned_data['password'] != self.cleaned_data['password1']:
raise forms.ValidationError("The password does not match ")
return self.cleaned_data
You can provide a keyword argument error_messages on form field for showing error message like "Error Missing Field , Please Fill this Field".
class SomeForm(forms.Form):
name = forms.CharField(error_messages={'required':'Error Missing Field , Please Fill this Field'})
There is a bug in your view.
is_valid() populates errors on the form but this same form instance must be sent to the template so that you can access the errors on the form's fields.
But in your view, you have only one call to render() which gets called even in case of an invalid form on a post request. And in this render(), you are creating a new instance of form. So, this new form which you are sending to template will not have any errors.
So, making slight modification to your view:
def PetRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:HappyLand'))
form = UserRegistration() #This will be used in GET request
if request.method =='POST':
form = UserRegistration(request.POST) #This will be used in POST request
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.is_active = True
user.first_name = form.cleaned_data['name']
user.save()
person = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password']
)
Person.objects.create(user_id=user.id,
name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])
login(request, person)
return HttpResponseRedirect(reverse('world:HappyLand'))
return render(request, 'register.html', {'form': form})
Notice in your view, I have added form=UserRegistration() before checking if its POST request, and have added the comment at two places where we are instantiating UserRegistration. And then in render(), you should send this form.
Then your {{form.username.errors}} will work.
I just modified your forms.py
class UserRegistration(forms.Form):
username = forms.CharField()
name = forms.CharField()
email = forms.EmailField()
birthday = forms.DateField(widget=extras.SelectDateWidget(years=range(1950, 2012)))
password = forms.CharField(
widget=forms.PasswordInput(render_value=False)
)
password1 = forms.CharField(
label=(u'Verify Password'),
widget = forms.PasswordInput(render_value=False)
)
def clean(self):
cleaned_data = super(UserRegistration, self).clean()
username = cleaned_data.get("username")
password = cleaned_data.get("password")
password1 = cleaned_data.get("password1")
#check if username exist
user = User.objects.filter(username=username)
if user:
raise forms.ValidationError(
"That user is already taken , please select another ")
#check password
if password != password1:
raise forms.ValidationError(
"Your current and confirm password do not match.")
return cleaned_data