PasswordResetForm doesn't send email - django

I'm working on a user system on an app. Everything works fine except one thing.
When I create a user, I generate a password to keep in database and send an email to the new created user to set his own password.
So the password is in the database and I use PasswordResetForm to send an email of password reseting.
Here is the code I use:
reset_password_form = PasswordResetForm(data={'email': user.email})
if reset_password_form.is_valid():
reset_password_form.save(request=request,
use_https=True,
from_email="Webmaster#mysite.com",
html_email_template_name='main/password_reset/password_reset_email.html',
subject_template_name="main/password_reset/password_reset_subject.txt")
And here is the problem, no email is sent.
So to clarify, I already use this Form in case we click on "I forgot my password" and it works very well. So There is no problems of settings for the email server.
As well the reset_password_form.is_valid() is true I can breakpoint in the if.
The user.email exists and contain a real and correct email adress.
I have the feeling that when I call save() on my form it doesn't send the message, did I do a mistake thinking it will do?
My complete view:
def adduser(request, id_user=None):
modify_user = User.objects.get(id=id_user) if id_user is not None else None
if request.method == 'POST':
if modify_user is not None:
userform = EditUserForm(request.POST, instance=modify_user)
else:
userform = AddUserForm(request.POST, instance=modify_user)
profileform = AddProfileForm(request.POST, request.FILES,
instance=modify_user.profile if modify_user is not None else None)
if userform.is_valid() and profileform.is_valid():
user = userform.save(commit=False)
profileuser = profileform.save(commit=False)
if modify_user is not None:
user.save(update_fields=['username', 'first_name', 'last_name', 'email'])
else:
reset_password_form = PasswordResetForm(data={'email': user.email})
if reset_password_form.is_valid():
reset_password_form.save(request=request,
use_https=True,
from_email="Webmaster#mantadivegiliair.com",
html_email_template_name='main/password_reset/password_reset_email.html',
subject_template_name="main/password_reset/password_reset_subject.txt")
user.set_password(User.objects.make_random_password(length=6))
user.save()
profileuser.created_by = request.user
profileuser.user = user
profileuser.save()
profileform.save_m2m()
if modify_user is not None:
messages.add_message(request, messages.SUCCESS,
"{} {} has been updated".format(user.first_name, user.last_name))
else:
messages.add_message(request, messages.SUCCESS,
"{} {} has been created".format(user.first_name, user.last_name))
return redirect('profile', user.id)
else:
for field in userform.errors:
if field == "__all__":
userform['confirm_password'].field.widget.attrs['class'] += ' error'
else:
userform[field].field.widget.attrs['class'] += ' error'
for field in profileform.errors:
profileform[field].field.widget.attrs['class'] += ' error'
else:
userform = AddUserForm(instance=modify_user)
profileform = AddProfileForm(instance=modify_user.profile if modify_user is not None else None)
return render(request, 'main/add_user.html', locals())

The user isn't saved yet when you save the PasswordResetForm. So the save() method won't do anything because it will try to fetch users in the database with the email submitted.
You just need to change the order in which you do things:
else: # user is new user
user.set_password(User.objects.make_random_password(length=6))
user.save()
reset_password_form = ...
reset_password_form.save(...)
profileuser.user = user
...

Related

Django Redirect returns 200, but page does not redirect

