Login

Snippets by theju

Snippet List

External service Test Client

The inbuilt test client can be used to only test single domain applications ie no support for supplying absolute URLs. But there are cases where one might like to test against URL rewrites, external domains/services like OpenID, OAuth etc. This client has an external dependency on httplib2, to maintain the sessions (cookie-based). The API is exactly similar to the inbuilt test client. >>> from client import TestClient >>> c = TestClient() >>> resp = c.get("http://www.google.com/") >>> resp.status_code 200 **Note**: Unlike the built-in test client, this test client cannot access the template and context attributes from the response even if testing a local application.

  • test
  • client
  • httplib2
Read More

Prevent form tampering of hidden fields

Sometimes, we need to pass hidden fields with an initial value in forms but cannot trust the returned values because it could have been tampered. So here is a form that adds an additional 'hidden' field (called 'form_hash') that hashes all the initial value of hidden fields and checks for tampering. Pretty straightforward to use.

  • forms
  • hidden
  • tampering
Read More

SplitTimeField

The SplitTimeField and the corresponding widget SplitDateTimeWidget show two select boxes with one for hour from 0 to 23 and the other showing minutes 0,15,30 and 45 (can be customized very easily). Usage: ------- class TestForm(forms.Form): start_time = SplitTimeField(widget=SplitTimeWidget) end_time = SplitTimeField(widget=SplitTimeWidget)

  • forms
  • field
  • widget
Read More

Pagination for date-based views

Date-based generic views do not provide pagination by default but Django is very extensible. It provides a Paginator that takes care of pagination. Since date based views usually order by descending order ie from latest entry to the oldest, I used a queryset to order the items (on a field called 'date_pub') and then pass this queryset to the paginator which takes care of the pagination.

  • views
  • date
  • pagination
Read More

theju has posted 4 snippets.