Install Django
-
Create a folder
-
Open folder with Visual Studio Code
-
(Only for first project) Open Terminal and run the code pip install pipenv (to install Django in a folder no all machine)
-
type pipenv shell
-
type pipenv install django
Create a project
-
In terminal type django-admin startproject projectname
-
change directory to projectname
-
type python manage.py runserver 8081 8081 is a path I choose / default is 8000
-
Quit the server with Ctrl+C
-
type python manage.py migrate to migrate tables
Create App
-
type python manage.py startapp polls polls is an example of app name
-
go to the file polls(the app name)/models.py 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 settings.py then declare your app under INSTALLED_APPS
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
.....
4. Create the migration, make sure in the terminal you are in the right folder and pipenv shell is running then type python manage.py makemigrations polls this will create the necessary python files
5. Make the complete migration to create the tables in the datbase by typing python manage.py migrate
Interacting with data using the shell
-
Type python manage.py shell
-
Import models from polls.models import Question,Choice
-
To check the recored Question.objects.all() //will return <QuerySet []> because 0 records
Creating a record using the terminal
-
we need time package, type from django.utils import timezone
-
Create a record q = Question(question_text=”What is your favorite Python Framework?”,pub_date=timezone.now())
-
Then save it q.save()
-
Now you can get its info q.id or q.question_text
-
You can also try to use filter Question.objects.filter(id=1)
-
You can get record by primary key Question.objects.get(pk=1)