How to load multiple models in views via using ModelForm?

Question
Models.py from django.db import models from django.contrib.auth.models import User class UserDetails(models.Model): mobile_no = models.BigIntegerField(unique = True) flat_no = models.TextField(max_length = 7, verbose_name = "Flat No./ Room No.") area = models.TextField(max_length = 15) state = models.TextField(max_length = 50) country = models.TextField(max_length = 50) city = models.TextField(max_length = 50) near_by = models.TextField(max_length = 50, null = True, blank = True, verbose_name = "Landmark") aadhaar_no = models.BigIntegerField(unique = True) locality = models.TextField(max_length = 50) pincode = models.PositiveIntegerField() user = models.ForeignKey(User) def __unicode__(self): return self.mobile_no RegisterUser.html {{ form.non_field_errors }}
{% csrf_token %} {{ form.as_p }} {{ second_form.as_p }}
Views.py from django.views.generic.edit import FormView from app.forms import UserDetailsForm, UserForm class RegisterUserView(FormView): form_class = UserDetailsForm template_name = 'app/RegisterUser.html' Forms.py from django import forms from app.models.UserDetailsModel import * from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] class UserDetailsForm(forms.ModelForm): class Meta: model = UserDetails fields = ['mobile_no', 'flat_no', 'area', 'state', 'country', 'city', 'near_by', 'aadhaar_no', 'locality', 'pincode', 'user'] def get_second_form(self): if self.request.method == 'POST': return UserForm(self.request.POST) else: return UserForm() def form_valid(self, form): print self.request.POST self.second_form = self.get_second_form() if self.second_form.is_valid(): return super(UserDetailsForm, self).form_valid(form) else: return super(UserDetailsForm, self).form_invalid(form) def form_invalid(self, form): self.second_form = self.get_second_form() self.second_form.is_valid() return super(UserDetailsForm, self).form_invalid(form) def get_context_data(self, **kwargs): context = super(UserDetailsForm, self).get_context_data(**kwargs) context['second_form'] = getattr(self, 'second_form', self.get_second_form()) return context I want to load User and UserDetails model in single html and validate via ModelForm.
sam21mishra@gmail.com Nov. 1, 2017, 5:33 a.m. 0 Answer

Warning! You are not logged in.
Your answer will be published as Guest user.

Post your Answer

 Prev question