Django modelform值下拉字段是object,而不是object
这是我第一次使用Django,我对下拉框有问题 在my models.py中,我有以下模型:Django modelform值下拉字段是object,而不是object,django,forms,django-forms,Django,Forms,Django Forms,这是我第一次使用Django,我对下拉框有问题 在my 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
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)
在my 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)
我的数据库表“country”包含了世界上所有的国家。
现在,当我在网站上填写表格时,国家的dropbdown框的值是“country object”,而不是像“Australia”这样的国家名称
我的问题是如何获取国家名称作为下拉框的值?您应该在返回
self.name
的国家定义一个\uuuunicode\uuuu
方法。(在Python3中,方法应该是\uuu str\uu
)