Skip to content

Instantly share code, notes, and snippets.

@aaronromeo
Created March 31, 2014 13:17
Show Gist options
  • Save aaronromeo/9892066 to your computer and use it in GitHub Desktop.
Save aaronromeo/9892066 to your computer and use it in GitHub Desktop.
Dealing with multiple models in a Django CBVs and ModelForms
class UserProfile(models.Model):
user = models.OneToOneField(User)
avatar = models.ImageField(upload_to='profile_images', blank=True)
def __unicode__(self):
return self.user.username
class RegistrationForm(forms.Form):
username = forms.CharField()
email = forms.CharField(widget=forms.EmailInput())
password = forms.CharField(widget=forms.PasswordInput())
avatar = forms.ImageField(widget=forms.FileInput(), required=False)
def clean_email(self):
email = self.cleaned_data['email']
try:
User.objects.get(email=email)
raise forms.ValidationError('Email already exists')
except User.DoesNotExist:
pass
return email
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
raise forms.ValidationError('Username already exists')
except User.DoesNotExist:
pass
return username
def save(self, commit=True):
if commit:
import ipdb; ipdb.set_trace()
new_user = User.objects.create(
username=self.cleaned_data['username'],
email=self.cleaned_data['email'],
password=self.cleaned_data['password'],
)
new_user_profile = UserProfile.objects.create(
user=new_user
)
return new_user_profile
return super(UserProfile, self).save(commit)
class UserRegistration(FormView):
template_name = "user/registration.html"
form_class = RegistrationForm
success_url = reverse_lazy('home')
def form_valid(self, form):
form.save()
return super(UserRegistration, self).form_valid(form)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment