[Fixed]-Redirect to another form if email exists

1👍

use get_or_create

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

0👍

I could solve it but is it the best way?

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

Leave a comment