Giter VIP home page Giter VIP logo

sample-django-create-model's Introduction

Create Model in Django

Open-source sample that explains how to create a Django Model. All commands used to code the project and also the relevant updates are listed below. For newcomers, Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel.

For support and more Django Samples join AppSeed.


Chech Python Version

$ python --version
Python 3.8.4 <-- All good

Create/activate a virtual environment

$ # Virtualenv modules installation (Unix-based systems)
$ virtualenv env
$ source env/bin/activate
$
$ # Virtualenv modules installation (Windows-based systems)
$ # virtualenv env
$ # .\env\Scripts\activate

Install Django

$ pip install django

Create Django Project

$ mkdir django-create-model
$ cd django-create-model

Inside the new directory, we will invoke startproject subcommand

django-admin startproject config .

Note: Take into account that . at the end of the command.


Setup database

$ python manage.py makemigrations
$ python manage.py migrate

Start the app

$ python manage.py runserver 

Create sample app

$ python manage.py startapp sample

Visualize the default SQL settings - config/settings.py

# File: config/settings.py (partial content)
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
...

Define a new model Books in sample application. The below changes should be added to sample/models.py:

# File: sample/models.py

from django.db import models                       

class Book(models.Model):                                 # <- NEW
    title            = models.CharField(max_length=100)   # <- NEW 
    author           = models.CharField(max_length=100)   # <- NEW
    publication_date = models.DateField()                 # <- NEW 

Update Project Configuration to use the new model - The sample application must be added in the project configuration to INSTALLED_APPS section.

# File: config/settings.py (partial content)
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sample'                        # <- NEW 
]
...

Tip - for a quick check over latest changes we can run check subcommand.

$ python manage.py check
System check identified no issues (0 silenced).  

Generate the SQL code

$ python manage.py makemigrations  # generate the SQL code
Migrations for 'sample':
  sample\migrations\0001_initial.py
    - Create model Book

Apply changes on database

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sample, sessions
Running migrations:
  Applying sample.0001_initial... OK

Use the model via CLI

Once the model is created we can use it via the Django shell

$ python manage.py shell
>>> 
>>> from sample.models import Book     # import the Book model in our context
>>> from django.utils import timezone  # used to provide the value for publication_date
>>>
>>> book1 = Book(title='The Adventures of Tom Sawyer', author='Mark Twain', publication_date=timezone.now() )
>>> book1.save()                       # save the new book

List all books (using the CLI)

$ python manage.py shell
>>> 
>>> from sample.models import Book
>>> Book.objects.all()
<QuerySet [<Book: Book object (1)>]>

We can see our new book retuned by the query. Let's improve the information that describe the object.


Django Model - add text representation of an object

To achieve this goal, we should define the __str__() method for the Book model

# File: sample/models.py

from django.db import models                       

class Book(models.Model): 
    title            = models.CharField(max_length=100) 
    author           = models.CharField(max_length=100)
    publication_date = models.DateField() 

    def __str__(self):       # <- NEW
        return self.title    # <- NEW

Let's restart the Django console and check the results:

$ python manage.py shell
>>> 
>>> from sample.models import Book
>>> Book.objects.all()
<QuerySet [<Book: The Adventures of Tom Sawyer>]>

Use the model via Admin Section

Django comes with an admin section our-of-the box that allows us to manage with ease all models defined in project. To manage the Book model in the administration console we need to create a superuser (aka the admin) and after register the Book model to be visible in the admin section.

Create the superuser

$ python manage.py createsuperuser
sername (leave blank to use 'sm0ke'): admin
Email address: [email protected]
Password: 
Password (again):
Superuser created successfully.

Register Book model to be visible in the admin section - Edit sample/admin.py as below:

# File: sample/admin.py

from django.contrib import admin

from .models import Book        # <- NEW

admin.site.register(Book)       # <- NEW

Authenticate as admin - http://localhost:8000/admin/

At this point we should see the Books model in the UI and able to execute CRUD operations.


Create Model Django - The Book model is visible in the admin interface.


Create Model Django - Books Model has all items listed by the admin interface.


Create Model Django - Item details defined by the Book model.


For support and more Django Samples join AppSeed.



Create Model in Django - Open-source Sample provided by AppSeed.

sample-django-create-model's People

Contributors

app-generator avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.