Configure PyCharm for Python/Django and Introduction to Django Rest Framework

Srijan Anand
7 min readApr 7, 2018

--

Working on a Django Project without a good support from an IDE could be a real pain. PyCharm is the most loved of all. Is has lots of features out of the box making your development process faster and efficient.

We’ll have a quick walkthrough to configure your development environment so that you can get the most out of PyCharm. Also, we’ll go through the basics of Django Rest Framework.

Prerequisites:

  • You must have PyCharm Professional version as the Community version doesn’t have much advanced features. You can get a free education license if you are a student.
  • Knowledge of Python/Django is recommended but not mandatory. We will start by setting up a new Django project.

Creating Django Project

  1. Open PyCharm Professional and click on Create New Project.
PyCharm Professional

2. Choose Django on the left (this is something people usually forget). Now, select your project’s Base Directory. Don’t try to play with Project Interpreter yet. We’ll set it up later.

Select Project Directory

3. Click on More Settings and it’ll give some other useful options. Make sure you checked Enable Django Admin. Also, type in your Application Name.

PyCharm App Settings

4. Click on Create and PyCharm will create your Django App for you.

Django App in PyCharm

Creating Virtual Environment

5. Go to File -> Settings and select Project Interpreter. On the right of Project Interpreter, click on the settings symbol and select Add.

Project Settings

6. Select New environment and choose Location for the environment and your Base interpreter as your Python version (I am using Python 3.6) and click OK.

Virtual Environment Setup

7. You’ll be redirected back to the settings menu. Now, select Show All from the right settings symbol.

Select Show All

8. This will give you a list of Virtual Environments. Select the one you created earlier and click OK.

List of Virtual Environments

Starting Django App Server

9. Let’s witness the power of Terminal inbuilt in PyCharm. Click on the Terminal tab below and you’ll see that the virtual environment is already activated . Its time to install Django using pip. Run pip install django.

Install Django inside Virtual Environment

10. Now go to Tools -> Run manage.py Task… Here you can run all the manage.py commands just by typing in their [options]. Run makemigrations inside manage.py@YourApp.

Manage.py Task Makemigrations

11. Now run migrate to create schema in your SQLite database.

Manage.py Task Migrate

12. Press the play button on the top to start your server. This is same as running python manage.py runserver.

Run Django Server

13. Open localhost in your browser to see your working demo app.

Demo App

14. Now, let’s run the app in PyCharm’s Debug Mode by pressing the bug symbol on the top.

Click on Debug

Introduction to Django Rest Framework

15. Install Django Rest Framework. Run pip install django-rest-framework.

Install Django Rest Framework inside Virtual Environment

16. Don’t forget to add ‘rest_framework’ in the list of installed apps in settings.py

Add to installed Apps

17. Create a Tech Model in models.py.

Models.py

from django.db import models

# Create your models here.


class Tech(models.Model):
short_name = models.CharField(max_length=10)
name = models.CharField(max_length=200)
models.py

18. Create a file named serializer.py inside your app directory and make a model serializer.

Serializer.py

from rest_framework import serializers
from .models import Tech


class TechSerializer(serializers.ModelSerializer):

class Meta:
model = Tech
fields = '__all__'
serializer.py

19. Now, write two class-based views inside views.py. One returns a list of all the entries and the second returns a single entry.

  • List API View —Inherit from this class to list all the entries. Also, you can use this view to create a post function that will allow creating a new entry in the database.
  • API View — Inherit from this class if you want to perform CRUD operations (Create, Read, Update and Delete). I used this class to read and delete entries from the database.

Views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.generics import ListAPIView
from .models import Tech
from .serializer import TechSerializer
# Create your views here.


class AllTech(ListAPIView):

queryset = Tech.objects.all()
serializer_class = TechSerializer

def post(self, request, format=None):
serializer = TechSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class TechView(APIView):

def get(self, request, pk, format=None):
try:
tech = Tech.objects.get(pk=pk)
serializer = TechSerializer(tech)
return Response(serializer.data)
except:
return Response(status=status.HTTP_404_NOT_FOUND)

def delete(self, request, pk, format=None):
tech = Tech.objects.get(pk=pk)
tech.delete()
return Response(status=status.HTTP_200_OK)
Views.py

20. Now add routes for your views in urls.py. Note that now we don’t have a URL function instead we have path and re_path in Django 2.0.

Urls.py

from django.urls import path, re_path
from django.contrib import admin
import Test_App.views as test_app

urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'', test_app.AllTech.as_view()),
re_path(r'(?P<pk>\d+)', test_app.TechView.as_view()),
]
urls.py

21. Start your server in Debug mode again and visit your localhost in your browser to see Django Rest List API view. Add some test entities.

Django Rest View

22. Entities will be added to list view as shown.

List View

23. Now go to the Object View to get a single entity with its id.

Connect your Database to PyCharm

24. Let’s configure your database with PyCharm so that you’ll have a watch over your data. Click on the Database tab on the right and press Alt+Insert. Select Data Source -> SQLite ( Choose the database which is connected to your project but obviously you can connect to any database you want)

Connect Database in Pycharm

25. Choose the location of SQLite file.

Select you database file (for SQLite)

26. Click on Test Connection to verify their are no errors. Click OK if the test was successful.

Click on Test Connection

27. Now you can view the schema of your database and view the tables as well.

Schema View

Making a Debug Point

28. Let’s test the debugging skills of PyCharm. Make a debug point by clicking on just right next to the line number. I have made a debug point inside delete method so this method will get paused at the debug point. Run your server in Debug mode again.

Debug Point

29. Go to TechView url and delete any entity. (Remember you have to open API View url and not the List View as we wrote our delete method inside TechView)

30. You’ll be redirected to PyCharm automatically as soon as the flow reaches the debug point.

Look at the window below. Its the most helpful window for debugging. It gives you all the info of variables and change in the value of those variables as the flow of code continues. Click on Step Over button (down symbol) to go the next line of code.

Debug Mode

31. As you press Step Over the debugger state moves to the next line of code. Notice the added variables including tech. Now, click Resume Program button (next button) to move onto the next Debug point. As we placed only one Debug point, the program will finish execution.

Debug View

Creating Django Applications on PyCharm is really fun and many Django Developers already use it. Try it out and give your thoughts in comments.

--

--

Srijan Anand
Srijan Anand

Written by Srijan Anand

Senior Backend Dev @ Valiance Solutions, Noida

Responses (3)