1

ModelChoiceField フォームで奇妙な動作が発生しています。少し背景。特定のフィールドの変数クエリセットを持つフォームが必要です。this questionthisを見て、 init メソッドに渡されたリクエストに基づいてこれを処理するフォームの init メソッドを作成しました。

class QueryTimeEntryForm(forms.Form):
query_start_date = forms.DateField(label='Start Date:', required=True, widget=forms.TextInput(), input_formats=['%m/%d/%Y', '%Y-%m-%d'])
query_end_date = forms.DateField(label='End Date:', required=True, widget=forms.TextInput(), input_formats=['%m/%d/%Y', '%Y-%m-%d'])
time_query_unit = forms.ModelChoiceField(queryset=Unit.objects.all().order_by('unit'), label='', required=False, empty_label='Choose a unit', widget=forms.Select())
time_query_employee = forms.ModelChoiceField(queryset=Employee.objects.none(), label='', required=False, empty_label='Choose an employee', widget=forms.Select())
time_query_radio = forms.ChoiceField(label='', widget=forms.RadioSelect(attrs={'class':'queryRadio'}), choices=QUERY_CHOICES, initial='1')

def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    super (QueryTimeEntryForm, self).__init__(*args, **kwargs)
    #depending on the user, set the queryset of the employee drop down
    #get the employee category for the user
    today = datetime.today()
    emp = Employee.objects.filter(user__exact=self.request.user)
    ec = EmployeeCategory.objects.filter(employee__exact=emp[0]).filter(effectiveDate__lte=today).filter(Q(enddate__gte=today) | Q(enddate__isnull=True))[0]

    if ec.category.category == 1:
        self.fields['time_query_employee'].queryset = Employee.objects.filter(user__exact=self.request.user)
    elif ec.category.category == 2:
        #get the unit for this category 2 employee
        unit = EmployeeUnit.objects.filter(employee__exact=emp).filter(effective_date__lte=today).filter(Q(end_date__gte=today) | Q(end_date__isnull=True))[0].unit
        #get the employees who currently share the unit with the current category 2 employee, excluding the current category 2 employee
        self.fields['time_query_employee'].queryset = Employee.objects.filter(employee_for_employeeunit__unit__exact=unit).filter(Q(employee_for_employeeunit__end_date__gte=today) | Q(employee_for_employeeunit__end_date__isnull=True)).exclude(employee_for_employeeunit__exact=emp).order_by('user__first_name')
    else:
        #get category 1
        cat = Category.objects.filter(category__exact=1)[0]
        self.fields['time_query_employee'].queryset = Employee.objects.filter(employee_for_employeecategory__category__exact=cat).filter(Q(employee_for_employeecategory__enddate__gte=today) | Q(employee_for_employeecategory__enddate__isnull=True)).order_by('user__first_name')

フォームがバインドされていない場合、すべてが正常に機能します。HTMLのドロップダウンに期待する従業員だけを取得します。私が抱えている問題は、フォームを投稿するときに ModelChoiceField が検証に失敗することです。ステップを進めていくと、この質問と同様に、「有効な選択肢を選択してください」というエラーが表示されることに気付きました。おそらく、スーパーが呼び出されて検証が行われたときにクエリセットが Employees.objects.none() であるためです。クエリセットを設定した後、すべてのエラーをクリアして full_clean をやり直す必要がありますか、それとも別のアプローチを取る必要がありますか? 基本的に私は立ち往生しており、何が起こっているのか、ここからどこへ行くべきなのかを正確に理解していません. init メソッドを追加して標準の Employee クエリセットを作成する前は、すべて正常に機能していました。

助けてください。ありがとう!

4

2 に答える 2

0

@Shawn、今日も同じ問題に遭遇しました。(Eclipse で、変数ペインを表示/アクティブにして) フォームの__init__() メソッドをデバッグし、コードを行ステップ実行すると、「有効な選択を選択してください」というエラーが表示されることに気付きました。ただし、ブレークポイントをクリアしてそのまま実行した場合、または変数ペインが表示されていない/アクティブでない状態でラインステップ デバッグを行った場合、エラーは発生しません。Eclipse で変数をレンダリングすると、エラーが発生します。

于 2013-10-09T14:19:43.297 に答える