在更新视图中设置表单的实例



我有一个包含几个表单的 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',)

现在的问题是如何/在哪里设置第二个表单的实例以及第一个表单实例在哪里设置。

这是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

相关内容

  • 没有找到相关文章

最新更新