【问题标题】:How to use field in a linked table as a field in django-crispy-forms?如何将链接表中的字段用作 django-crispy-forms 中的字段?
【发布时间】:2012-11-06 18:48:11
【问题描述】:

我有两个由 ForiegnKey 链接的模型,我想使用 django-crispy-forms 将 PhoneNumber 模型中的字段用于我的表单。

我尝试使用语法“phone_number__number”,但这只会在表单中给我一个空的下拉列表。

这是我的模型,除了 phone_number 之外的所有内容都从这篇文章的 Customer 模型中删除:

class Customer(models.Model):
  phone_number = models.ForeignKey(PhoneNumber)

class PhoneNumber(models.Model):
  TYPES = (
      ('Cell', 'Cell'),
      ('Home', 'Home'),
      ('Fax', 'Fax'),
      ('Work', 'Work'),
  )
  primary = models.BooleanField(default=False)
  phone_type = models.CharField(max_length=30, choices=TYPES, default='Cell')
  number = models.CharField(max_length=15)

还有我的表单,只有 phone_number 字段:

class CustomerCreateForm(forms.ModelForm):
 '''
 Base form for creating customers
 '''
 def __init__(self, *args, **kwargs):
     self.helper = FormHelper()
     self.helper.layout = Layout(
         Fieldset(
             'Personal Information',
             'phone_number__number',
         ),
         FormActions(
             Submit('submit' , 'Submit' , css_class='btn btn-success'), 
             Button('cancel' , 'Cancel' , css_class='btn btn-warning', onclick='javascript:history.go(-1);'), 
         )
     )
     super(CustomerCreateForm, self).__init__(*args, **kwargs)

 class Meta:
     model = Customer
     exclude = (
         'create_user',
         'modify_user'
     )

【问题讨论】:

    标签: django forms django-crispy-forms


    【解决方案1】:
    from yourapp.models import PhoneNumber    
    
    class CustomerCreateForm(forms.ModelForm):
        '''
        Base form for creating customers
        '''
        def __init__(self, *args, **kwargs):
            self.helper = FormHelper()
            self.helper.layout = Layout(
                Fieldset(
                    'Personal Information',
                    'phone_number',
                ),
             FormActions(
                 Submit('submit' , 'Submit' , css_class='btn btn-success'), 
                 Button('cancel' , 'Cancel' , css_class='btn btn-warning', 
                        onclick='javascript:history.go(-1);'), 
                 )
             )
             super(CustomerCreateForm, self).__init__(*args, **kwargs)
             self.fields["phone_number"].choices = \
             [(item.number, item.number) for item in PhoneNumber.objects.all()]
    
             class Meta:
                 model = Customer
                 exclude = (
                     'create_user',
                     'modify_user'
                 )
    

    【讨论】:

    • 数字字段应该是 CharField,而不是 ModelChoiceField。我不是要显示一组电话号码选择,而是要显示电话号码的文本框。
    猜你喜欢
    • 2019-12-31
    • 2021-05-29
    • 2018-06-17
    • 2012-11-09
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 2014-02-22
    相关资源
    最近更新 更多