I have a django project where I am doing google oauth2. I click on a google signin button, I receive a post request from Googles api, and then I interpret that request and want to redirect the user to a page where they can create their own account.
Right now everything appears to work up until the redirect is suppose to happen. The terminal where my django project is running shows that it was successful (the print statements I wrote to confirm it reaches the render function work, and I see a 200 response also), but I remain on the login page.
I am wondering if the redirect and render are happening on another website session, or otherwise somewhere besides where the user is currently on the website?
Here is the code for my google webhook:
token = request.POST.get('idtoken')
print(token)
try:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), settings.GOOGLE_CLIENT_ID)
print(idinfo)
print('got past token')
google_user_id = idinfo['sub']
google_email = idinfo['email']
try: # authenticates user who already exists as a google signed in user.
user_from_sub = User.objects.get(google_sub_id=google_user_id)
user = user_from_sub.get_user_object()
if user.type == Types.BUSINESS:
backend = 'user_accounts.auth_backends.BusinessAuthBackend'
login(request, user, backend=backend) # TODO: add auth backend cred
elif user.type == Types.CONSUMER:
backend = 'user_accounts.auth_backends.ConsumerAuthBackend'
login(request, user, backend=backend) # TODO: add auth backend cred
else:
login(request, user)
print('logged in')
return redirect(reverse('home'))
except: # user doesn't yet exist, with specified sub id
idinfo['account_type'] = 'consumer'
print(request.GET)
print('creating account')
url = f'http://localhost:8000/oauth2/google/account-creation/?{urllib.parse.urlencode(idinfo)}'
return redirect(url)
except ValueError:
print("authentication failed due to an error")
Here is the code for my account creation view:
def create_google_oauth_user_view(request, *args, **kwargs):
""""""
print('hello')
print(request.GET)
print(request.body)
account_type = request.GET.get('account_type')
idinfo = request.GET
print(f'idinfo: {idinfo}')
if idinfo: # user data was passed
user = User.objects.filter(email=idinfo['email']).first()
if user:
user = user.get_user_object()
else: # no user_info was passed
return HttpResponse(status=400)
if account_type == 'business': # add to special business sign up page
if request.method == 'POST':
form = BusinessGoogleSignUpForm(request.POST, request.FILES, idinfo=idinfo)
if form.is_valid():
data = form.save()
messages.success(request, 'Account Creation Successful')
login(request, data, backend='user_accounts.auth_backends.BusinessAuthBackend')
return redirect(reverse('accounts:add_profile_picture', kwargs={'user_id': data.id}))
else:
form = BusinessGoogleSignUpForm(idinfo=idinfo)
elif account_type == 'consumer': # for regular consumer users
print('got to consumer')
if request.method == 'POST':
form = ConsumerGoogleSignUpForm(request.POST, request.FILES, idinfo=idinfo)
if form.is_valid():
data = form.save()
messages.success(request, 'Account Creation Successful')
login(request, data, backend='user_accounts.auth_backends.ConsumerAuthBackend')
return redirect(reverse('accounts:add_profile_picture', kwargs={'user_id': data.id}))
else:
form = ConsumerGoogleSignUpForm(idinfo=idinfo)
else: # no user type was specified
return HttpResponse(status=404)
print('got to context')
context = {
'user': user,
'form': form,
}
return render(request, 'oauth/google/account_creation.html', context)
As it stands the code always gets to the 'got to context' print statement and returns 200. Any advice or suggestions are welcome.
Have you tried adding an else statement for if the form isn't valid in post requests? If I'm reading it right then, if your form isn't valid, it will just continuously re-render with a pre-populated form with the data you submitted.

How to implement transaction rollback in database if there is insertion in more than one model consecutively?

