본문 바로가기

프레임워크/Django

As a Beginner, going through Django Rest Framework tutorial: #1

Recently, I happened to start on a project to which I choose to use Django for the backend development. Any reason? Nah... I just felt like it, probably it was because Python was the one I was familiar with the most. In fact, this is my very first project as a developer in my life. Anyway, let's get to the point. I decided to write a series of posts about me as a newbie going through the official DRF tutorials and this is the very first one. Well, let's get started.

Preparations: 1. Project creation and settings

Nothing special here. Just copy and paste what's given.

django-admin startproject tutorial
cd tutorial
# manage.py must be there
python manage.py startapp snippets

# Add the following in
# tutorial/settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'snippets.apps.SnippetsConfig',
]

Preparations: 2. Create views and serializer Classes

It is rather bulky but I will copy and paste anyway in case someone doesn't want to bother to visit the official website but is willing to bother relying on me.

# tutorial/snippets/models.py
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])


class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

    class Meta:
        ordering = ['created']

Let's create a database for the model Class we just created.

# turorial/
python manage.py makemigrations
python manage.py migrate

Get in the Python shell

python manage.py shell

and do the following

from snippets.models import Snippet
# from snippets.serializers import SnippetSerializer
# from rest_framework.renderers import JSONRenderer
# from rest_framework.parsers import JSONParser

snippet = Snippet(code='print("hello, world")\n')
snippet.save()

Note that I commented out three lines of imports from the office tutorial as they are not needed yet and so far there is no DRF element involved, i.e., pure Django. Bascially, we created a Snippet instance called snippet with the arugment, code='print("hello, world")\n'. However, I found no __init__ in Snippet. So the given argument, code='print("hello, world")\n', must get passed to superclasses somewhere. In the source code, base.py, from the Github repository to Django, I found Class Model in which __init__ is defined as below:

# django/db/models/base.py
def __init__(self, *args, **kwargs):
    ...
    ...
    super().__init__()
    ...

super().__init__() is not called without any arguments passed either. Therefore, I reckon the argument, code='print("hello, world")\n', must be dealt with in Class Model somehow; how exactly I did not look into.

By the line snippet.save(), moreover, the Snippet instance was saved in the database. I found the save method in Class Model as well. Let's check if save did save the instance in the DB. First, we need to create a superuser account as below:

cd <some path>/tutorial # where manage.py is
python manage.py createsuperuser

After this, the following needs to be updated to make the Snippet model appear in admin GUI.

# snippets/admin.py
...
from .models import Snippet

admin.site.register(Snippet)
...
python manage.py runserver

and go to localhost:8000/admin and check out the snippet database if there is an entry we created in the Python shell. I confirmed the new entry appears in the admin GUI.

'프레임워크 > Django' 카테고리의 다른 글

As a Beginner, going through Django Rest Framework tutorial: #2  (0) 2020.06.23
Django http  (0) 2020.06.06
장고 모델  (0) 2020.06.06
장고 (Django)  (0) 2020.06.06