ModelChoiceField 给出了“选择一个有效的选择”,用 ajax 调用填充选择

Mar*_*rte 5 python django ajax django-forms

我已经在多个线程上尝试了所有可能的解决方案,但仍然无法解决问题。我有以下代码:

模型.py

class CustomerVisit(models.Model):
  start_date = models.DateField()
  end_date = models.DateField()
  customer = models.ForeignKey(Customer)
  address = models.ForeignKey(Address)
Run Code Online (Sandbox Code Playgroud)

表格.py

address = forms.ModelChoiceField(label='Address',
                                 queryset=Address.objects.none(),
                             widget=forms.Select(attrs={'style': 'width: 100%;'}))
customer = forms.ModelChoiceField(label='Customer',
                                  queryset=Customer.objects.all(),
                          widget=forms.Select(attrs={'style': 'width: 100%;'}))
Run Code Online (Sandbox Code Playgroud)

视图.py

if request.method == "POST":
    # Cleaning fields
    post = request.POST.copy()
    post['address'] = Address.objects.get(id=post['address'])
    post['start_date'] = dateparser.parse(post['start_date'])
    post['end_date'] = dateparser.parse(post['end_date'])
    # Updating request.POST
    request.POST = post
    form = CustomerVisitForm(request.POST)
    if form.is_valid():
        form.save(commit=True)
        return redirect("customervisit:calendar")
Run Code Online (Sandbox Code Playgroud)

js

$("#id_customer").select2({}).on("change", function () {
    var customer_id = $("#id_customer").val();
    var id_address = $("#id_address");
    id_address.select2({
        ajax: {
            url: '/get_customer_address/' + customer_id,
            dataType: "json",
            type: "GET",
            data: function (params) {

                var queryParameters = {
                    term: params.term
                }
                return queryParameters;
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.text,
                            id: item.id
                        }
                    })
                };
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我的address选择基于customer使用ajax 调用的选择填充select2。在阅读了几个线程后,我注意到modelchoicefield需要一个Address对象,这就是为什么我在验证表单之前在我的视图中使用以下代码:post['address'] = Address.objects.get(id=post['address'])但我仍然收到Select a valid choice. That choice is not one of the available choices.错误

我正在使用,queryset=Address.objects.none(),因为我需要一个空的选择

Mar*_*rte 3

问题解决了。

如果以后有人和我有同样的错误,请检查保存我的一天to_python的方法ModelChoiceField

def to_python(self, value):
    if value in self.empty_values:
        return None
    try:
        key = self.to_field_name or 'pk'
        value = self.queryset.get(**{key: value})
    except (ValueError, TypeError, self.queryset.model.DoesNotExist):
        raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
    return value
Run Code Online (Sandbox Code Playgroud)

所以我把我querysetqueryset=Address.objects改为queryset=Address.objects.none()orqueryset=Address.objects.all()

感谢丹尼尔·罗斯曼的评论