[Answer]-Validate nested form in Django

1๐Ÿ‘

i implemented the same today. I learnt this from the this website tango with django. http://www.tangowithdjango.com/book/chapters/login.html. Also i provided my code how i achieved this. Inbuilt user model itself checks if the username already exists or not. hope this is helpful.

class Sam(models.Model):
      user = model.OneToOneField(User)
      #custom fields apart from the inbuilt User model
      region = models.CharField(max_length=10)
      designation = models.CharField(max_length=10)
#forms.py form models. Created SamProfileform  to capture the custom fields which are specific to One's Profile and SamForm to capture the password and then hash later in the view. 
#Please note that i didnt add any username check here. The inbuilt User does it for us. I verified it.
class SamForm(forms.ModelForm):
      #form model to capture inbuilt fields of "User" model
      password = forms.CharField(widget=PasswordInput())
      class Meta:
            model = User
            fields = ('username', 'email', 'password', 'firstname', 'lastname')
class SamProfileForm(forms.ModelForm):
       #form model to built the custom fields in my case region and designation
       class Meta:
             model = Sam
             fields = ('desgination', 'mgr')
def register(request):
    registered = False
    if request.method == 'POST':
         user_form = SamForm(data=request.POST)
         profile_form = SamProfileForm(request.POST)
         if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            registered = True
         else:
            print user_form.errors, profile_form.errors
   else:
       user_form = SamForm()
       profile_form = SamProfileForm()
   template = loader.get_template('sam/register.html')
   context = RequestContext(request, {
            'user_form' : user_form, 'profile_form' : profile_form, 'registered' : registered,
    })
   return HttpResponse(template.render(context))
๐Ÿ‘คVenu

Leave a comment