I am building a Blog App and I am trying to add inbuilt initial instances in django admin
so when user clone the repo , then user will see several initial blogs
every time even after reset the database
.
I didn't find anywhere to set the initial data. I also tried How to set initial data for Django admin model add instance form? But it was not what i am trying to do.
models.py
class BlogPost(models.Model):
title = models.CharField(max_length=1000)
body = models.CharField(max_length=1000)
I tried to use Providing data with fixtures But I have no idea , How can I store in.
Any help would be much Appreciated. Thank You.
CodePudding user response:
Fixtures still need to be loaded manually. You can add that step into installation instruction, something like "to load example data, install the provided fixture via manage.py loaddata ./my_blog_fixture.json
If you want to have the data inserted into database without any user's action, then you are looking for a Data Migration
that's a kind of database migration which does not change the database structure in any way, but it executes a custom command, eg. inserting some data. An example (adjustments needed to match your app name) below. You can either generate an empty migration (recommended) or append RunCommand into an existing migration.
To generate a new empty migration run makemigrations
$ manage.py makemigrations your_app_name --empty
then edit the migration and add RunPython
there (see linked docs above).
from django.db import migrations
def insert_blogpost(apps, schema_editor):
BlogPost = apps.get_model('your_app_name', 'BlogPost')
post = BlogPost(title="hello", body="post content")
post.save()
class Migration(migrations.Migration):
dependencies = [
('your_app_name', '0001_initial'),
]
operations = [
migrations.RunPython(insert_blogpost),
]