问题
I'm trying to implement a pulldown field that contains a list of country names in a Customer Billing Information form using the ModelChoiceField field. However, when I try to render the form, I'm getting "AttributeError, 'str' object has no attribute 'all'" and I don't know what's causing it.
I have a lookup table that contains country codes and names:
# models.py
from django.db import models
class Country(models.Model):
# Ex: code = 'us', name = 'United States'
country_cd = models.CharField(max_length=2)
name = models.CharField(max_length=40)
I then have a Customer model and associated Customer Billing Information modelform that contains a foreign key field to point to the above lookup table:
# models.py
class Customer(models.Model):
user = models.OneToOneField(User, primary_key=True)
country = models.ForeignKey(Country)
# Other fields...
# forms.py
from django import forms
from app.models import Customer, Country
class CustomerBillingInfoForm(forms.ModelForm):
class Meta:
model = Customer
fields = ('country',)
country = forms.ModelChoiceField(queryset='Country.objects.all()', empty_label=None)
I've run this in the debugger and doing "type(country)" does show that it's a QuerySet and that "Country.objects.all()" is returning all of the countries in my "country" database. The stacktrace says the error is being raised at line 896 of the /django/forms/models.py module (Django v. 1.4) in the 'ModelChoiceIterator' class.
Does anyone see what I'm doing wrong here? Many thanks for your help.
回答1:
Change:
country = forms.ModelChoiceField(queryset='Country.objects.all()',
empty_label=None)
to:
country = forms.ModelChoiceField(queryset=Country.objects.all(),
empty_label=None)
来源:https://stackoverflow.com/questions/14901300/use-django-modelchoice-field-to-create-pulldown-to-lookup-table