Skip to content

django rest framework

RaoufCherif edited this page Mar 7, 2023 · 3 revisions

Les étapes pour créer une app django rest framework.

Create the project directory

mkdir tutorial
cd tutorial

Create a virtual environment to isolate our package dependencies locally

  python3 -m venv env
 source env/bin/activate  # On Windows use `env\Scripts\activate`

install package requirements.

  pip install django
  pip install djangorestframework
  pip install pygments

starting a project

django-admin startproject my_projetc cd my_project

Create an app that we'll use to create a simple Web API.

python manage.py startapp snippets

We'll need to add our new snippets app and the rest_framework app to INSTALLED_APPS. Let's edit the my_project/settings.py file:

INSTALLED_APPS = [ ... 'rest_framework', 'snippets', ]

Creating a model to work with

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']