Django模型值下拉字段是对象而不是对象字段

时间:2015-04-03 19:16:23

标签: django forms django-forms

这是我第一次使用Django时遇到下拉框问题。

在我的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中,我有我的模型形式:

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 个答案:

答案 0 :(得分:1)

您应该在Country上定义一个返回__unicode__的{​​{1}}方法。 (在Python 3中,方法应为self.name。)