2015-04-03 72 views
1

這是我第一次使用Django,並且我對下拉框有問題。Django modelform value下拉字段是對象而不是對象字段

在我的models.py,我有以下型號:

class Country(models.Model): 
countryID = models.AutoField(primary_key=True) 
iso = models.CharField(max_length=2, null=False) 
name = models.CharField(max_length=80, null=False) 
nicename = models.CharField(max_length=80, null=False) 
iso3 = models.CharField(max_length=3, null=False) 
numcode = models.SmallIntegerField(null=False) 
phonecode = models.SmallIntegerField(null=False) 

class Address(models.Model): 
addressID = models.AutoField(primary_key=True) 
name = models.CharField(max_length=50, null=False) 
street = models.CharField(max_length=50, null=False) 
streetnumber = models.CharField(max_length=20, null=False) 
city = models.CharField(max_length=50, null=False) 
postalcode = models.CharField(max_length=30, null=True) 
country = models.ForeignKey(Country) 

在我forms.py,我有我的ModelForm:

class AddLocationForm(ModelForm): 
class Meta: 
    model = Address 
    fields = ('name','street','streetnumber','city','postalcode','country') 

而且views.py:

@login_required 
def addlocation(request): 
# Get the context from the request. 
context = RequestContext(request) 

# A HTTP POST? 
if request.method == 'POST': 
    form = AddLocationForm(request.POST) 

    # Have we been provided with a valid form? 
    if form.is_valid(): 
     # Save the new category to the database. 

     form.save(commit=True) 
     # Now call the index() view. 
     # The user will be shown the homepage. 
     return HttpResponseRedirect('/') 
    else: 
     # The supplied form contained errors - just print them to the terminal. 
     print(form.errors) 
else: 
    # If the request was not a POST, display the form to enter details. 
    form = AddLocationForm() 

# Bad form (or form details), no form supplied... 
# Render the form with error messages (if any). 
return render_to_response('accounts/addlocation.html', {'form': form}, context) 

我的數據庫表「國家」填寫了世界上所有的國家。 現在,當我在網站上填寫表格時,國家下拉框的值是「國家對象」,而不是像「澳大利亞」這樣的國家名稱。

我的問題是如何獲得國家的名稱作爲下拉框的值?

回答

1

您應該在返回self.name的國家/地區中定義__unicode__方法。 (在Python 3中,方法應該是__str__。)

+0

這樣做,謝謝 – jdb 2015-04-04 09:51:39