我需要让user
创建一个具有Category
的事件。当用户转到create_event页面时,会显示dropdown list
个Category
个实例。我需要确保只有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
有人可以帮我吗?
答案 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
)