Skip to content
Advertisement

Can’t get form class object in template view

I want to get the form object from self.Form

This is my form

class ActionLogSearchForm(forms.Form):
    key_words = forms.CharField(required=False)

and I set form as form_class, however I can’t fetch the form data in view

class ActionLogListView(LoginRequiredMixin, ListSearchView):
    template_name = "message_logs/action_log.html"
    form_class = ActionLogSearchForm
    def get_queryset(self):
        res = []        
        form = self.form ## somehow form is None
        print(form.cleaned_data) # error occurs here. 'NoneType' object has no attribute 'cleaned_data'

I think this is the simplest set, but how can I make it work?

Advertisement

Answer

Try this:

from django.http import HttpResponseRedirect
from django.shortcuts import render

class ActionLogSearchForm(forms.Form):
    key_words = forms.CharField(required=False)

class ActionLogListView(LoginRequiredMixin, ListSearchView, request):
    form_class = ActionLogSearchForm
    def get_queryset(self, request):
        res = []        
        if request.method == 'POST':
            form = self.form(request.POST)
            if form.is_valid():
                return HttpResponseRedirect('/thanks/')
        else:
            form = NameForm()

    return render(request, 'message_logs/action_log.html', {'form': form})
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement