Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created October 17, 2012 06:41
Show Gist options
  • Select an option

  • Save bmispelon/3904053 to your computer and use it in GitHub Desktop.

Select an option

Save bmispelon/3904053 to your computer and use it in GitHub Desktop.
Newsletter signup form
class NewsLetterSignupForm(forms.ModelForm):
class Meta:
model = NewsLetterSignup
fields = ['email']
def save(self, commit=True):
"""Return an existing instance if one exists with the same email.
Create and return it otherwise.
"""
email = self.cleaned_data['email']
# XXX: This is not atomic and is suceptible to race conditions where two
# models with the same email address could be created.
try:
return NewsLetterSignup.objects.get(email=email)
except NewsLetterSignup.DoesNotExist:
return super(NewsLetterSignupForm, self).save(commit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment