Aditya Singh
Aditya Singh

Reputation: 970

FormView get_context_data does not work when form is invalid

When creating a view using FormView class and using get_context_data to display some data on the test html page alongside the form , Error is received when the form gets invalid , and context data is not retrieved

in get_context_data

context['username'] = data['username'] KeyError: 'username'

Key Error is thrown when the form invalidates

class TestView(LoginRequiredMixin,FormView):
    form_class = TestForm
    template_name = 'test.html'


    def get_context_data(self, **kwargs):
        context = super(CredentialsView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated:
            data = TestViewSet.as_view({'get': 'list'})(self.request).data
            context['username'] = data['username']
            context['firstname'] = data['firstname']
            context['lastname'] = data['lastname']
            
        return context

        
    def form_valid(self, form):
        password = form.cleaned_data['password']
        if form.is_valid():
            return self.query_api(password)
        else:
            return super(TestView, self).form_valid(form)

here is the traceback

Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "./ssh/views.py", line 91, in post return self.form_invalid(form, **kwargs) File "./ssh/views.py", line 77, in form_invalid context = self.get_context_data(**kwargs) File "./ssh/views.py", line 97, in get_context_data kwargs['username'] = data['username'] KeyError: 'username'

In the Scenario Above ,

Upvotes: 1

Views: 828

Answers (1)

Benjamin_Mourgues
Benjamin_Mourgues

Reputation: 369

get_context_data is called before your form_valid function.

On the loading of the page you try to fetch the value of data["username"] while it's still not completed.

Basically : GET on your View -> get_context_data is called --> The form isn't completed yet

You could get your args on a post function.

def post(self, request, *args, **kwargs):
    form = TestForm(request.POST)
    if form.is_valid():
        # Do Stuff
    else:
        # Something else
        return render(ThePageWithTheForm)

Upvotes: 1

Related Questions