如何根据型号选择创建选择字段

时间:2014-08-07 07:12:20

标签: python django

我有一个Django模型如下:

class Property(models.Model):
    id = models.AutoField(unique=True, primary_key=True)
    name = models.CharField(max_length=500)
    desc = models.CharField(max_length=2000)
    residential = 'residential'
    commercial = 'commercial'
    outright = 'outright'
    lease = 'lease'
    empty = ''
    types = ((residential, 'residential'), (commercial, 'commercial'), (outright, 'outright'), (lease, 'lease'), (empty, ''))
    property_type = models.CharField(choices=types, default=empty, max_length=20)

我现在有一个ModelForm如下:

class PostForm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control input-area', 'placeholder': 'Enter name for Property'}), required=True)
    desc = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control input-area', 'placeholder': 'Enter a small description', 'rows': '5', 'style': 'resize:none;'}), required=True)
    property_type = forms.CharField(max_length=20, widget=forms.Select(types)) #This is where I want to add the choices available in the Property Model.

我试过这个方法

class PostForm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control input-area', 'placeholder': 'Enter name for Property'}), required=True)
    desc = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control input-area', 'placeholder': 'Enter a small description', 'rows': '5', 'style': 'resize:none;'}), required=True)
    residential = 'residential'
    commercial = 'commercial'
    outright = 'outright'
    lease = 'lease'
    empty = ''
    types = ((residential, 'residential'), (commercial, 'commercial'), (outright, 'outright'), (lease, 'lease'), (empty, ''))
    property_type = models.CharField(choices=types, default=empty, max_length=20)

然而,这给了我'tuple' object has no attribute 'copy'错误。通过Django Docs,我看到了一个解决方案here,但我不确定这是如何工作的。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

在表单中,字段property_type必须为ChoiceField而非CharField外观:

class PostForm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control input-area', 'placeholder': 'Enter name for Property'}), required=True)
    desc = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control input-area', 'placeholder': 'Enter a small description', 'rows': '5', 'style': 'resize:none;'}), required=True)
    residential = 'residential'
    commercial = 'commercial'
    outright = 'outright'
    lease = 'lease'
    empty = ''
    types = ((residential, 'residential'), (commercial, 'commercial'), (outright, 'outright'), (lease, 'lease'), (empty, ''))
    property_type = models.ChoiceField(choices=types, default=empty, max_length=20)