选择一个有效的选择。该选择不是可用的选择之一

时间:2019-01-14 12:07:05

标签: ajax django django-models django-forms modelchoicefield

在我的应用程序中,我有一个下拉列表(部门),该下拉列表取决于先前从下拉列表(“教职”字段)中选择的值。我正在使用ajax获得可以正常工作的新值。但是,当我尝试保存表单时,我得到选择一个有效的选择。该选择不是可用的选择之一。

这是我的模特

from django.db import models
from system.models import FacultyData, DepartmentData, SessionData, SemesterData, SettingsData

# Create your models here.

class SchoolFees(models.Model):
    fid = models.ForeignKey(FacultyData, on_delete= models.SET_NULL, null=True)
    did = models.ForeignKey(DepartmentData, on_delete= models.SET_NULL, null=True)
    sid = models.ForeignKey(SessionData, on_delete= models.SET_NULL, null=True)
    amount = models.CharField(max_length=30)

    def __str__(self):
        return self.amount

和我的form.py

from django import forms
from . import models
from system.models import FacultyData, DepartmentData, SessionData
from .models import SchoolFees



class FeesCreationForm(forms.ModelForm):
    fid = forms.ModelChoiceField(queryset=FacultyData.objects.all(), empty_label="--Select Faculty--",
                                 widget=forms.Select(attrs={'class': 'form-control'}))

    did = forms.ModelChoiceField(queryset=DepartmentData.objects.all(), empty_label="--Select Faculty First--",
                                 widget=forms.Select(attrs={'class': 'form-control'}))

    sid = forms.ModelChoiceField(queryset=SessionData.objects.all(), empty_label="--Select Session--",
                                 widget=forms.Select(attrs={'class': 'form-control'}))

    class Meta:
        model = models.SchoolFees
        fields = ['sid', 'fid', 'did', 'amount']

        widgets = {
            'amount': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Amount'})

        }



  def __init__(self, *args, **kwargs):
    super(FeesCreationForm, self).__init__(*args, **kwargs)
    self.fields['did'].queryset = DepartmentData.objects.none()

   # Get did queryset for the selected fid
    if 'fid' in self.data:
        try:
            fd = int(self.data.get('fid'))
            self.fields['did'].queryset = DepartmentData.objects.filter(fid=fd).order_by('dept_name')
        except (ValueError, TypeError):
            pass # invalid input from the client; ignore and use empty queryset

在我的view.py中,我有一种根据所选择的系获取科系的方法。以及节省新费用

def create_fee(request):
    app = settings.CONFIG
    #table = FacultyTable(FacultyData.objects.all())
   # RequestConfig(request, paginate={'per_page': 10}).configure(table)
    context = {"form": FeesCreationForm,  'app': app}
    return render(request, 'bursary.html', context)

def get_department(request):

    fid = request.GET.get('fid', None)

    datas = {
        'is_taken': DepartmentData.objects.filter(fid=fid)
    }
    department = list(DepartmentData.objects.filter(fid=fid).values())
    data = dict()
    data['department'] = department
    return JsonResponse(data)

def save_fee(request):
    app = settings.CONFIG
    # table = FacultyTable(FacultyData.objects.all())
    # RequestConfig(request, paginate={'per_page': 10}).configure(table)
    form = FeesCreationForm(request.POST)
    context = {"form": FeesCreationForm, 'app': app}
    if form.is_valid():
        form.save()
        messages.add_message(request, messages.SUCCESS, "Fees added successfully")
    else:
        messages.add_message(request, messages.ERROR, form.errors)

    return redirect('bursary:create_fee')

我不知道我在哪里弄错了或者怎么解决

2 个答案:

答案 0 :(得分:1)

这是因为您将查询集初始化为空(这很好),但决不要在表单对象本身内对其进行更新。因此服务器端验证失败。

尝试在FeesCreationForm的__init__方法中更新查询集:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    # Init empty did queryset
    self.fields['did'].queryset = DepartmentData.objects.none()

    # Get did queryset for the selected fid
    if 'fid' in self.data:
        try:
            fid = int(self.data.get('fid'))
            self.fields['did'].queryset = DepartmentData.objects.filter(
                fid=fid).order_by()
        except (ValueError, TypeError):
            # invalid input from the client; ignore and use empty queryset
            pass

答案 1 :(得分:1)

(解释)

  

我有一个下拉菜单,具体取决于先前从另一个下拉菜单中选择的值

我过去也有类似的问题。 this是否回答您的问题?基本思想是,您可以将所有正确的信息发送到所需的客户端,但是在一天结束时,服务器应验证是否使用了正确的选项集。 Django生气了,因为它认为发送到服务器的第二个下拉列表选择无效。收到POST后,您需要根据作为下拉列表#1的选择发送的内容动态地获得第二个下拉列表的选择,然后尝试验证表单。