picomon picomon - 1 month ago 7
Python Question

Django-Models: TypeError: coercing to Unicode: need string or buffer, User found

I want to display values


(last name and first name)


from a model as a ForeignKey. I want the values to be in form of choices so users can select the name of student they want to assign objects to.

For example, I have student form and Testscore form, when a teacher wants to submit the test score of student, in the test form there will be a drop down form that contains name of students, so the teacher can choose which student he wants to assign the test scores to.

After writing the below codes, I'm getting this error:

TypeError at /submiit_test/

coercing to Unicode: need string or buffer, User found


models.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')


views.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))

Answer

I've fixed it. It was from

Student

Models. I had to change it to

def __unicode__(self):
     return '%s' % (self.user)
Comments