Djano Contents App Django.How

Author avatar wrote on 26/05/2022

This app allows editing the contents of the static pages:

Tow types of contents

1.Text-only contents, to edit text on critical pages like the index page

2.HTML content to edit the content of the static pages like the about, term pages

Steps

1.Create app

2.Add to the installed apps

3.Declare classes in the models file

4.Register app in the admin area

5.Migrate

6.Import tables

7.Edit pages/views.py file

8.Edit templates, HTML files

1. Create App

Type python manage.py startapp content

2. Add to the installed app

In settings.py under installed apps add ‘content.apps.ContentConfig’,


# Application definition

INSTALLED_APPS = [
    ...
    'content.apps.ContentConfig',
    ...
]

3. Declare classes in the models file

We declare two classes, one for text contents and one HTML contents

Edit content/models.py file

4. Register app in the admin area

We need to add the contents then to disallow deleting the contents or editing the name field in the admin area

* If you need to add the contents via admin you need to comment readonly_fields = ["name"] temporarily and uncomment it when adding contents is done

Edit content/admin.py file

5. Migrate

Make sure in the terminal you are in the right folder and pipenv shell is running then type

python manage.py makemigrations content

python manage.py migrate

6. Import tables

Download the attached files, use this code to import the contents from csv files to the DB

* edit the file path to point to the location of the files on your PC


COPY content_content(name,page,dob,en_text,ar_text) 
FROM 'C:\tmp\content_table.csv' DELIMITER ',' CSV HEADER;

COPY content_pagescontent(page_name,en_page_title,ar_page_title,en_content,ar_content) 
FROM 'C:\tmp\pages_content_table.csv' DELIMITER ',' CSV HEADER;

More resources https://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/

7. Edit pages/views.py file

We are passing the contents to the pages so we need to edit the views.py file in pages app, not the content app

Edit pages/views.py file

8. Edit templates, HTML files

To make pages editable in the admin area, you need to edit its HTML file and add this

for static content, for example in home page

Notes:

  • This app does not allow creating new pages in the admin panel,
  • It is good to use when we want to have control of the contents of the static pages, for example: not allowing HTML or not allowing creating new pages
  • You can have full control of the path, you can create mywebsite.com/about not mywebsite.com/pages/about
  • To create a new page you need to add code to
    1. pages/views.py
      pages/urls.py
      Create an HTML page in the folder templates/pages
      Optional - Create a record in pages content table and pass the content to the page
    CRUDgen Django CRUD generator