2013-03-24 8 views
8

मेरे पास ModelChoiceField के साथ एक फॉर्म है, और मैं इसे अपने डीबी से एक टेबल लोड करना चाहता हूं। अगर मैं अपने रूप के init पर इस क्वेरीसमूह उपयोग करते हैं, तो मेरे विचार के form.is_valid ठीक काम करता है:Django - कैसे ModelChoiceField क्वेरीसेट का काम करता है?

self.fields['categoria_formfield'].queryset = sitio_categoria.objects.exclude(categoria='patrimonio').values_list('idCategoria',flat=True) 

enter image description here

कि कोड ModelChoiceField पर एक पहचान-पत्र सूची दिखाने के लिए है, लेकिन मैं क्या यह श्रेणियों दिखाने के लिए की जरूरत है सूची। तो मैं का उपयोग करें:

self.fields['categoria_formfield'].queryset = sitio_categoria.objects.exclude(categoria='patrimonio').values_list('categoria',flat=True) 

लेकिन इस कोड का उपयोग कर सत्यापित नहीं .is_valid और मैं एक रूप त्रुटि recive: "एक मान्य विकल्प का चयन करें यह विकल्प उपलब्ध विकल्पों में से एक नहीं है।।" समस्या के बारे में कुछ सुराग क्या हो सकता है?

Error recived

मॉडल

class sitio_categoria(models.Model): 
    idCategoria   = models.AutoField(primary_key=True) 
    categoria   = models.CharField(max_length=30, null=False, unique=True) 

फार्म

class anadirComercioPaso1_form(forms.Form): 
     categoria_formfield = forms.ModelChoiceField(widget=forms.Select(attrs={'size':'13', 'onchange':'this.form.action=this.form.submit()'}), queryset=sitio_categoria.objects.none()) 

def __init__(self, *args, **kwargs): 
     super(anadirComercioPaso1_form, self).__init__(*args,**kwargs) 
     self.fields['categoria_formfield'].queryset = sitio_categoria.objects.exclude(categoria='patrimonio').values_list('categoria',flat=True) 

उत्तर

13

values_list, (या values) का उपयोग न करें, ModelChoiceField वास्तविक मॉडल वस्तुओं की जरूरत है।

queryset = sitio_categoria.objects.exclude(categoria='patrimonio') 

 

ModelChoiceField सत्यापन और प्रदर्शित करने के लिए उनके यूनिकोड प्रतिनिधित्व के लिए वस्तुओं की प्राथमिक कुंजी का प्रयोग करेंगे। अपने मॉडल में यूनिकोड को तो तुम रूपांतरण को परिभाषित करने की आवश्यकता होगी:

class sitio_categoria(models.Model): 
    idCategoria = models.AutoField(primary_key=True) 
    categoria = models.CharField(max_length=30, null=False, unique=True) 

    def __unicode__(self): 
     return self.categoria 

 

ModelChoiceField documentation

The __unicode__ method of the model will be called to generate string representations of the objects for use in the field’s choices;

संबंधित मुद्दे