Telling if a field is required in Django templates

If you want to tell whether a field in a template is required, use form.myfield.field.required as in the example below:

{% for field in form %}
    <label for="{{ field.id_for_label }}">
        {{ field.label }}
        {% if field.field.required %}*{% endif %}
    </label>
    {{ field }}
    {{ field.errors }}
{% endfor %}

In this example, there will be an asterisk next to the required fields.

Diagnosing a bad ping

Once in a while, you will deal with an unbearably long ping time. Calling your ISP might solve the problem after a few minutes of trial and error, but it’s usually after spending a few hours on the phone. Here is a short list of things you should check before calling:

Step 1: Gathering data

First, let’s see whether it’s you or the ISP:

  1. Look at your ISP’s Twitter and status page. It’s a low effort way to see if other people are having the same issue.
  2. Reboot your modem and router and try plugging your computer to the modem directly. Sometimes, it’s the simple stuff.
  3. Check your ping immediately after rebooting your router and modem. In a recent case, the ping was fast for a minute or two after rebooting, then slowed to a crawl. A service on my server was hogging my bandwidth as soon as it had internet access.
  4. Ping from different devices. If you can get a good ping on a wired device but not on a wireless one, it might be a signal problem.
  5. Check your router’s status page. If you run DD-WRT, you can see the bandwidth usage and connection strength. In a recent case, I could see that a wired device was hogging the bandwidth.

Step 2: Common culprits

If you have figured that the problem is on your side, here are some common problems to look for.

  1. Check your torrents. If your upload rate matches that of your internet connection, it can slow the internet down to a crawl. Don’t forget to convert kilobytes to kilobits when comparing.
  2. Check your services. If you are running services (VPN, proxy, web server, SSH etc), check if they are being attacked or used without consent. I once foolishly ran a public proxy that somehow made its way onto a public proxy list and it killed my router after a few minutes. The Apache access logs, among other things, might provide some information.
  3. Check your other computers. On OS X, use the Network tab in Activity Monitor to spot bandwidth hogs. The Windows task manager offers similar functionality.

Specifying a port when connecting with SSH

Some servers run their SSH server on a different port than 22 for a variety of reasons, including security.

To specify a custom port when connecting, use the -p flag as in the example below:

ssh user@server.com -p 2222

In this example, the client would attempt to connect using port 2222.

Fix garbled file names in SMB shares

If you have files in your SMB networked folders that look like this: TRZB4~J.mp4, there is a very easy fix to get the original file names.

Open your smb.conf file (usually at /etc/samba/smb.conf) and add the following line under [global]:

mangle case = no
mangled names = no

Once this is done, enter the following command in your terminal:

sudo service samba2 restart

Names are mangled to make them compatible with older operating systems, but this absolutely shouldn’t be a problem that you will face at home.

Following redirects with the Django test client

When running unit tests with in Django, the test client’s default behaviour is to stop at the first response, even if that response is a redirect.

If you want the client to follow these redirects and return the last page, perform your requests like this:

response = c.get('/redirect_me/', follow=True)

This will also add response.redirect_chain so you can see which URLs it followed before getting to the final page. Here is a sample redirect_chain:

[(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]

Euclidean algorithm in Python

While it won’t really be useful to most people, here’s how you implement the Euclidean algorithm in Python.

b = 13
a = 18

while b > 0:
    if a>b:
        a = a-b
    else:
        b = b-a

print "The GCD is:"
print a or b

Ping once and return true/false

The ping command will usually try pinging a device forever, returning the response time after each pingback. If you want to ping a device once and use the answer to perform an action, use the following snippet:

ping -c 1 [your ip or hostname] > /dev/null

This command will either return 1 on failure or 0 on success.

In the example below, we use the && operator to perform an action if and only if the ping to “homeserver” was successful:

ping -c 1 homeserver >/dev/null && echo 'Successfully pinged device!'

This can be a great way to monitor the presence of a device on the network for a dead man’s switch for example.

Print preview significantly different from Inspector in Chrome?

Are you having issues with the Chrome print media emulator showing different results from print preview? Here’s how I solved this problem.

In the emulator, my styles were showing just fine, but despite all the !important rules in the world, nothing would work in print preview. It turns out the print preview will display your page before CSS transitions are applied, so if there’s a transition when some elements are moved, print preview will show them before that transition. This is especially tricky if you use CSS transitions for columns, responsive design, slide out menus etc.

Adding *{transition:none!important} in the print stylesheet fixed it for me.

What is Cross-Site Request Forgery (CSRF)?

Following the previous “you should know” introductions about SQL injection and XSS injection, here is a short introduction to CSRF. I’ll quickly define it with a few examples, then provide solutions to avoid it.

CSRF (or XSRF) is an exploit where a malicious application transmits unsolicited requests to another web application in the name of an unsuspecting user.

For example, a malicious website could exploit on your application by putting an image with http://yourapp.com/transferCredits?amount=1500&to=hacker as the source on the page. If an unsuspecting visitor loads the image and is also connected to yourapp.com, he would unknowingly transfer 1500 credits to the hacker.

<p>
    This image on maliciouswebsite.com would silently
    delete a connected user's account on importantsite.com

    <img src="http://importantsite.com/api/account/delete">
</p>

Click jacking is a similar exploit. A malicious website could move an invisible Like button right under your mouse as you are about to click, making you Like a Facebook page without your consent.

Unlike XSS and SQL injections, you might not notice when a CSRF attack takes place, since it will look as a legitimate request.

Preventing CSRF

Using POST for requests with side-effects (creating, updating or deleting records) instead of GET will already help make your application safer.

To prevent CSRF, you need to verify that the request comes from a legitimate user. This can be achieved by emitting a unique token when serving the page that would normally call an action. When you receive a request, you verify that a valid token was supplied with that request. This is the approach most frameworks take.

Alternatively, you can verify the Origin and Referer headers to make sure that the request comes from your own site.

If you use Django, you are required by default to use CSRF tokens for POST requests with side-effects.

As usual, OWASP has an excellent guide about preventing CSRF.

.find() vs. .children(): which one should you use?

jQuery offers two functions to find children in an element: .find() and .children(). .find() will look through all children of an element while .children() will only look at immediate children.

<ul>
    <li>
        <p></p>
    </li>
    <li>
        <p></p>
    </li>
    <li>
        <p></p>
    </li>
</ul>

In the snippet above, $('ul').children('p') wouldn’t return anything, while $('ul').find('p') would return all three paragraph blocks.

In terms of performance, .find() is faster than .children() in most cases, since it uses native browser methods instead of JavaScript.

Here is a performance test that compares .find() and .children().