ModelChoiceField给出了“选择一个有效的选择”填充选择与阿贾克斯呼吁

问题描述:

我已经尝试了所有可能的解决方案在几个线程,我仍然无法解决问题。我有以下代码:ModelChoiceField给出了“选择一个有效的选择”填充选择与阿贾克斯呼吁

models.py

class CustomerVisit(models.Model): 
    start_date = models.DateField() 
    end_date = models.DateField() 
    customer = models.ForeignKey(Customer) 
    address = models.ForeignKey(Address) 

forms.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%;'})) 

views.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") 

个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 
         } 
        }) 
       }; 
      } 
     } 
    }); 
}); 

address选择基于使用ajax call using select2customer选择其被填充。阅读几个线程后,我注意到,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(),因为我需要一个空的选择

+0

你不应该这样做。所有这些逻辑都应该以这种形式出现。 –

+0

@DanielRoseman我相信你在谈论清洁领域吧?如果是这样,我有TODO来改变这一点。谢谢 –

+0

但关键是你不想为地址字段进行转换。我不知道为什么你认为它需要一个实例,表单字段的要点是他们需要POST数据并将其转换为适当的类型。 –

问题解决了。

如果有人在未来具有相同的错误我,检查从ModelChoiceFieldto_python方法救了我的一天:

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 

所以我改变了我的querysetqueryset=Address.objects而不是queryset=Address.objects.none()queryset=Address.objects.all()

谢谢丹尼尔Roseman您的意见