使用django Form子类创建下拉列表

时间:2012-11-08 08:17:32

标签: python django

我需要让user创建一个具有Category的事件。当用户转到create_event页面时,会显示dropdown listCategory个实例。我需要确保只有Category创建的user应显示在下拉列表中

我尝试将Form子类化为此,我可以在视图和模板中使用它。

create_event的模板:

<h3>select from existing categories</h3>
{{category_choices_form.as_p}}

查看create_event:

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

然后我创建了Form子类

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')

但是,以categoryoption =开头的行会导致错误name 'self' is not defined

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

如果您想要将模型公开为html表单,请始终选择 使用ModelForm而不是简单的形式。除非你当然在做 很多奇怪或复杂的东西,构建一个简单的形式更直接。

所以在你的生活中

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_form_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))

关于self is not defined错误:

在你的CategoryChoicesForm中有这一行

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

这是在班级,self只能在instance级别使用。 self在那里“不可见”。它会在CategoryChoicesForm的方法中可见。

答案 1 :(得分:1)

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

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
                                                                        )