Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting html form data into django class based view

I have created a Class view in views.py of the django application.

class HelloTemplate(TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        context = super(HelloTemplate, self).get_context_data(**kwargs)
        return context

Now I have a form defined in the html page:

<form method="get">
    <input type="text" name="q">
    <input type="text" name="q1">
    <input type="submit" value="Search">
</form> 

As you can see, I am submitting the form on the same page.

Now I want to get the form submitted values in my HelloTemplate class. I don't want to create another class or methods outside the existing class.

Also, I would like to send an error message to the html form if data is not validated in the django.

I don't know how to do this, please help me out.

like image 866
Nikunj Aggarwal Avatar asked Nov 19 '13 07:11

Nikunj Aggarwal


1 Answers

You need to define get (because your form defined with get method <form method="get">) method in view class:

class HelloTemplate(TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        context = super(HelloTemplate, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        q = request.GET.get('q')
        error = ''
        if not q:
            error = "error message"
        return render(request, self.template_name, {'error': error})

More information in django docs here Introduction to Class-based views

like image 66
ndpu Avatar answered Sep 21 '22 01:09

ndpu