Pass Variable from View to Form Django - django

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 ....

Related

Django Form not saving for Custom User Model

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

Unicode issue updating User model with a custom Form

Tryng to update User model and UserProfile model I diceded to generate a form with User and UserProfile models attributes, to update both with the same form. But when i subbmit the form to the view, the Users model is updating with no unicode render, example: (u'username'
), (u'name'). I dont understand why this happening, i check the utf-8 tag in both files.
forms.py
# -*- encoding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
class UserProfileForm(forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(UserProfileForm, self).__init__(*args, **kwargs)
username = forms.CharField(required=True,
widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))
name = forms.CharField(required=True,
widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))
lastname = forms.CharField(required=True,
widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))
email = forms.CharField(required=True,
widget = forms.EmailInput(attrs={'class':'input', 'autocomplete':'off'}))
change_password = forms.BooleanField(required=False,widget = forms.CheckboxInput())
password1 = forms.CharField(required=False, min_length = 8,
widget = forms.PasswordInput(render_value=False, attrs={'class':'input hidden'}))
password2 = forms.CharField(required=False, min_length = 8,
widget = forms.PasswordInput(render_value=False, attrs={'class':'input hidden'}))
institution = forms.CharField(required=False,
widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))
logo = forms.ImageField(required=False)
def clean_username(self):
username = self.cleaned_data.get('username').lower()
print username
try:
u = User.objects.exclude(pk=self.request.user.id).get(username__iexact=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(u'Este nombre de usuario ya existe.')
def clean_email(self):
email = self.cleaned_data.get('email')
try:
e = User.objects.exclude(pk=self.request.user.id).get(email__iexact=email)
except User.DoesNotExist:
return email
raise forms.ValidationError(u'ya existe un usuario asociado a este correo electrónico.')
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if not(password1 and password2):
pass
elif not password2:
raise forms.ValidationError("Debes confirmar la contraseña")
if password1 != password2:
raise forms.ValidationError("Las contraseñas no coinciden")
return password2
currently the view is only updating User model:
class UpdateProfile(FormView):
model = User
template_name = 'general/perfil.html'
form_class = UserProfileForm
def get_initial(self):
initial = super(UpdateProfile, self).get_initial()
initial['username'] = self.request.user.username
initial['name'] = self.request.user.first_name
initial['lastname'] = self.request.user.last_name
initial['email'] = self.request.user.email
try:
profile = UserProfile.objects.get(user=self.request.user)
except UserProfile.DoesNotExist:
profile = None
if profile:
initial['institution'] = profile.institution
return initial
def get_form_kwargs(self):
kwargs = super(UpdateProfile, self).get_form_kwargs()
kwargs.update({'request' : self.request})
return kwargs
def form_valid(self, form):
user = get_object_or_404(User, pk= self.request.user.id)
user.username = form.cleaned_data['username'],
user.first_name = form.cleaned_data['name'],
user.last_name = form.cleaned_data['lastname'],
user.email = form.cleaned_data['email']
if form.cleaned_data['change_password']:
user.password = form.cleaned_data['password1']
user.save()
return HttpResponseRedirect('/profile')
could be a problem with form.cleaned_data method?
Any ideas?
Look veeery closely at the following lines:
user.username = form.cleaned_data['username'],
user.first_name = form.cleaned_data['name'],
user.last_name = form.cleaned_data['lastname'],
Do you see it?
Yes, it's that comma at the end. It's creating a tuple. Stop doing that.

check_password always returning false even if the password is correct?

I am using Django 1.5. I am a custom User model like this:
class User(AbstractBaseUser):
#id = models.IntegerField(primary_key=True)
#identifier = models.CharField(max_length=40, unique=True, db_index=True)
username = models.CharField(max_length=90, unique=True, db_index=True)
create_time = models.DateTimeField(null=True, blank=True)
update_time = models.DateTimeField(null=True, blank=True)
email = models.CharField(max_length=225)
#password = models.CharField(max_length=120)
external = models.IntegerField(null=True, blank=True)
deleted = models.IntegerField(null=True, blank=True)
purged = models.IntegerField(null=True, blank=True)
form_values_id = models.IntegerField(null=True, blank=True)
disk_usage = models.DecimalField(null=True, max_digits=16, decimal_places=0, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
class Meta:
db_table = u'galaxy_user'
I have a custom authentication:
class AuthBackend:
def authenticate(self, username=None, password=None):
if '#' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = User.objects.get(**kwargs)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Even after entering the correct username and password check_password() always returning false so that I can't login. I tried that in terminal too:
user.check_password(password)
is always returning False.
#views.py:
def login_backend(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
state = "Username or Password Incorrect!"
if user is not None:
login(request, user)
return HttpResponseRedirect('/overview/')
else:
return render_to_response('login_backend.html', {'state':state}, context_instance=RequestContext(request))
else:
return render_to_response('login_backend.html', context_instance=RequestContext(request))
The problem is that when you create your CustomUser, you save the password in open-way(without hashing). Can you give me your RegistrationForm code?
In my case:
# forms/register.py
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
class Meta:
model = CustomUser
fields = ['username', 'password', 'email']
Register-handler:
# views.py
def register(request):
"""
User registration view.
"""
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
if form.is_valid():
user = form.save() # Save your password as a simple String
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'news/register.html', {'form': form})
So when you try to login:
if user.check_password(password):
return user
check_password always returns False.
Solution:
To set password properly, you should redefine save() method in RegistrationForm:
# forms/register.py
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
class Meta:
model = CustomUser
fields = ['username', 'password', 'email']
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(user.password) # set password properly before commit
if commit:
user.save()
return user
Or simply change handler:
def register(request):
"""
User registration view.
"""
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(request.POST["password"])
user.save()
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'news/register.html', {'form': form})

where to create group and pass the permission in django

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

UserProfile Registration erases all rows

I have created a user registration view and this is it:
def register(request):
if request.method == 'POST':
data = request.POST.copy() # so we can manipulate data
# random username
data['username'] = hashlib.md5( data['email'] ).hexdigest()
data['username'] = data['username'][0:30]
#data['username'] = ''.join([choice(letters) for i in xrange(30)])
form = RegisterForm(data)
if form.is_valid():
new_user = form.save()
#UserProfile.objects.create(user=new_user)
return HttpResponse("Thanks for Registering")
else:
form = RegisterForm()
return render_to_response("CTUser/register.html", { 'form': form, })
When I uncommented the UserProfile line:
#UserProfile.objects.create(user=new_user)
the email and password are saved correctly, but when It is there, all the info is erased. Am I doing something wrong here?
here is the UserProfile classs:
class UserProfile(User):
user = models.OneToOneField(User)
#user = models.ForeignKey(User, unique=True)
#profile sub URL
pagelink = models.CharField(max_length=40)
#one or many albums
albums = models.ManyToManyField(Album)
UPDATE(10/19/11):
Here is the registration form function:
class RegisterForm(UserCreationForm):
email = forms.EmailField(label = "Email Address", max_length=75)
class Meta:
model = User
#exclude = ['username',]
fields = ("username", "email")
def clean_email(self):
email = self.cleaned_data["email"]
try:
user = User.objects.get(email=email)
raise forms.ValidationError("This email address already exists. Did you forget your password?")
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
Check if new_user contains all data you want to save. Paste RegisterForm code.
EDIT
try to change:
user = super(UserCreationForm, self).save(commit=False)
into
user = super(RegisterForm, self).save(commit=False)