Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django request.GET

Tags:

request

django

It seems I can't make this example print "You submitted nothing!". Every time I submit an empty form it says:

You submitted: u''

instead of:

You submitted nothing!

Where did I go wrong?

views.py

def search(request):
    if 'q' in request.GET:
        message = 'You submitted: %r' % request.GET['q']
    else:
        message = 'You submitted nothing!'

    return HttpResponse(message)

template:

<html>
    <head>
        <title> Search </title>
    </head>
    <body>
        <form action="/search/"  method="get" >
        <input type="text" name = "q">
        <input type="submit"value="Search"/>
        </form>
    </body>
</html>
like image 420
MacPython Avatar asked Aug 17 '10 09:08

MacPython


People also ask

What is request get in Django?

In this Django tutorial, you will learn how to get data from get request in Django. When you send a request to the server, you can also send some parameters. Generally, we use a GET request to get some data from the server. We can send parameters with the request to get some specific data.

What does get () do in Django?

The get() method in Django returns a single object that matches the given lookup parameter. While using the get(), we should always use the lookups which are unique like primary keys or fields in unique constraints.

What is request POST get in Django?

When a POST request is received at the Django server, the data in the request can be retrieved using the HTTPRequest. POST dictionary. All the data of the POST request body is stored in this dictionary. For example, you can use the following code snippet inside your view.py file.

How do I use GET GET request?

request. GET will hold a dictionary and the . get('page', 1) is the call on that dictionary to retrieve the value from that dictionary with key 'page'. If key 'page' does not exist, return 1 instead.


2 Answers

Calling /search/ should result in "you submitted nothing", but calling /search/?q= on the other hand should result in "you submitted u''"

Browsers have to add the q= even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:

if request.GET.get('q'):     message = 'You submitted: %r' % request.GET['q'] else:     message = 'You submitted nothing!' 
like image 55
tux21b Avatar answered Oct 07 '22 20:10

tux21b


q = request.GET.get("q", None)
if q:
    message = 'q= %s' % q
else:
    message = 'Empty'
like image 36
Davor Lucic Avatar answered Oct 07 '22 18:10

Davor Lucic