我有一个带有几种形式的UpdateView,我试图了解如何为另一种形式设置实例,因为第一种形式工作得很好,但是第二种形式始终为空,我无法弄清楚如何设置该模型表单的实例。
class ProfileUpdateView(UpdateView):
# model = User
queryset = User.objects.all()
form_class = UserForm
second_form_class = ClientForm
template_name = 'accounts/update.html'
def get_object(self):
user = get_object_or_404(User , username__iexact=self.kwargs.get('username'))
return user
def get_context_data(self, **kwargs):
user = self.object
profile = Client.objects.get(id = user.clients.id)
context = super(ProfileUpdateView, self).get_context_data(**kwargs)
if user.is_client and 'ClientForm' not in context:
context['client_form'] = self.second_form_class(self.request.GET, instance=profile )
return context
class User(AbstractUser):
gender_choice =(
('Male','Male'),
('Female','Female'),
)
is_artisan = models.BooleanField('artisan status', default=False)
is_client = models.BooleanField('client status', default=False)
avatar = models.ImageField(null=True ,blank=True)
birth_day = models.DateField(null=True,blank=True)
birth_location = models.CharField(max_length=30, null=True ,blank=True)
adresse = models.CharField(max_length=30, null=True ,blank=True)
gender = models.CharField(max_length=6,choices=gender_choice,)
phone = models.CharField(max_length=10 ,null=True ,blank=True)
class Client(models.Model):
client_choice = (
('erson','person'),
('company','company'),
)
client_type = models.CharField(max_length=10,choices=client_choice,)
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='clients')
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email','avatar','adresse','birth_location','birth_day' ,'gender' ,'phone')
class ClientForm(forms.ModelForm):
class Meta:
model = Client
fields = ('client_type',)
现在的问题是如何/在哪里设置第二个表单的实例,在哪里设置第一个表单的实例。
答案 0 :(得分:0)
get_context_data中是否有错字?应该是
if user.is_client and 'client_form' not in context:
context['client_form'] = self.second_form_class(self.request.GET, instance=profile)
第一种形式是在UpdateView的超类FormMixin.get_context_data中设置的(后者又调用FormMixin.get_form())。 Docs for FormMixin