2010-01-14 51 views
0

我試圖使用存儲爲會話數據的值在我的模型之一中填寫外鍵條目的值......它一切正常,但是當我嘗試訪問從管理記錄我得到這個錯誤:爲ModelForm填充外鍵條目

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

Applicant是外鍵字段鏈接到模型。我該如何解決這個問題?代碼如下:

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)) 
+3

這是代碼的行觸發錯誤? 'request.session [「customer_details」]'是什麼?主鍵?在嘗試爲其設置current.customer之前,您可能需要獲取由會話數據表示的'Applicant'。 – 2010-01-14 09:29:57

+0

當我嘗試在管理員 – Stephen 2010-01-14 10:55:56

回答

3

它看起來像你試圖通過使用指向申請人的外鍵字段輸出模型的Unicode表示形式。

類似的東西(就在我的頭頂):

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 

請告訴我們的模型代碼以確保萬無一失。如果我的猜測是正確的,請確保__unicode__()方法返回一個unicode對象。事情是這樣的:

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

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

WOW !!!中嘗試查看記錄時,會觸發該錯誤......這解決了問題。感謝Haes :) – Stephen 2010-01-14 11:12:43