django questions

13 Most Asked Django Questions

Django is a Python-based open-source framework that is maintained by Django Software Foundation. It is mainly used for rapid development, pragmatic, maintainable, clean design, and secured websites and web applications. It is one of the most popular frameworks. So, today we will be checking out the 13 most asked Django questions.

13 Most Asked Django Questions

1. What is the difference between null=True and blank=True in Django?


null=True sets NULL (versus NOT NULL) on the column in your DB. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the DB.

blank determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True then the field will not be required, whereas if it’s False the field cannot be blank.

The combo of the two is so frequent because typically if you’re going to allow a field to be blank in your form, you’re going to also need your database to allow NULL values for that field. The exception is CharFields and TextFields, which in Django are never saved as NULL. Blank values are stored in the DB as an empty string ('').

A few examples:

models.DateTimeField(blank=True) # raises IntegrityError if blank

models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form

Obviously, those two options don’t make logical sense to use (though there might be a use case for null=True, blank=False if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)

models.CharField(blank=True) # No problem, blank is stored as ''

models.CharField(null=True) # NULL allowed, but will never be set as NULL

CHAR and TEXT types are never saved as NULL by Django, so null=True is unnecessary. However, you can manually set one of these fields to None to force set it as NULL. If you have a scenario where that might be necessary, you should still include null=True.

2. How to do a not equal in Django queryset filtering?


Maybe Q objects could be of help for this problem. They can be negated and combined much like normal python expressions.

Its working work pretty well:

>>> from myapp.models import Entry
>>> from django.db.models import Q

>>> Entry.objects.filter(~Q(id = 3))

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]

3. How to combine two or more querysets in a Django view?


Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won’t add further cost.

from itertools import chain
result_list = list(chain(page_list, article_list, post_list))

Using itertools.chain is faster than looping each list and appending elements one by one, since itertools is implemented in C. It also consumes less memory than converting each queryset into a list before concatenating.

Now it’s possible to sort the resulting list e.g. by date. The sorted() function conveniently accepts a generator and returns a list:

result_list = sorted(
    chain(page_list, article_list, post_list),
    key=lambda instance: instance.date_created)

If you’re using Python 2.4 or later, you can use attrgetter instead of a lambda.

from operator import attrgetter
result_list = sorted(
    chain(page_list, article_list, post_list),

Alternative Answer:

You can also try this:

matches = pages | articles | posts

It retains all the functions of the querysets which is nice if you want to order_by or similar.

Please note: This doesn’t work on querysets from two different models.

4. What is a “slug” in Django?


A “slug” is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. It is better to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

An example:

<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>

Now let’s pretend that we have a Django model such as:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

How would you reference this object with a URL and with a meaningful name? You could for instance use so the URL would look like this:

Or, you might want to reference the title like this: 46 Year Old Virgin

Since spaces aren’t valid in URLs, they must be replaced by %20, which results in:

Both attempts are not resulting in a very meaningful, easy-to-read URL. This is better:

In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -.

Also, see the URL of this very web page for another example.

Additional Answer:

The term “slug” has to do with casting metal—lead, in this case—out of which the press fonts were made. Every paper then had its fonts factory regularly re-melted and recast in fresh molds, since after many prints they became worn out.

Typographs had to compose the text of an article in a backward manner with lead characters stacked in a wise. So at printing time, the letters would be straight on the paper. All typographs could read the newspaper mirrored as fast as the printed one. Therefore the slugs, (like snails) also the slow stories (the last to be fixed) were many on the bench waiting, solely identified by their first letters, mostly the whole title generally more readable. Some “hot” news were waiting there on the bench, for possible last-minute correction, (Evening paper) before last assembly and definitive printing.

Django emerged from the offices of the Lawrence journal in Kansas. Where probably some printing jargon still lingers.

5. How to check Django version?


Django 1.5 supports Python 2.6.5 and later.

If you’re under Linux and want to check the Python version you’re using, run python -V from the command line.

If you want to check the Django version, open a Python console and type

>>> import django
>>> django.VERSION
(2, 0, 0, 'final', 0)

Alternative Answer:

Here is as an executable command:

$ python -c "import django; print(django.get_version())"

6. How to set up a scheduled job?


One solution is to do this:

1) Create a custom management command, e.g.

python my_cool_command

2) Use cron (on Linux) or at (on Windows) to run my command at the required times.

This is a simple solution that doesn’t require installing a heavy AMQP stack. However, there are nice advantages to using something like Celery. In particular, with Celery it is nice to not have to spread your application logic out into crontab files. However, the cron solution works quite nicely for a small to medium-sized application and where you don’t want a lot of external dependencies.

In the later versions of windows, the at command is deprecated for Windows 8, Server 2012, and above. You can use schtasks.exe for the same use.

This the link of Django doc for writing the custom management command.

Additional Answer:

Celery is a distributed task queue, built on AMQP (RabbitMQ). It also handles periodic tasks in a cron-like fashion (see periodic tasks). Depending on your app, it might be worth a gander.

