2015-04-02 65 views
0

我目前正在使用Django1.7,并且正在处理一个需要我根据值显示特定表单域的项目。这是得到的。我如何从views.py中更改ModelForm中字段的属性?

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改变?

+0

究竟是什么你想改变什么? – rnevius 2015-04-02 09:44:05

+0

是的,我想从我的views.py – phourxx 2015-04-02 09:52:37

+0

改变'区域'的查询集。你可以在窗体的'__init __()'方法中覆盖它。 – Rohan 2015-04-02 10:17:00

回答

0

您可以通过“区域”的形式作为参数,并加载它现场查询集:

#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())