I am creating a student user which will be linked to the built-in User model in Django. In my code, I create the user in the user model first then I create it in the StudentUser model. However, if ever an error occurs, maybe the StudentUser was not created, I want to undo the changes in user. How to go around this with rollback?
Here is my code snippet:
views.py
def user_signup(request):
if request.method == 'POST':
# Signup for student
if(request.POST['stud_fname']):
stud_fname = request.POST['stud_fname']
stud_lname = request.POST['stud_lname']
stud_uni = request.POST['stud_uni']
stud_email = request.POST['stud_email']
stud_password = request.POST['stud_passwd']
try:
user = User.objects.create_user(first_name=stud_fname, last_name=stud_lname,
username=stud_email, password=stud_password)
StudentUser.objects.create(user=user, university=stud_uni, user_type="Student")
messages.success(request, "Account successfully created. You can now log in")
return redirect('login')
except:
messages.error(request, "Failed to create account. Try again!")
return render(request, 'signup.html')
else:
return render(request, 'signup.html')
You can use transaction.atomic() for those db queries that you want to be either created all or none. I have written code snippet you can refer from here :-
from django.db import transaction
def user_signup(request):
if request.method == 'POST':
# Signup for student
if(request.POST['stud_fname']):
stud_fname = request.POST['stud_fname']
stud_lname = request.POST['stud_lname']
stud_uni = request.POST['stud_uni']
stud_email = request.POST['stud_email']
stud_password = request.POST['stud_passwd']
try:
with transaction.atomic():
user = User.objects.create_user(first_name=stud_fname, last_name=stud_lname, username=stud_email, password=stud_password)
StudentUser.objects.create(user=user, university=stud_uni, user_type="Student")
messages.success(request, "Account successfully created. You can now log in")
return redirect('login')
except:
messages.error(request, "Failed to create account. Try again!")
return render(request, 'signup.html')
else:
return render(request, 'signup.html')

Django: send emails to users

I have a list of users with their email adress (only for Staff members), I am trying to send a form to the user.
When I use i.email, I get this error: "to" argument must be a list or tuple
When I use ['i.email'] I don't receive the message.
urls.py
path('users/<int:id>/contact', views.contactUser, name='contact_user'),
views.py
def contactUser(request, id):
i = User.objects.get(id=id)
if request.method == 'POST':
form = ContactUserForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
send_mail('Website administration', message, ['website#gmail.com'], ['i.email'])
return redirect('accounts:users')
else:
form = ContactUserForm()
return render(request, 'accounts/contact_user.html', {'form': form, 'username': i})
I am using SendGrid. I have a 'contact us' form which is similar to contactUser and it works fine.
['i.email'] should be [i.email]

AttributeError: 'AcceptInvite' object has no attribute 'email'

Im doing some unit testing in my Django project, and am getting error
"AttributeError: 'SignUp' object has no attribute 'email'"
when I run this test.
def test_signup(self):
response = self.c.post('/accounts/signup/', {'email': 'test#test.com', 'password': 'test123', 'password_conf': 'test123',
'org_name': 'test org', 'org_username': 'test org username', 'invite': '4013'})
code = response.status_code
self.assertTrue(code == 200)
The view this is testing simply takes a signup form, and creates a new account with it.
def signup(request):
# """Register a new account with a new org."""
if request.method == "POST":
form = SignUp(request.POST)
if not form.email or not form.password:
raise Exception("Email and Password are required")
if form.password != form.password_conf:
raise Exception("Password does not match confirmation")
if not form.org_name or not form.org_username:
raise Exception('Organization name and username are required')
if not form.invite:
raise Exception('Invitation code is required')
if form.is_valid():
cleaned_data = form.cleaned_data
email = cleaned_data['email']
password = cleaned_data['password']
org_name = cleaned_data['org_name']
org_username = cleaned_data['org_username']
invite_token = cleaned_data['invite']
invitation = OrgInvite.objects.get(token=invite_token)
if invitation.used:
raise Exception("invitation code is invalid")
account = Account(email=email, password=password)
account.save()
org = Org(org_name=org_name, org_username=org_username)
org.save()
invitation.used = False
invitation.save()
login(request)
# Send Email
md = mandrill.Mandrill(settings.MANDRILL_API_KEY)
t = invite_token.replace(' ', '+')
url = "https://www.humanlink.co/verify/{}".format(t)
message = {
'global_merge_vars': [
{'name': 'VERIFICATION_URL', 'content': url},
],
'to': [
{'email': account.email},
],
}
message['from_name'] = message.get('from_name', 'Humanlink')
message['from_email'] = message.get('from_email', 'support#humanlink.co')
try:
md.messages.send_template(
template_name='humanlink-welcome', message=message,
template_content=[], async=True)
except mandrill.Error as e:
logging.exception(e)
raise Exception('Unknown service exception')
The Signup form has an email field, and the data in request.POST should have the email I am sending it with my Client's post method being used in my unit test, so I am really not sure why it still wouldn't have an 'email' attribute.
Form:
class SignUp(forms.Form):
email = forms.EmailField()
password = forms.CharField()
password_conf = forms.CharField()
org_name = forms.CharField()
org_username = forms.CharField()
invite = forms.CharField()
You code suffers from multiple errors. To address your question, in your view method signup you were creating a form, but you shouldn't do form.email or form.password because that's not how django handles form data.
Other related issues, first, you need to call form.is_valid() before you could get any data from form object. Even so, you should use form.cleaned_data['email'] to access the form data.
Secondly. You shouldn't do empty check like that. If you put:
email = forms.EmailField(required=True)
django will automatically verify the emptiness for you already.
Thirdly, raising Exception in views.py method doesn't get your form to return the message to the template you want. If you have custom form validation, you should do it in form class's clean method.
Please check django doc about how to use form properly.

