2017-10-28 56 views
1

我已經嘗試了所有可能的解決方案在幾個線程,我仍然無法解決問題。我有以下代碼: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數據並將其轉換爲適當的類型。 –

回答

0

問題解決了。

如果有人在未來具有相同的錯誤我,檢查從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您的意見

相關問題