开发者

Populate foreign key entry for a ModelForm

开发者 https://www.devze.com 2022-12-17 11:12 出处:网络
I\'m trying to fill in 开发者_StackOverflow中文版the value of a foreign key entry in one of my models using a value stored as session data...it all works well but when I try to access the record from

I'm trying to fill in 开发者_StackOverflow中文版the value of a foreign key entry in one of my models using a value stored as session data...it all works well but when I try to access the record from the admin I get this error:

Caught an exception while rendering: coercing to Unicode: 
   need string or buffer, Applicant found

Where Applicant is the model linked to by the foreign key field. How am I supposed to sort out this issue? The code is as follows:

if "customer_details" in request.session:
    customer = request.session["customer_details"]
else:
    return HttpResponseRedirect('/application/')

if request.method == 'POST':
    current_address_form = CurAddressForm(request.POST or None)

    if current_address_form.is_valid():
        current = current_address_form.save(commit=False)
        current.customer = customer
        current.save()

else:
    current_address_form = CurAddressForm()

return render_to_response('customeraddress.html', {
    'current_address_form': current_address_form,},
    context_instance=RequestContext(request))


It looks like you're trying to output a Unicode representation of a model by using the foreign key field which points to Applicant.

Something like that (just off the top of my head):

class Applicant(models.Model):
    name = models.CharField(max_length=255)

class Foo(models.Model):
    applicant = models.ForeignKey(Applicant)

    def __unicode__(self):
        # this won't work because __unicode__ must return an Unicode string!
        return self.applicant

Please show us the model code to be sure. If my guess is correct, make sure the __unicode__() method returns a unicode object. Something like this:

def __unicode__(self):
    return self.applicant.name

or

def __unicode__(self):
    return unicode(self.applicant)
0

精彩评论

暂无评论...
验证码 换一张
取 消