我需要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
有人可以帮我吗?