Django说它必须是一个模型实例

时间:2012-09-25 12:57:46

标签: django django-models django-forms django-views

我正在使用Django 1.3和South那些应该是有用的信息。我的问题是,在保存表单时,它说:

ValueError at /reportforms/c13
Cannot assign "u'3'": "c13.job" must be a "joblist" instance.
Request Method: POST
Request URL:    http://localhost:9000/reportforms/c13
Django Version: 1.3
Exception Type: ValueError
Exception Value: Cannot assign "u'3'": "c13.job" must be a "joblist" instance.
Exception Location: /media/Django/path_env/local/lib/python2.7/site-packages/django/db/models/fields/related.py in __set__, line 331
Python Version: 2.7.3

知道这有什么问题吗?

models.py

class joblist(models.Model):
    job_english                     = models.CharField(_('Job name in english'), max_length=255, default="")
    job_hungarian                   = models.CharField(_('Job name in hungarian'), max_length=255, default="")

class c13(models.Model):
    job                             = models.ForeignKey(joblist, verbose_name=_('Job'))

forms.py

class C13Form(ModelForm):
    job =   forms.ChoiceField(choices=[(item.pk, item.job_english) for item in joblist.objects.all()])
    class Meta:
        model = c13
        exclude = ('added_by')

views.py

    form = C13Form(request.POST)
    if form.is_valid():
        new_c13 = c13.objects.create(
            job                             = joblist.objects.get(pk=form.cleaned_data['job']),
            year                            = form.cleaned_data['year'],
            needlestick_injuries            = form.cleaned_data['needlestick_injuries'],
            staff_beginning                 = form.cleaned_data['staff_beginning'],
            staff_end                       = form.cleaned_data['staff_end'],
            working_hours_beginning         = form.cleaned_data['working_hours_beginning'],
            working_hours_end               = form.cleaned_data['working_hours_end'],
            added_by                        = request.user,
        )
        new_c13.save()
        return render_to_response('filled_out.html', {}, context_instance=RequestContext(request))
    else:
        form = C13Form(request.POST)
        return render(request, 'c13.html', { 'form': form })

1 个答案:

答案 0 :(得分:1)

也许您必须使用ModelChoiceField,请参阅https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField

job = forms.ModelChoiceField(queryset=joblist.objects.all())