Introduction: File Writing
in Python & Django Tables
Discover essential skills in Python file writing and Django database
tables. Learn why file input/output and table management are
vital. This session suits beginners with basic Python and Django
knowledge.
by Preethi P Palankar
Writing to Files in Python:
The Basics
File Operations
Open files using open() in read, write, or append modes.
Writing Methods
Use write() and writelines() to add data to files.
Proper Closing
Close files with close() or use with statement for safety.
Example
Write a list of names to names.txt efficiently.
Advanced File Writing: CSV and JSON
CSV Files JSON Files Practical Use
Utilize Python’s csv module and Use the json module’s dump() Store complex data for easy
csv.writer() for structured data. method to save dictionaries as sharing and portability.
JSON.
Error Handling in File I/O
Common Exceptions Graceful Handling
• FileNotFoundError Utilize try...except blocks
• IOError to catch errors cleanly.
• PermissionError
Resource Safety
Ensure files close even if exceptions occur.
Introduction to Django
Models and Tables
Django ORM Models Fields
Maps Python classes Define tables as Include types like
to database tables Python classes with CharField,
for easy data specific fields. IntegerField, and
management. DateField.
Defining Django Models
Product Model
Name, price, and description fields for detailed data.
CharField
Stores strings like product names, limited by max_length.
DecimalField
Handles precise prices with digits and decimal places.
Model Inheritance
Create abstract models to share common features.
Migrations: Creating and
Updating Tables
1 Generate Migrations
Run makemigrations to create migration files reflecting
model changes.
2 Apply Migrations
Use migrate to update the database schema accordingly.
3 Migration Order
Be aware of dependencies to avoid conflicts.
4 Example
Migrate the Product model to create its database table.
Interacting with Django Models: CRUD
Operations
Create Read Update Delete
Use Query with all() or get() Modify fields and call Remove records with
Product.objects.creat to access data. save() to save changes. delete().
e() to add records.
Django Admin Interface
Model Registration Customization
Register models to manage Customize list displays and
data through admin. add filters for usability.
Data Management
Use the admin site to add, edit, or delete table records easily.
Conclusion & Best Practices
Key Takeaways Further Learning
• File I/O uses safe open-write-close methods. Explore official Django and Python documentation for
• Django models map Python code to databases. depth.
• Migrations manage table changes effectively. Adopt error handling and coding standards for reliability.
• CRUD operations handle data seamlessly.