2017-03-18 54 views
0

我想要實現一個邀請功能,用戶將填寫電子郵件地址並將其電子郵件保存到數據庫。如果他們再次填寫電子郵件地址並要求邀請,則應將其重定向到另一種表單(ReferForm),以便他們可以引用其他表單。如果電子郵件存在,則重定向到另一個表格

這裏是我的代碼

class InviteForm(forms.Form): 
    email = forms.EmailField(label=_("E-mail"), required=True) 

    def save(self, email): 
     print('email', email) 
     print ('############') 
     if (Invitation.objects.get(email=email)): 
      return True 
     invitation = Invitation.objects.create(email=email) 
     return invitation 

class RequestInvitation(FormView): 
    template_name = 'home.html' 
    form_class = InviteForm 

    def form_valid(self, form): 
     email = form.cleaned_data.get('email') 
     invite_instance = form.save(email) 
     if invite_instance == True: 
      return HttpResponseRedirect('/refer-form') 
     invite_instance.invited_by_email_address = self.request.user 
     invite_instance.custom_invite_code = get_custom_invite_code() 
     invite_instance.save() 
     messages.success(self.request, '{0} has been invited'.format(email)) 
     return HttpResponseRedirect('/') 

    def form_invalid(self, form): 
     # messages.error(self.request, '{0}'.format(form.errors)) 
     return self.render_to_response(self.get_context_data(form=form)) 

我進去形式保存功能在那裏我有質疑的電子郵件是否存在錯誤。但是我收到錯誤

邀請匹配查詢不存在。

回答

1

使用get_or_create

invitation, created = Invitation.objects.get_or_create(email=email) 
return invitation if created else True 
+0

我已經這樣做了,但我總是被創建爲false。是否因爲我沒有使用modelForm – pythonBeginner

+0

,當電子郵件已存在於數據庫中時,您將創建爲false。 – user3148949

0

我可以解決這個問題,但它是最好的方式?

class InviteForm(forms.Form): 
    email = forms.EmailField(label=_("E-mail"), required=True) 

    def save(self, email): 
     try: 
      invitation = Invitation.objects.get(email=email) 
      return None 
     except Invitation.DoesNotExist: 
      invitation = Invitation.objects.create(email=email) 
      return invitation 


def form_valid(self, form): 
     email = form.cleaned_data.get('email') 
     invite_instance = form.save(email) 
     if invite_instance is None: 
      return HttpResponseRedirect('/invitations/refer-invitation') 
     invite_instance.invited_by_email_address = self.request.user 
     invite_instance.custom_invite_code = get_custom_invite_code() 
     invite_instance.save() 
     messages.success(self.request, '{0} has been invited'.format(email)) 
     return HttpResponseRedirect('/') 
相關問題