Install Django and Create a Project Django.How

Author avatar wrote on 26/05/2022

Install Django

  1. Create a folder

  2. Open folder with Visual Studio Code

  3. (Only for first project) Open Terminal and run the code pip install pipenv (to install Django in a folder no all machine)

  4. type pipenv shell

  5. type pipenv install django

Create a project

  1. In terminal type django-admin startproject projectname

  2. change directory to projectname

  3. type python runserver 8081 8081 is a path I choose / default is 8000

  4. Quit the server with Ctrl+C

  5. type python migrate to migrate tables

Create App

  1. type python startapp polls polls is an example of app name

  2. go to the file polls(the app name)/ and declare your class

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

3. Go to your app folder and open then declare your app under INSTALLED_APPS

# Application definition


4. Create the migration, make sure in the terminal you are in the right folder and pipenv shell is running then type python makemigrations polls this will create the necessary python files

5. Make the complete migration to create the tables in the datbase by typing python migrate

Interacting with data using the shell

  1. Type python shell

  2. Import models from polls.models import Question,Choice

  3. To check the recored Question.objects.all() //will return <QuerySet []> because 0 records

Creating a record using the terminal

  1. we need time package, type from django.utils import timezone

  2. Create a record q = Question(question_text=”What is your favorite Python Framework?”,

  3. Then save it

  4. Now you can get its info or q.question_text

  5. You can also try to use filter Question.objects.filter(id=1)

  6. You can get record by primary key Question.objects.get(pk=1)