ajax-in-django

How to perform an Ajax request in Django

Ajax request are everywhere in modern web applications. No matter which platform you are using for development, the main scheme is always the same. You send a request to a server side method using JavaScript, jQuery etc. and server processes the request, prepares the response and sends this response to client (browser). Finally, response is received and processed by the client-side code (script) and dynamically generated content is displayed to the users.

Flow is the same in Django. So, what we need to implement here?

1- We need a view function to receive and handle the request

2- We need a mapping in urls.py file to map the request url (which will be specified in the requesting client-side jQuery script) to the view function in 1

3- We need the client-side script to make the request to the url in 2 and handle/render the response

Let me clarify by some simple code snippets.

1- Sample view function:

Here we convert the resulting dictionary into a JSON object and return it as an HttpResponse.

2- Sample mapping in urls.py:

3- Sample jQuery script to send the request and get/render the response:

Hope this helps.
Good Luck,
Serdar

django-list-comprehensions

Python – Single Line For Loops (List Comprehensions)

In Python there is a very simple and elegant way of defining a for loop in a single line. Thing is, not only can you define this for loop but you can also use the values in this loop to create new lists/ tuples etc. In Python, we achieve this through the use of a concept called List Comprehensions. List Comprehensions can be used to construct lists in a very natural, easy way, like a mathematician is used to do.

Here the List1 is [0, 1, 4, 9, 16, 25, 36, 49, 64, 81], List2 is [0, 4, 16, 36, 64]. As you can see in the case of List2, we can also use conditions in List Comprehensions.

We could also do something like below:

In the above real-life example we create a list of tuples in the first line, then we feed this list(items) to a ChoiceField control in Django to display the selectable options. Just in a single line. Very easy, very practical.

Hope this helps.
Good Luck,
Serdar

django-forms

Django – Adding a Form to Your Django Site

In your Django website you have models. These models represent tables in your database. So, what would you do if you wanted to record new model data into your DB? How would you get user input? Of course, using forms.

There is an impractical way to do this but let’s skip that and show the better method of adding a form to your Django site.

First, create “forms.py” file in your project if you don’t already have it. I had to create this file myself since my Django project template (created by PyCharm) didn’t have it by default.

Your forms.py file will simply be something like this:

Here we have to import our Item class since we are referring to it from our form class. Our form class “AddItemForm” inherits from “forms.ModelForm” class. By inheriting from this class, we can easily tell Django which model’s data we will be submitting using this form. Of course, for Django to know the model class we are preparing the form for, we need to use “Meta” class and specify which model this form will be for and which fields will be input through the form fields. See how I define the “Meta” class above.

Once we are done with forms.py, we can modify our urls.py and views.py.

URLS.py

In your urls.py you need to specify a url pattern that resolves to a view which loads your form. It could be something like this:

VIEWS.py

In views.py you need to add a new view “def” for “view_add_item” like below:

See add_item.html here? That is our template file which will be rendered once a request to “mysite.com/add_item” is received. Here we are passing the context {‘Form’: form} to add_item.html template. Which means add_item.html template has a reference for “Form” and it will be replaced by this instance of “form”.

add_item.html could look like this:

Details of this template is not the subject of this post but I can say add_item.html extends base.html. This is subject of another post about template inheritance. Here Form.as_p means display this form’s fields as paragraphs, each field and label in its own line.

Hope this helps.
Good Luck,
Serdar

django-capture-arguments-in-urls

Django – Capture Arguments in URL Patterns and Pass Them to View Functions

As you already know when a request comes to your Django site, it first looks for the url patterns of your site and once a patter is matched related view function is called passing some arguments to that function.

But how do you catch those arguments? How do you know which arguments you are sending to your view functions?

First things first. To capture a parameter in a regex url pattern in your urls.py file, you surround the part of your regex you want to match and capture with parenthesis.

Let’s say you have the line below in your urls.py file:

And let’s say you have the below view function in your views.py file (details of the function is not important right now):

Here “request” is Http Request that goes for every view function. What we do here is we surround (.*) part of the regex and capture its value in the url for the incoming request (if we have a match). Then this captured value is provided to “category_view” function as the value for “my_category_name” parameter.

Keyword Arguments and Positional Arguments

A Python function can be called using keyword arguments, named arguments and sometimes both, and so there are 2 ways to capture and pass parameters in url patterns to view functions.

Capturing and Passing by Position

This way you specify no name for the values you are capturing. Captured values are passed to view function by the order they are captured.

Here /articles/2006/03/ request would result in this function call: view_archive(request, ‘2006’, ’03’).

Capturing and Passing by Name

Here you specify a name for each parameter you capture. You specify the parameter name using ?P<param_name>.

Here/articles/2006/03/ request would result in this function call: view_archive(request, year=’2006′, month=’03’).

Hope this helps.
Good Luck,
Serdar

django-difference-filter-get

Django – Difference Between Filter and Get

For the new comers Django’s Get and Filter functions may be consuming when it comes to decide which one to use. The primary difference between the two is Get will return exactly one object while Filter will return a query object even if the result set contains only a single object.

GET

Returns the object matching the given lookup parameters, which should be
in the format described in Field lookups.

get() raises MultipleObjectsReturned if more than one object was found.
The MultipleObjectsReturned exception is an attribute of the model
class.

get() raises a DoesNotExist exception if an object wasn’t found for the
given parameters. This exception is also an attribute of the model class.

FILTER

Returns a new QuerySet containing objects that match the given lookup parameters.

You can query this QuerySet again and again applying different filters.

Use GET when you want to fetch a single unique object, and FILTER when you want to get all objects that match your specific lookup parameters.

Hope this helps.
Good Luck,
Serdar

django related_name

