2016-05-25 3 views
0

新しいユーザーが作成されると、djangoのpost_save関数を使用して電子メールを送信する必要があります。認証および作成次のように どのように私は、コードに統合んが、v​​iews.pyにバックエンド自体で行われます -post_saveを使用してデータベースエントリ作成時に電子メールを送信

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

上記は、ユーザー作成のためのコードです。コードをより良くするためのアドバイスも歓迎します。

答えて

1

IMOの場合は、signalsを使用して電子メールを送信し、直接ビューに電子メールを送信することはできません。 This postは信号を非常にうまく使用する方法を示しています。

また、createdkwargsを使用して、インスタンスが作成されているかどうかを確認できます。

@receiver(post_save, sender=User) 
def user_post_save(sender, **kwargs): 
    if kwargs['created']: # true if the instance is created 
     # send email for the new user... 
関連する問題