Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting data from a form to django view

When I open the html file it displays as expected and when I enter data in the text box and submit, It redirects me to localhost/myapp/output/ but why is the data I enter in the text box not submitted for example like localhost/myapp/output/data_I_submitted

My basic html file:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>db app</title>
</head>
<body>
{% csrf_token %}
<form action="output/" method="post" name="Input">
Data : <input type="text" name="text">
<input type="submit" value="submit">
</form>
</body>
</html>

In my app.urls file:

urlpatterns = patterns('',
    url(r'^$',views.index),
    url(r'^output/(?P<text>\w+)/$',views.return_data)
)

Finally the view:

def return_data(request,text):
    return HttpResponse('entered text ' + text)
like image 298
K DawG Avatar asked Dec 11 '22 10:12

K DawG


2 Answers

If your goal is only getting the text on the form:

change your view to

def return_data(request):
    return HttpResponse('entered text:' + request.POST['text'])

edit your urls

urlpatterns = patterns('',
    url(r'^$', views.index),
    url(r'^output/$', views.return_data)
)

and your template

<form action="output/" method="post">
{% csrf_token %}
...
</form>
like image 148
danielcorreia Avatar answered Dec 22 '22 15:12

danielcorreia


you'd better review data submitting in forms. with two methods you can submit forms data with your request to the forms action attribute:

GET: like http://www.google.com/?q=keyword+to+search you can access the "keyword+to+search" by:

request.GET['q']
#or better is:
request.GET.get('q', None)

the text arguement is not passed to url pattern. so not accessible in this way

POST: in this method the data is not in request url. so to access the forms data submittin by POST method try this

request.POST['text'] (
#or better is: 
request.POST.get('text', None)

but it is highly recommended to use Django forms instead of direct accessing from request.POST or request.GET

so check this: https://docs.djangoproject.com/en/dev/topics/forms/

like image 24
kia Avatar answered Dec 22 '22 15:12

kia