Use Django ModelChoice field to create pulldown to lookup table?

蹲街弑〆低调 提交于 2019-12-13 02:24:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!