1
我有一個驗證包含ModelMultipleChoiceField的表單的問題。 在面子上提交,我有這樣的錯誤:Django,unicode對象沒有屬性pk
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/Proapp/main_app/views.py", line 275, in felicitationInscription
if completerProfilForm.is_valid() :
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 161, in is_valid
return self.is_bound and not self.errors
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 153, in errors
self.full_clean()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 362, in full_clean
self._clean_fields()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 380, in _clean_fields
value = field.clean(value)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1254, in clean
qs = self._check_values(value)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1287, in _check_values
pks = set(force_text(getattr(o, key)) for o in qs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 1287, in <genexpr>
pks = set(force_text(getattr(o, key)) for o in qs)
AttributeError: 'unicode' object has no attribute 'pk'
所以我的形式是這樣的:
class inscritForm(forms.ModelForm) :
firstname = forms.CharField(max_length=50,widget=forms.TextInput(attrs={'class':'form-control'}))
class Meta :
model = Inscrit
fields = ['firstname','skills']
def __init__(self, *args, **kwargs):
super(inscritForm, self).__init__(*args, **kwargs)
thedomains = Domain.objects.values_list('name',flat=True)
self.fields["skills"] = forms.ModelMultipleChoiceField(queryset=thedomains, widget=forms.CheckboxSelectMultiple()
for key, field in self.fields.iteritems():
self.fields[key].required = False
而且型號:
class Inscrit(models.Model):
user = models.OneToOneField(User)
competences = models.ManyToManyField(Speciality,related_name='specialities')
class Domain(models.Model):
name = models.CharField(max_length=20,primary_key=True)
def __str__(self) :
return self.name
def __unicode__(self) :
return self.name
@python_2_unicode_compatible
class Speciality(models.Model):
domain = models.ForeignKey(Domain,null=False)
specificity = models.TextField(max_length=100,null=True)
def __str__(self):
return u'%s %s'%(self.domain.name, self.specificity)
最後,我的觀點驗證:
我測試了域的實例是否在shell中具有屬性'pk',並且他們有...
謝謝,我忘了這種特殊性...謝謝! – Zoulou