2015-04-03 70 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