开发者

Posting a form back with it's default values in the Django TestClient

开发者 https://www.devze.com 2023-04-05 21:46 出处:网络
I\'m writing some tests for some forms in Django. These forms change quite often so I\'m trying to avoid hard-coding the form parameters into my tests as because every time my form would change, I\'d

I'm writing some tests for some forms in Django. These forms change quite often so I'm trying to avoid hard-coding the form parameters into my tests as because every time my form would change, I'd have to modify the tests as well. I have quite a few forms of this nature. I'm mainly testing that the info开发者_如何学Crmation is stored properly in the correct tables without really bothering about each form field.

Using the Django TestClient, is there a way I could fetch the page with the form and then post it back with the default form field values filed in?

I've Googled around for this but to no avail.

An y help guys? Thanks.


I've had to do something like this before, and unfortunately there is no easy way to do it. The best I could come up with was to render the form, then parse the result with BeautifulSoup to get all the values of the inputs and selects. Something like:

from BeautifulSoup import BeautifulSoup
myform = MyForm()
rendered_form = myform.as_p()
soup = BeautifulSoup(rendered_form)
values = {}
for input in soup.findAll('input'):
    value = input.get('value')
    if value:
        values[input['name']] = value
for select in soup.findAll('select'):
    selected = select.find(selected='selected')
    if selected:
        values[select['name']] = selected['value']
0

精彩评论

暂无评论...
验证码 换一张
取 消