Django: How to remove fields from a Form

Let’s say you want to inherit from the following form: class SuperLongForm(forms.Form): first_name = … last_name = … … And that you want to recreate the same form, but without the last_name field. All you have to do is to remove the field from the fields dict: class FirstNameOnlyForm(SuperLongForm): def __init__(self, *args, **kwargs): super(FirstNameOnlyForm, self).__init__(*args, […]

Django unit tests: How to populate request.raw_post_data

If you are creating unit tests with Django, you might need to send raw data with the Client object. In the example below, we are testing how our view reacts to a raw POST string sent by another API. The string in question is myrawpoststring. All you need to do is set the data attribute […]

How to run Django in a command line terminal

Let’s say, for example, that you want to manually add certain objects without using the admin, or need to quickly check a function without creating unit tests for it. In that case, you will need to run Django-specific commands from a python shell. If you import django or use shell, you will probably hit […]

How to redirect views in Django

If you wish to redirect a URL to another in Django, there is a simple way to do it using generic views. This method is far simpler than writing a custom view, as it doesn’t require you to write anything in In this example, we are redirecting the root URL, /, to /dashboard. In […]

Integrating Django forms with Twitter Bootstrap

With this template, you will be able to use Twitter Bootstrap with your Django forms. In this example, we assume our form is in the form variable. <form class=”form-horizontal” action=”” method=”POST” {% if form.is_multipart %}enctype=”multipart/form-data”{% endif %}> {% csrf_token %} {{ }} {% if form.errors %} <div class=”alert alert-error”> <ul> {% for error in […]