contact@digitalnotebooks.co
Stay Organized, Stay Inspired. Let's Write.

Custom Management Command Part 6: Adding Comments or Messages

Back To All Notes
  • Notebook: Django: Automating Common Tasks
  • Speaker: Udemy Instructor Rathan Kumar
  • Date Created: Aug. 11, 2024, 7:40 p.m.
  • Owner: Rosilie

Django has built-in MESSAGES FRAMEWORK that we can use to show ERROR OR SUCCESS MESSAGES. See Django's documentation.

SETTINGS.PY has already the configurations needed to support the messages.

1. So, we just need to include the following in our SETTINGS.PY.

From Django documentation, we copy this and modify based on our needs.

 

in our SETTINGS.PY, we modify it to where 'danger' is a bootstrap name.

2.  Then in the TEMPLATES FOLDER, create a new HTML, ALERT.HTML and design as:

from our documentation:

So, in our ALERTS.HTML, we add the same code:

3. Now you can call this ALERTS.HTML in ANY HTML that will require messages or comments.

So, in DATAENTRY\IMPORTDATA.HTML, we add

4. To add our custom messages, we go to DATAENTRY\VIEWS.PY

5. Now when you add a CSV file again, you should be able to see an error message.

6. Now to make the style of the message that follows the bootstrap style, go to this BOOTSTRAP ALERT documentation, 

ALERTS.HTML BEFORE:

ALERTS.HTML AFTER:

7. Run the server again and check the message shown.

Saving Student.CSV to Student Model.

Saving Student.CSV to Customer Model

Or a different file to CUSTOMER model.

 

8. To modify the error message into something user-friendly especially the user has used a different file with a different model, we update our IMPORTDATA.PY

To get the fields of our model, in our IMPORTDATA.PY, we add this:

So, when we upload our STUDENT.CSV FILE, we see this in our terminal:

CUSTOMER MODEL:

So, when we import a different file like EMPLOYEE.CSV into CUSTOMER Model, we get this user- friendly message:

Instead of this:

9. Your IMPORTDATA.PY should be:

10. But this will give us an error message since we have the the field 'ID' in our table but not in our CSV file, so we update our IMPORTDATA.PY as 

11. IF WE WANT  TO HIDE THE ERROR MESSAGES RIGHT AWAY AFTER IT WAS DISPLAYED, we create a JAVASCRIPT. But we need to update our SETTINGS.PY STATIC FILES.

FROM:

TO:

12. Create an ID FOR YOUR ALERTS.HTML

FROM:

TO:

 

13. In our main project, we create a new folder and JS file, so in AUTOCOMMONTASKS_MAIN\STATIC\JS\CUSTOM.JS

14. Since we have our own static files like CUSTOM.JS, we need to run COLLECTSTATIC COMMAND in our DJANGO-SERVER bash terminal. This will create a new folder STATIC in the root directory.

15. Include this CUSTOM.JS JAVASCRIPT FILE in our DATAENTRY.HTML

16. Run the Django server again for testing. After 5 seconds, your alert message should disapper.

Push all changes to Github.



No PDF file attached.

Notebook
Notebook Details
Title: Django: Automating Common Tasks
Category: Coding