I need to let a user create an Event which has a Category.When a user goes to the create_event page he is shown a dropdown list of Category instances.I need to make sure that only those Category s created by the user should be shown in the dropdown list
I tried to subclass Form for this sothat I can use it as below in view and template.
template for create_event:
<h3>select from existing categories</h3>
{{category_choices_form.as_p}}
view for 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
Then I created the Form subclass
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')
However, the line starting categoryoption = causes error saying name 'self' is not defined
Can somebody help me with this?
When you have a model that you want to expose as an html form, always prefer
to use a ModelForm instead of a simple form. Unless of course you’re doing
a lot of weird or complicated stuff and building a simple form is more straightforward.
So in your situtation
Your
get_form_datafunction is unnecessary. This is how you use your form in a viewAbout the
self is not definederror:in your
CategoryChoicesFormyou have this lineThis is at the class level, when
selfcan be used only on aninstancelevel.selfis not “visible” there. It would be visible inside a method ofCategoryChoicesFormthough.