Django中表单的动态初始化

时间:2015-05-26 17:35:09

标签: django forms

我正在尝试动态初始化表单。这是我的forms.py:

class MapLocalityForm(forms.Form):


def search_locs(self, location):
    print("inside form")
    print(location)
    return Locality.objects.filter(name=location)

def __init__(self,*args, **kwargs):
    self.loc = kwargs.pop('loc', None)
    super(MapLocalityForm, self).__init__(*args, **kwargs)
    self.fields['locality'] = forms.ModelChoiceField(queryset='',widget=forms.RadioSelect(),required=True,
                                      initial=1)
    if self.loc:
        loc_term = self.loc
        # print(loc_term)
        loc_list = self.search_locs(loc_term)
        # print(loc_list)
        self.fields['locality'].queryset = loc_list
    else:
        self.fields['locality'].queryset = Locality.objects.none()

所以我在views.py中执行检查:

def map_locality(request,freq_term):
    if request.method =='POST':
        form = MapLocalityForm(request.POST, loc=freq_term)
        if form.is_valid():
            "do something"
    else:
        form = MapLocalityForm()
return render(request, 'maplocalities.html', {'form': form,'loc':freq_term,'alias_created':alias_created})

我使用重定向选项定向到此视图,因此请求是GET。每当我跳转到这个maplocalities.html时,我都会得到一个空表单,因为代码转到了else部分并且没有参数。通常当我们创建一个静态的表单时,表单会在转到else部分时显示。任何想法都可以纠正我的观点,就像静态表格一样。

0 个答案:

没有答案