The next step to continue with the Django project is to add some models. Just follow the steps bellow to have them migrated in the database. You must have your virtual environment activated (remember, in your Powershell or terminal just run: )
\flask\Script\activate
Let’s go to our directory app “blogs” with our favourite IDE or text editor, in my case inside “blog”, in models.py of your app, insert under #Create your models here (obviously he,he,he) something like that, in any case whatever you need to be in your model, in my case :
class Entry(models.Model):
"""An entry for your blog"""
title = models.CharField(max_length=400)
date_added = models.DateTimeField(auto_now_add=True)
text = models.TextField()
def __str__(self):
"""Return a string representation of the model."""
return self.title
To see the different kinds of fields that you can use in a model :
https://docs.djangoproject.com/en/2.2/ref/models/fields/
The next step is to modify the database so it can store information related to our model Entry and apply our migration. So, from the terminal, we will run the follow commands:
python manage.py makemigrations blogs
python manage.py migrate
Whenever you want to modify the data that your Project (Blog) manages we’ll follow these three steps:
Let’s add another model just to show for example, Tags. It’s a relation of many_to_many, so a lot of Entries can use many Tags, and these Tags can be used for many Entries. In our case we need to modify our Entry model and add Tag model.
class Entry(models.Model):
"""An entry for your blog"""
title = models.CharField(max_length=400)
date_added = models.DateTimeField(auto_now_add=True)
text = models.TextField()
tags = models.ManyToManyField('Tag', related_name='tags')
def __str__(self):
"""Return a string representation of the model."""
return self.title
class Tag(models.Model):
"""An entry for your blog"""
tag_name = models.CharField(max_length=400)
def __str__(self):
"""Return a string representation of the model."""
return self.tag_name
Remember, after the modification to run on your terminal the next two mandatory steps, to see your modifications:
python manage.py makemigrations blogs
python manage.py migrate
In your admin area you can easily add data to your models. Just login as superuser and there you go: http://127.0.0.1:8000/admin