0

我需要user创建一个事件,它有一个Category。当用户进入 create_event 页面时,他会看到一个实例dropdown list。我Category需要确保只有那些Category由 s​​ 创建的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

有人可以帮我吗?

4

2 回答 2

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

于 2012-11-08T08:28:48.790 回答
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
                                                                        )
于 2012-11-08T08:32:00.267 回答