How to use Many-to-many relationships

I am using Many-to-many relationships in my app and I am not able to feed data into the table which is by default created by the Django to ensure the Many-to-many relationships.It gives the error in method (def Set_Checkout_Attributes(request):) that 'Customer_check_attributes' object has no attribute 'set_customers' If I replace set_customers with set_users the error will remain same.
The models which I used are:
class Customer(models.Model):
user =models.OneToOneField(User)
birthday =models.DateField()
class Customer_check_attributes(models.Model):
users =models.ManyToManyField(User)
billing_add =models.CharField(max_length=100, blank=True , null=
My view.py is as
def CustomerRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = Registration_Form(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.first_name = form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name']
user.save()
customer=Customer(user=user, website=form.cleaned_data['website'], birthday=form.cleaned_data['birthday'], store=form.cleaned_data['store'], welcomemail=form.cleaned_data['welcomemail'])
customer.save()
return HttpResponseRedirect('/profile/')
else:
check_form=Check_Attribute_Form()
context={'form':form, 'check':check_form}
return render_to_response('customer/customer_register.html',context , context_instance=RequestContext(request))
else:
''' user is not submitting the form, show them a blank registration form '''
form = Registration_Form()
check_form = Check_Attribute_Form()
context={'form':form,'check':check_form}
return render_to_response('customer/customer_register.html',context , context_instance=RequestContext(request))
####################################### checkout attributes ##################################################
def Checkout_Attributes(request):
check_form = Check_Attribute_Form()
context={'form':check_form}
return render_to_response('customer/checkout.html',context,context_instance=RequestContext(request))
def Set_Checkout_Attributes(request):
#if request.user.is_authenticated():
#return HttpResponseRedirect('/checkout/')
if request.method == 'POST':
check_form = Check_Attribute_Form(request.POST)
#if check_form.is_valid():
customer_check=Customer_check_attributes(billing_add=check_form.data['billing_add'],shipping_add=check_form.data['shipping_add'],payment_method=check_form.data['payment_method'],shipping_method=check_form.data['shipping_method'],reward_points=check_form.data['reward_points'])
customer_check.save()
customer_check.set_customers([user.id])
return HttpResponseRedirect('/profile/')
#else:
#check_form=Check_Attribute_Form()
#return render_to_response('a.html',{'check_form':check_form} , context_instance=RequestContext(request))
else:
return render_to_response('f')
I am got struck here for two days but I can't solve it Please help me.
Thanks
You can use like this:
customer_check.users.add(your user instance)
I think you are trying to use
user.customer_check_set.
but you just use wrongly.
if class x has M2M field y you can reach y directly from x instance like this
x.y
and you can reach x from y like this:
y.x_set
Have fun with django