1

我想显示值

(姓和名)

从模型作为外键。我希望这些值采用选择的形式,以便用户可以选择他们想要分配对象的学生的姓名。

比如我有学生表和Testscore表,当老师要提交学生的考试成绩时,在考试表中会有一个包含学生姓名的下拉表,所以老师可以选择他想要的学生将考试成绩分配给。

编写以下代码后,我收到此错误:

TypeError at /submiit_test/

coercing to Unicode: need string or buffer, User found

模型.py

class Student(models.Model):
     user=models.ForeignKey(User,unique=True)
     pic=models.ImageField(upload_to="profile_image")
     first_name=models.CharField(max_length=100)
     last_name=models.CharField(max_length=100)

class TestScore(models.Model):
    user=models.ForeignKey(User)
    studd=models.ForeignKey(Student)
    year=models.CharField(max_length=20)
    subject_1=models.CharField(max_length=50, choices=SUBJECT_CHOICES)
    score_1=models.CharField(max_length=50)
    subject_2=models.CharField(max_length=50, choices=SUBJECT_CHOICES)
    score_2=models.CharField(max_length=50)
    subject_3=models.CharField(max_length=50, choices=SUBJECT_CHOICES)
    score_3=models.CharField(max_length=50)

    def __unicode__(self):
        return unicode(self.studd)

 class TestScoreForm(ModelForm):
      class Meta:
         model=TestScore
         fields=('year','studd','subject_1','score_1','subject_2','score_2','subject_3','score_3')

视图.py

def test_submit(request):
    if request.method=="POST":
       form=TestScoreForm(request.POST, request.FILES)
       if form.is_valid():
            data=form.cleaned_data
            newtest=TestScore(
               user=request.user,
               studd=data['studd'],
               year=data['year'],
               subject_1=data['subject_1'],
               score_1=data['score_1'],
               subject_2=data['subject_2'],
               score_2=data['score_2'],
               subject_3=data['subject_3'],
               score_3=data['score_3'])
           newtest.save()
           return HttpResponse('thanks')
        else:
            return HttpResponse('fill the form correctly')
     else:
        return render_to_response('posttest.html',{'TestScoreForm':TestScoreForm,'TestScore':TestScore},context_instance=RequestContext(request))
4

1 回答 1

7

我已经修好了。它来自

学生

楷模。我不得不把它改成

def __unicode__(self):
     return '%s' % (self.user)
于 2013-10-26T00:28:03.690 回答