UserProfile Registration erases all rows - django

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)

Related

Django - user should have is_active = False but it is showing active in admin

My custom signup view has the user's is_active set to False. They use an emailed authorized token to set is_active to True. However, immediately after I sign up as a new user, I log into the admin page as a superuser and I can see that my new user has active checked off.
views
def signup(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
user.is_teacher = True
user.is_staff = True
user.is_active = False
to_email = form.cleaned_data.get('email')
user.username = to_email # make the username the same as the email
user.save()
group = Group.objects.get(name='teacher')
user.groups.add(group)
current_site = get_current_site(request)
# use sendgrid api for email
sendgrid_client = SendGridAPIClient(
api_key=os.environ.get('SENDGRID_API_KEY'))
from_email = From("me#email.com")
to_email = To(to_email)
subject = "Activate your SmartMark Account"
active_link = render_to_string('account/acc_active_email_link.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
html_text = f'Hello {user}<br/><p>Registration email</p>{active_link}'
html_content = HtmlContent(html_text)
mail = Mail(from_email, to_email, subject,
html_content)
response = sendgrid_client.send(message=mail)
return redirect(reverse('accounts:account_activation_sent'))
else:
form = CustomUserCreationForm()
return render(request, 'account/signup.html', {'form': form})
def account_activation_sent(request):
return render(request, 'account/account_activation_sent.html')
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = CustomUser.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
# calls check_token function but user is already set to active - email and token
# were never used.
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
return redirect('home')
else:
return render(request, 'account/account_activation_invalid.html')
CustomUser model
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
is_teacher = models.BooleanField('teacher status', default=False)
def __str__(self):
return self.username
Form
class CustomUserCreationForm(UserCreationForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
class Meta:
model = get_user_model()
fields = ('email', 'first_name', 'last_name')
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
def clean_email(self):
value = self.cleaned_data["email"]
if not value:
raise forms.ValidationError('An Email address is required.')
check_users = CustomUser.objects.filter(email__iexact=value)
if check_users:
raise forms.ValidationError('This email is already in use.')
return value
I am using Django's built in authentication. I am expecting the Active in the admin panel to be not checked off. I also tried moving the user.is_active=False to after the user.save() but this did not change the behaviour. I know from looking at my inital migrations file that the default for is_active is True but I would think that my signup view would override this
Edit
I thought I had fixed this by changing to user=form.save(commit=False) but it's happening again. New sign ups are automatically active.
First I changed my form save to:
user=form.save(commit=False)
However, it appears that the problem is that when I email the authorization token, the email recipient is checking the url for spam. By checking that the token url is a valid, the token is getting validated. I add a POST form such that the token is not checked until the user submits the form.

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

Pass Variable from View to Form 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 ....

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