我目前正在使用Django1.7,并正在开发一个项目,该项目要求我根据值显示特定的表单字段。这就是我们所拥有的。
forms.py
class ServiceForm(forms.ModelForm):
area = forms.ModelChoiceField(queryset=Area.objects.all(), label=u'Area')
class Meta:
model = Service
fields = ['title', 'price', 'negotiable', 'location', 'phone', 'email', 'area', 'category', 'description',
'image1', 'image2', 'image3', 'image4']
widgets = {
'title': forms.TextInput(attrs={'placeholder': 'Service title e.g: Servicing of generators'}),
'location': forms.TextInput(attrs={'placeholder': 'Physical location of where the service will be rendered'}),
'price': forms.NumberInput(attrs={'placeholder': 'item price in figures e.g: 2000, 0 if free'}),
'phone': forms.NumberInput(attrs={'placeholder': 'seller\'s phone number (buyers can contact)'}),
'email': forms.EmailInput(attrs={'placeholder': 'seller\'s email (buyers can contact)'}),
'description': forms.Textarea(attrs={'placeholder':'Service description, a good and straight description attracts more interest', 'rows':'4'}),
}
def save(self, commit=True):
service = super(ServiceForm, self).save(commit=False)
service.active = True
if service.price == '':
service.price = 0.0
if commit:
service.save()
return service
有没有办法可以从views.py?
更改属性'area'的属性答案 0 :(得分:0)
您可以将“area”作为参数传递给表单,并使用它加载字段查询集:
#form.py
class ServiceForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
area = kwargs.pop('area')
super(ServiceForm, self).__init__(*args, **kwargs)
self.fields['area'] = forms.ModelChoiceField(queryset=area, label=u'Area')
class Meta:
...
# view.py
service_form = ServiceForm(area=Group.objects.all())