我需要在创建新用户时使用django中的post_save函数发送电子邮件。身份验证和创建在后端本身的views.py中完成, 我如何整合到代码中如下 -
def signup(request):
if request.method == 'POST':
try:
username = request.POST.get('username')
firstname = request.POST.get('first_name')
password = request.POST.get('password')
lastname = request.POST.get('last_name', '')
email = request.POST.get('email')
contact_num = request.POST.get('mobile_number', '')
try:
user = Customer(username=username, first_name=firstname,
last_name=lastname, email=email, mobile_number=contact_num,
is_staff=False, is_superuser=False,
is_active=True, last_login=now.date(), )
user.set_password(password)
user.save()
user = auth.authenticate(username=username, password=password)
try:
context = {"customer_name": firstname}
html = render_to_string('email_templates/welcome.html', context)
tasks.send_welcome_email(email, html)
except Exception as e:
logger.error("Error while sending Welcome email on signup {}".format(e.message))
except Exception as e:
logger.error("Constraint violation new user Signup", e.message)
c = {}
c.update(csrf(request))
return render(request, 'login.html',
{'user': False, 'c': c, 'Error': 'Username or Email exist already,Try again'})
if user is not None and user.is_active:
auth.login(request, user)
if request.user.is_authenticated():
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/accounts/login/')
else:
return HttpResponseRedirect('/404/')
except Exception as e:
logger.error("Exception in new user Signup", e.message)
return HttpResponseRedirect('/500/')
else:
if check_authentication(request):
return HttpResponseRedirect('/404/')
else:
try:
c = {}
c.update(csrf(request))
return render(request, 'login.html', {'user': False, 'c': c})
except Exception as e:
logger.error("Exception in generating csrf for login form", e.message)
return HttpResponseRedirect('/500/')
以上是用户创建的代码。任何关于使代码更好的建议也是受欢迎的。