Celery is pretty easy to set up with django (docs), and periodic tasks will actually skip missed tasks in case of downtime. Celery also has built-in retry mechanisms, in case a task fails.

7. How to filter for empty or NULL names in a queryset?


You could do this:


If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:


Chaining these methods together basically checks each condition independently. In the above example, we exclude rows where alias is either null or an empty string, so you get all Name objects that have a not-null, not-empty alias field. The generated SQL would look something like:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

You can also pass multiple arguments to a single call to exclude, which would ensure that only objects that meet every condition get excluded:

Name.objects.exclude(some_field=True, other_field=True)

Here, rows in which some_field and other_field are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

Alternatively, if your logic is more complex than that, you could use Django’s Q objects:

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

For more info see this page and this page in the Django docs.

8. How to capture url parameters in request.GET?


When url is like: domain/search/?q=haha, Then you would use request.GET.get('q', '').

q is the parameter you want, And '' is the default value if q isn’t found.

However, if you are instead just configuring your URLconf, Then your captures from the regex are passed to the function as arguments (or named arguments).

Such as:

(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),

Then in your you would have

def profile_page(request, username):
    # Rest of the method

Additional Answer:

Let’s suppose you have

  • the rule url(regex=r'^user/(?P<username>\w{1,50})/$', view='views.profile_page')
  • a in incoming request for http://domain/user/thaiyoshi/?message=Hi

The URL dispatcher rule will catch parts of the URL path (here "user/thaiyoshi/") and pass them to the view function along with the request object.

The query string (here message=Hi) is parsed and parameters are stored as a QueryDict in request.GET. No further matching or processing for HTTP GET parameters is done.

This view function would use both parts extracted from the URL path and a query parameter:

def profile_page(request, username=None):
    user = User.objects.get(username=username)
    message = request.GET.get('message')

As a side note, you’ll find the request method (in this case "GET", and for submitted forms usually "POST") in request.method. In some cases it’s useful to check that it matches what you’re expecting.

Update: When deciding whether to use the URL path or the query parameters for passing information, the following may help:

  • use the URL path for uniquely identifying resources, e.g. /blog/post/15/ (not /blog/posts/?id=15)
  • use query parameters for changing the way the resource is displayed, e.g. /blog/post/15/?show_comments=1 or /blog/posts/2008/?sort_by=date&direction=desc
  • to make human-friendly URLs, avoid using ID numbers and use e.g. dates, categories and/or slugs: /blog/post/2008/09/30/django-urls/

9. How to create a JSON response using Django and Python?


Do as shown below:

import json

from django.http import HttpResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'

Pre-Django 1.7 you’d return it like this:

return HttpResponse(json.dumps(response_data), content_type="application/json")

For Django 1.7+, use JsonResponse like so :

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

Alternative Answer:

New in Django 1.7

You could use JsonResponse objects.

from the docs:

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

10. How to reset the Django admin password?


Use the following code:

python changepassword <user_name>

See docs

Additional Answer:

  1. python createsuperuser will create another superuser, you will be able to log into admin and remember your username.

To give normal user privileges, open a shell with python shell and try:

from django.contrib.auth.models import User
user = User.objects.get(username='normaluser')
user.is_superuser = True

11. In a Django form, how to make a field read-only (or disabled) so that it cannot be edited?


Django 1.9 added the Field.disabled attribute:

The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.

With Django 1.8 and earlier, to disable entry on the widget and prevent malicious POST hacks you must scrub the input in addition to setting the readonly attribute on the form field:

class ItemForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and
            self.fields['sku'].widget.attrs['readonly'] = True

    def clean_sku(self):
        instance = getattr(self, 'instance', None)
        if instance and
            return instance.sku
            return self.cleaned_data['sku']

Or, replace if instance and with another condition indicating you’re editing. You could also set the attribute disabled on the input field, instead of readonly.

The clean_sku function will ensure that the readonly value won’t be overridden by a POST.

Otherwise, there is no built-in Django form field which will render a value while rejecting bound input data. If this is what you desire, you should instead create a separate ModelForm that excludes the uneditable field(s), and just print them inside your template.

12. How to get value from form field in Django framework?


Using a form in a view pretty much explains it.

The standard pattern for processing a form in a view looks like this:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...

            print form.cleaned_data['my_form_field_name']

            return HttpResponseRedirect('/thanks/') # Redirect after POST
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,

13. How to get the full/absolute URL (with domain) in Django?


Use handy request.build_absolute_uri() method on request, pass it the relative URL and it’ll give you full one.

By default, the absolute URL for request.get_full_path() is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.

Alternative Answer:

If you want to use it with reverse() you can do this : request.build_absolute_uri(reverse('view_name', args=(, )))

In Conclusion
These are the 13 most commonly asked Django questions. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.
We, at Truemark, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.
Hope this article helped you.

Leave a Reply

Your email address will not be published. Required fields are marked *