Python 使用django表单子类创建下拉列表

Python 使用django表单子类创建下拉列表,python,django,Python,Django,我需要让用户创建一个具有类别的事件。当用户进入创建事件页面时,会显示一个下拉列表,其中包含类别实例。我需要确保只有用户创建的类别才会显示在下拉列表中 我尝试将表单子类化,以便在视图和模板中使用它 创建\u事件的模板: <h3>select from existing categories</h3> {{category_choices_form.as_p}} def create_event(request,..): user_categories = Cate

我需要让
用户
创建一个具有
类别
的事件。当用户进入创建事件页面时,会显示一个
下拉列表
,其中包含
类别
实例。我需要确保只有
用户
创建的
类别
才会显示在下拉列表中

我尝试将
表单
子类化,以便在视图和模板中使用它

创建\u事件的模板:

<h3>select from existing categories</h3>
{{category_choices_form.as_p}}
def create_event(request,..):
    user_categories = Category.objects.filter(creator=request.user)
    form_data = get_form_data(request)
    category_choices_form = CategoryChoicesForm(request.user,form_data)# is this correct?
    ...

def get_form_data(request):
    return request.POST if request.method == 'POST' else None
然后我创建了
表单
子类

class CategoryChoicesForm(forms.Form):
    def __init__(self, categorycreator,*args, **kwargs):
        super(CategoryChoicesForm, self).__init__(*args, **kwargs)
        self.creator=categorycreator
    categoryoption = forms.ModelChoiceField(queryset=Category.objects.filter(creator=self.creator),required=False,label='Category')
但是,以
categoryooption=
开头的行会导致错误,表示未定义名称“self”


有人能帮我吗?

当您有一个模型要以html表单的形式公开时,总是更喜欢 使用a而不是简单的形式。除非你在做什么 很多奇怪或复杂的东西,构建一个简单的表单更简单

所以在你的情况下

from django.forms import ModelForm

class CategoryForm(ModelForm):
    class Meta:
        model = Category
        # exclude = ('blah', 'foo') # You can exclude fields from your model, if you dont want all of them appearing on your form.
您的
get\u form\u data
功能是不必要的。这就是在视图中使用表单的方式

from django.template import RequestContext
from django.shortcuts import render_to_response

def create_event(request,..):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            # do stuff and redirect the user somewhere

    else:
        # We're in a GET request, we just present the form to the user
        form = CategoryForm()
    return render_to_response('some_template.html', {'form':form}, context_instance=RequestContext(request))

关于未定义的
自身
错误:

在您的
类别选择表中
有这一行

    categoryoption = forms.ModelChoiceField(queryset=Category.objects.filter(creator=self.creator),required=False,label='Category')

这是在类级别,当
self
只能在
实例
级别上使用时<代码>自身在那里不“可见”。在
CategoryChoicesForm
的方法中可以看到它。

使用表单时,您应该以以下方式更改查询集:

class CategoryChoicesForm(forms.Form):
    categoryoption = forms.ModelChoiceField(
                           queryset = Category.objects.none(),
                           required=False,label='Category')

    def __init__(self, categorycreator,*args, **kwargs):
        super(CategoryChoicesForm, self).__init__(*args, **kwargs)
        self.creator=categorycreator
        self.fields['categoryoption'].queryset = Category.objects.filter( 
                                                           creator=self.creator
                                                                        )