pycharm django breakpoint

PyCharm – Django Debugger Won’t Stop At BreakPoints

Debugging a Django project in PyCharm is actually quite easy. All you need to do is add couple of breakpoints and hit that little debug button you see at the top right corner of the IDE. Now when you run your app, PyCharm’s Django debugger should stop at those breakpoints, right?

django-debug-button

Nope, not that straightforward.

Breakpoints that won’t stop the debugger

Check out the lines below for example. I first put breakpoints on these 2 lines but the debugger would not hit any of them:

invalid-breakpoints-pycharm-django

This one stops the debugger

Then I added 1 more breakpoint and voila. Debugger stops now.

valid-breakpoint-pycharm-django

Suspend

You see. Not all the breakpoints will make the debugger stop there. But why? Why did it not stop at my breakpoints? The answer was simple.

Click Run -> View Breakpoints…

run-viewbreakpoints-pycharm

Now I see the Breakpoints window. Clicking through my breakpoints I realise that for the ones that debugger won’t stop at, the Suspend checkbox is not selected.

django-breakpoints-window

Coming from other IDEs you might assume (like I did) that putting a breakpoint would by default mean that the debugger would stop there but for PyCharm 2016.21994 this is not the case. Your breakpoints not only need to be enabled but also need to be marked as Suspend.

Hope this helps.
Good Luck,
Serdar

clone virtual environment django

Django – How to Clone a Virtual Environment

I wanted to write 1 more post in 2016 before the year ends. So, here it is 🙂 Let’s talk a little more about Virtual Environments.

If you have a virtual environment you can back it up and re-create it later with the exact same installations in it. No need to worry about what and which versions were installed.

clone virtual environment django

Actually, what we will do is not cloning the Virtual Environment, it is just exporting the configuration of it (as I said this includes the installation and version info) which can be used later in a brand new Virtual Environment to make it an exact same copy of this exported one.

FREEZING & INSTALLING

This export of installation configurations is called “freezing”. Below is how you can do it in console.

First activate your virtual environment. Then type below:

Above line will create a text file whose content will be something like this:

If in the future you want to re-create this Virtual Environment all you need to do is open a console, activate your newly created Virtual Environment and type the below line:

 

Hope this helps.
Good Luck,
Serdar

javascript error undefined

Cannot read property ‘toLowerCase’ of undefined

I am finally back with another post after a while. I had this time period where I got busy with other things in life and felt a little tired for coding and blogging. That seems to be over now. Thank you my little angel. 🙂

Today I was working on my Django project and had this annoying error in my javascript code. My code kept saying Cannot read property ‘toLowerCase’ of undefined but why? What was happening?

Apparently the problem was with the context of the function I was calling and the meaning if “this” parameter inside that function.

I was trying to invoke a function attached to the “onchange” event of a select control. I was attaching the function to the event “inline” as below:

Nothing wrong with that. The problem was that the function “myFunction” was defined in the scope of the page and I was using “this” in that function as if it referred to the select control itself while it was actually referring to the page.

Wrong:

Correct:

Instead of using “this”, I passed a parameter to myFunction and built the id of my select control to use it instead of “this”. The problem was gone.

If you are seeing the same error message you might have a similar problem in your code.

Hope this helps.
Good Luck,
Serdar

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