Python 如何根据模型选择创建选择字段
我有一个Django模型,如下所示:Python 如何根据模型选择创建选择字段,python,django,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 = 'comme
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)
我现在有一个模型,如下所示:
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”对象没有属性“copy”的错误。通过查看Django文档,我看到了一个解决方案,但我不确定它是如何工作的。如何解决此问题?在表单中,字段
属性\u 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)