Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I post to a Django 1.2 form using urllib?

Going off of this other SO question, I tried to use urlencode and urlopen to POST data to a form. However, Django 1.2 gives me a CSRF verification failed error when I use it. Is there a workaround?

Thanks.

like image 723
Kevin Avatar asked Sep 02 '10 04:09

Kevin


People also ask

What is the difference between Urllib and urllib3?

The Python 3 standard library has a new urllib which is a merged/refactored/rewritten version of the older modules. urllib3 is a third-party package (i.e., not in CPython's standard library).

Which method of Urllib will be first used to get site content?

Urllib package is the URL handling module for python. It is used to fetch URLs (Uniform Resource Locators). It uses the urlopen function and is able to fetch URLs using a variety of different protocols.

How do I import Urlopen into Python 3?

You need to use from urllib. request import urlopen , also I suggest you use the with statement while opening a connection. @BradleyD. Freeman-Bain: you can't have a with -statement without the following block.

What is urllib2?

urllib2 is a Python module that can be used for fetching URLs. It defines functions and classes to help with URL actions (basic and digest. authentication, redirections, cookies, etc) The magic starts with importing the urllib2 module.


2 Answers

The difference between submitting data to other forms and your case is that you will have to first get the CSRF token. This can be done by performing a GET request on the page first and then parsing the csrfmiddlewaretoken using a suitable parser.

Also keep in mind that you'll need to install a cookie jar to get this to work.

For example:

#!/usr/bin/python
import urllib, urllib2, cookielib
from BeautifulSoup import BeautifulSoup

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

url = urllib2.urlopen('http://localhost:8000/accounts/login/')
html = url.read()

doc = BeautifulSoup(html)
csrf_input = doc.find(attrs = dict(name = 'csrfmiddlewaretoken'))
csrf_token = csrf_input['value']

params = urllib.urlencode(dict(username = 'foo', password='top_secret', 
       csrfmiddlewaretoken = csrf_token))
url = urllib2.urlopen('http://localhost:8000/accounts/login/', params)
print url.read()
like image 193
Manoj Govindan Avatar answered Sep 23 '22 00:09

Manoj Govindan


use the csrf_exempt decorator for the view that is handling the request

from django.views.decorators.csrf import csrf_exempt
like image 27
Ashok Avatar answered Sep 27 '22 00:09

Ashok