Django – How to Make Queries and Retrieve Objects – Part 2

Field Lookups

Field Lookups are where you actually specify the “where” clause of your SQL query.

Here I have used the __lte lookup to find the books that were published in and before 2010.

Here I have used __exact lookup to find the book whose title is “guide to the galaxy”. If you don’t provide a lookup type – that is, if your keyword argument doesn’t contain a double underscore – the lookup type is assumed to be exact. For a case-insensitive match use __iexact lookup.

Another common lookup type is __contains. There is also __icontains which is as you can imagine the case insensitive version of __contains lookup.

__startswith, __endswith, __istartswith, __iendswith are other common lookup types you will find yourself using a lot.

Here you can find a list of most used Field Lookups.

Lookups that Span Relationships

Consider this model structure below:

To retrieve Entry objects whose blog name contains ‘webmaster’ you can use the lookup below:

Note that ‘i’ here stands for case insensitive lookup.

We can also perform a reverse lookup. Line below retrieves Blog objects that which have at least one entry whose title contains ‘scripting’:

Multi-valued Relationships

Everything inside a single filter() call is applied simultaneously to filter out items matching all the requirements.

Here this part is just a little bit tricky. Below are 2 examples. In the first example, we are querying for the Blog objects that contain Entries which contain ‘webmaster’ in their titles AND which were published in 2016. Satisfying both criteria at the same time. In the second example we are querying for the Blog objects that include Entries with ‘webmaster’ in their titles as well as Blogs with Entries that were published in 2016.

1-

2-

See the difference?

This is the end of Part 2.

Hope this helps.
Good Luck,
Serdar

django related_name

Django – How to Make Queries and Retrieve Objects – Part 1

Django provides you with a database abstraction layer (or an API) that lets you perform CRUD operations without writing a single line of SQL. In this post I will talk about how we can retrieve objects using this API.

We retrieve objects of models as query sets. To create a query set you need to use the manager for that particular Django model. This manager is called “objects” by default.

To give an example below is how you can query for all the Book objects in your database. This will return a query set that contains all the Book objects and assign it to “books” variable:

Retrieving Specific Objects with “Filter”

To retrieve a subset of objects we will use “filter” conditions. You can use filters as below:

Here we are retrieving books that were published in 2004. You can also do this as below:

There is also “exclude” method that you can use. As you can imagine, it excludes the objects meeting a specific criteria from the query set.

Chaining Filters

It is also possible to chain the filters to further refine the query set. Below is an example:

The query above will return the Book objects whose title contains ‘econ’ and that was published between January 30, 2010 and today. Here __startswith, __gte are field lookups.

Retrieve a Single Object with get()

“filter” always returns a query set, even if it contains only a single item. To retrieve a single item you can use get() method. You can use query expressions with get just like you do with filter. Example:

Here we are retrieving the book object whose primary key is equal to 1.

Limiting QuerySets

You can use Python’s array slicing notation to limit your resulting query set to a certain number of results and/or to a certain range of results.

The above result set will be composed of the first 5 Book objects while the below will give us the 6th through 10th Book objects:

To retrieve a single object you use a simple index as below:

This will return the first Book object in the database.

In part 2 we will look at Field Lookups.

Hope this helps.
Good Luck,
Serdar

django-install-package-virtual-env

How to – Install a Django Package Inside a Virtual Environment

You have created your Virtual Environment and PyCharm automatically associated it with you default project. Now you want to install packages into this Virtual Environment. Here is how you can do it.

First of all, activate your Virtual Environment. To do that, launch a terminal (Mac OS X), type this:

Here “.virtualenvs” is the directory in which you created your Virtual Environment, “MyVirtualEnv” is the name of your Virtual Environment. Once you type this and hit enter you will activate “MyVirtualEnv”. You will see (MyVirtualEnv) at the beginning of the prompt indicating you have activated your Virtual Environment. From now on any package you install using pip will be installed in this Virtual Environment.

Once you are done installing your packages you can type “deactivate” and hit enter to stop working on this Virtual Environment.

Hope this helps.
Good Luck,
Serdar

pycharm-virtualenvironment

How to – Create a Virtual Environment in PyCharm

Virtualenv tool is integrated in PyCharm (my version is 2016.1.4) so you can create and configure virtual environments right inside the IDE. “virtualenv” comes bundled with PyCharm so you don’t need to install it.

Follow the steps below to create a virtual environment in PyCharm:

Go to File -> Default Settings…

pycharm-default-settings

In the window that opens choose “Project Interpreter” on the left, click “…” button next to Project Interpreter dropdown on the top of this window and click “Create VirtualEnv”.

django-project-interpreter

In the window that opens enter a name for this Virtual Environment, select a location and base interpreter. If you want the site-packages of the base interpreter to be visible from the virtual environment, select the check box Inherit global site-packages. If you leave this check box cleared, the new virtual environment will be completely isolated.

Once this Virtual Environment is created, PyCharm starts using this Virtual Environment for your project. See the screenshot below:

Pycharm-project-interpreter-virtualenv

Hope this helps.
Good Luck,
Serdar

django-clear-migrations

Django – How to Clear All Migrations and Re-migrate

During your website development with Django, you will find yourself changing your models and migrating these changes to your database. Sometimes this will happen too often and you will encounter problems creating/applying your migrations. On some occasions you will feel the need to reset/clear all your migrations and re-create/re-apply them.

Below are the steps to clear all your Django migrations and re-migrate:

1- Delete everything in application’s “migrations” folder except for __init__.py
2- DELETE FROM django_migrations WHERE app = ‘app_name’;
3- Drop all tables associated with ‘app_name’.
4- Run makemigrations
5- Run migrate

Hope this helps.
Good Luck,
Serdar