如何构造具有ModelChoiceField的Django表单?

时间:2016-05-31 14:29:59

标签: python django forms

我正在尝试为我的表单编写一个使用自定义ModelChoiceField的测试:

from django.forms import ModelChoiceField
class CycleModelChoiceField(ModelChoiceField):
    def label_from_instance(self, cycle):
        return str(cycle.begin_date)

用户在此字段中选择的内容需要通过覆盖clean()方法传递到其他2个字段(DateField和radio ChoiceField)。这是我需要测试的复杂逻辑。

所以这是我到目前为止在测试中尝试的内容:

self.client.login(username='user', password='1234')
response = self.client.get(reverse('my_form'), follow=True)
cyc = list(CycleDate.objects.all())[0]
form_data = {'type_of_input': '0', 'cycle': cyc,'usage_type': 'E',}
form = EnergyUsageForm(data=form_data, user=response.context['user'])

但是form.is_valid()返回false而form.errors说:

{'cycle': [u'Select a valid choice. That choice is not one of the available choices.']}

我的表单构造一定有问题。 'cycle': cyc显然无法按预期工作。我还尝试了'cycle': '0''cycle': '1'

构建这样的表单的正确方法是什么?

修改 我应该解释一下可用的选择。数据库中只有一个CycleDate,只有一个选择。在shell中运行我的测试行后,我输入form.fields['cycle'].choices.choice(cyc),返回(1, '2015-05-01')。奇怪的是form.fields['cycle'].queryset返回[]。也许问题与此有关?

EDIT2: 这是我的形式与复杂(阅读:凌乱,可怕和可耻)清洁方法:

class EnergyUsageForm(forms.Form):
    # Override init so that we can pass the user as a parameter.
    # Then put the cycle form inside init so that it can access the current user variable
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(EnergyUsageForm, self).__init__(*args, **kwargs)

        # Get the last 12 cycle dates for the current user
        td = datetime.date.today
        cycle_dates = CycleDate.objects.filter(cycle_ref=Account.objects.get(holder__user=user).cycle,
                                               begin_date__lte=td).order_by('begin_date')
        self.fields['cycle'] = CycleModelChoiceField(queryset = cycle_dates,
                                                      required = False,
                                                      widget = forms.Select(attrs={"onChange":'changeCalendar()'}),
                                                      label = "Choose a billing cycle")


    type_of_input = forms.ChoiceField(required=False,
                                    widget=forms.Select(attrs={"onChange": "switchInput()"}),
                                    choices=INPUT,
                                    initial='0',
                                    label="Choose a way to display usage", )

    end_date = forms.DateField(widget=forms.TextInput(attrs=
                                {
                                    'class':'datepicker'
                                }), 
                                label="Choose start date",
                                help_text='Choose a beginning date for displaying usage',
                                required=True,
                                initial=datetime.date.today,)

    period = forms.ChoiceField(required=True,
                                widget=forms.RadioSelect, 
                                choices=DISPLAY_PERIOD, 
                                initial='01',
                                label="Choose period to display",)

    usage_type = forms.ChoiceField(required=True,
                                widget=forms.RadioSelect,
                                choices=USAGE_TYPE,
                                initial='E',
                                label="Choose type of usage to display",)

    def clean_end_date(self):
        data = self.cleaned_data['end_date']

        if datetime.date.today() < data:
            raise forms.ValidationError("Don't choose a future date")
        # Always return the cleaned data, whether you have changed it or
        # not.
        return data

    def clean(self):
        cleaned_data = super(EnergyUsageForm, self).clean()
        selection = cleaned_data['type_of_input']
        # Check if the user wants to use cycle_dates instead
        if selection == '0':
            # Set the end_date and period
            cleaned_data['end_date'] = cleaned_data['cycle'].begin_date #MUST BE CHANGED TO END_DATE LATER
            cleaned_data['period'] = cleaned_data['cycle'].duration
        return cleaned_data

EDIT3 修正了我的测试中的拼写错误,这也是我的测试的setUp方法:

client = Client()
    def setUp(self):
        user = User.objects.create_user(username = 'user', password = '1234')
        user.save()
        profile = UserProfile.objects.create(user = user)
        profile.save()
        account = Account(number=1, first_name='test',
                          last_name='User',
                          active=True,
                          holder=profile,
                          holder_verification_key=1)

        account.save()

        the_cycle = Cycle.objects.create(name = 'test cycle')
        the_cycle.save()
        cd = CycleDate.objects.create(begin_date = datetime.date(2015, 5, 1),
                                 end_date = datetime.date.today(),
                                 cycle_ref = the_cycle)
        cd.save()

EDIT4: 除了所有这些混乱之外,每当我致电KeyError: 'cycle'时,我现在都会收到form.is_valid()。可能是由于clean()方法在循环字段选择无效时尝试访问cleaning_data ['cycle']。

2 个答案:

答案 0 :(得分:1)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr/><p id="myparagraph"></p><hr/>
<textarea></textarea>

特别是

self.client.login(username='user', password='1234')
response = self.client.get(reverse('my_form'), follow=True)
cyc = list(CycleDate.objects.all())[0]
form_data = {'type_of_input': '0', 'cycle': cyc,'usage_type': 'E',}
form = EnergyUsageForm(data=form_data, user=response.context['user'])
  • 首先你得到所有CycleDates的迭代器(确定,或多或少好......)
  • 然后你把所有东西都读到记忆中(为什么!)
  • 最后..你选择第一个列表元素(当然,如果列表为空,你会得到异常......)

为什么不:

cyc = list(CycleDate.objects.all())[0]

EnergyUsageForm的初始化:

cyc = CycleDate.objects.first()
if cyc:
    # cycle is a ModelChoice - in html it stores primary key!
    form_data = {'type_of_input': '0', 'cycle': cyc.pk, 'usage_type': 'E'}
    form = EnergyUsageForm(data=form_data, user=response.context['user'])

答案 1 :(得分:0)

正如DanielRoseman所指出的,答案是使用实例的id。

因此,使用ModelChoiceField构造表单的正确方法如下:

my_instance = MyModelName.objects.get(whatever instance you need)
form_data = {'my_regular_choice_field': '0', 'my_model_choice_field': my_instance.id}
form = MyFormName(data=form_data)