Why do we run BOTH makemigrations and migrate in Django? When I started learning Django, this was one of the concepts that confused me the most. If Django already knows our models, why do we need two commands? Here’s the simple explanation Suppose we create or modify a model: class Student(models.Model): name = models.CharField(max_length=100) Now we need to update the database so that it contains a Student table. But Django doesn’t change the database directly. Instead, it uses a migration system to track database changes safely. Step 1️⃣ makemigrations python manage.py makemigrations This command checks your models and creates migration files that describe what changed. Examples of changes it tracks: ✔ Create a new table ✔ Add a new field ✔ Remove a field ✔ Modify a field These instructions are stored inside the migrations folder. Think of it as: “Prepare the instructions for updating the database.” Step 2️⃣ migrate python manage.py migrate This command reads the migration files and applies those changes to the database. It actually: ✔ Creates tables ✔ Updates columns ✔ Applies schema changes Now your database structure matches your models. 📌 Simple way to remember makemigrations → prepare instructions migrate → execute instructions 💡 Bonus Tip Whenever you modify your models, always run: makemigrations → migrate to keep your database and models in sync. Understanding this small concept makes working with Django models much easier. #Django #Python #BackendDevelopment #LearningInPublic #WebDevelopment
Django makemigrations vs migrate explained
More Relevant Posts
-
Understanding Flask and Django in My Python Learning Journey 🚀 As I continue building my skills in Python backend development, I’ve been exploring two widely used web frameworks: Flask and Django. Both frameworks are powerful in their own way, but what really stood out to me is how differently they approach web development. Learning both has given me a broader perspective on designing and building applications. Working with Flask Flask gave me a clear understanding of how web applications function at a fundamental level. Its lightweight and minimal design allows developers to build step by step without unnecessary complexity. While working with Flask, I explored: ▸ Routing and request handling ▸ Building simple APIs ▸ Structuring small-scale applications What makes Flask interesting is the level of control it provides. It allows developers to choose how they want to build and scale their applications. Exploring Django Django offered a more structured and feature-rich experience. It comes with many built-in tools that make development faster and more organized. Some key features I found valuable: ▸ Built-in admin panel ▸ ORM for database operations ▸ Predefined project structure ▸ Authentication and security support Django feels like a framework that is ready for larger applications right from the start. Key Takeaway One important difference I noticed: ▸ Flask → Flexibility and simplicity ▸ Django → Structure and built-in functionality This helped me understand that the choice of framework depends on the type and scale of the project. Moving Forward Exploring both Flask and Django is strengthening my backend development skills and helping me understand real-world application design more effectively. Looking forward to building more projects and diving deeper into the Python ecosystem. #Python #Flask #Django #WebDevelopment #BackendDevelopment #SoftwareDevelopment #LearningJourney 🚀 #snsinstitutions #snsdesignthinkers #designthinking
To view or add a comment, sign in
-
-
Introducing my first published Python package - django-field-permissions! As far as Python web frameworks go, Django is undoubtedly the choice that comes with the most features out of the box. "Batteries included" is their mantra, after all. One of these "batteries" is the permissions framework, which is a flexible foundation for creating role-based access systems in your apps. One limitation is that by default, it only operates at the model level. Field-level granularity is where it stops short. You can say, "this user can view and edit orders" - but you can't say "this user can view and edit order dates and quantities, but can only view addresses". That's a gap that Django's native permissions framework doesn't cover. That's exactly what django-field-permissions is built to fill - it lets you define field-level permissions with minimal setup. You can get it up and running in a Django project in 5 minutes, with: - Assignable read and edit permissions on any models that you specify - Permission checks in both templates and backend - Built-in caching for performance with automatic invalidation via signals - Django admin integration for managing field permissions through the UI The package is live on PyPi to install: https://lnkd.in/gtntwqHp Check out the source code here (maybe give it a star?): https://lnkd.in/gMaPMPqq
To view or add a comment, sign in
-
Day-120,121 📘 Python Full Stack Journey – Django Forms & User Input Handling Today I learned how to handle user input in Django using models and forms — an important step toward building interactive and data-driven applications. 🚀 🎯 What I learned today: 🗄️ Model Creation (Contact Form) Created a Contact model to store user data: Name Email Phone number Applied migrations and registered the model in Django Admin for easy data management 📝 Django ModelForm Created a form using Django’s built-in ModelForm: class BookingContact(forms.ModelForm): class Meta: model = Contact fields = '__all__' Learned how Django automatically generates form fields from models 🌐 Displaying Forms in Templates Rendered forms in HTML using: {{ form }} {{ form.as_p }} for structured layout 📩 Form Submission (POST Method) Used POST method for secure data submission Added {% csrf_token %} for protection Handled form submission in views.py: if request.method == 'POST': form = BookingContact(request.POST) if form.is_valid(): form.save() 🎨 Custom Form Styling Styled individual form fields manually using labels and inputs Learned how to design forms for better user experience This session helped me understand how Django manages forms, validation, and database storage seamlessly — a key step in building real-world web applications. Excited to keep building more interactive features! 💻✨ #Django #Python #FullStackDevelopment #WebDevelopment #Backend #Forms #Database #CodingJourney #LearningToCode #Upskilling #ContinuousLearning
To view or add a comment, sign in
-
-
Day-129 📘 Python Full Stack Journey – Django Messages & Authentication Flow 🔐 Today I enhanced my Django application by implementing user feedback messages and complete authentication flow (Login & Logout). 🚀 🎯 What I learned today: 💬 Django Messages Framework Displayed success messages after signup using: messages.success(request, f'Account created for {username}!') Rendered messages in HTML using: {% if messages %} {% for message in messages %} <p style="color: green;">{{ message }}</p> {% endfor %} {% endif %} 💡 This improves user experience by giving instant feedback. 🔐 Login Using AuthenticationForm Used Django’s built-in AuthenticationForm Accessed form fields directly in template: {{ form.username }} {{ form.password }} Validated and authenticated users securely 🚪 Logout Functionality Implemented logout using: from django.contrib.auth import logout def logout_view(request): logout(request) return redirect('Login') Added logout route and link in UI ⚙️ Key Takeaways Improved user interaction with messages Built a complete authentication cycle (Signup → Login → Logout) Learned how Django handles sessions and user state This session made my application more user-friendly, secure, and complete. Excited to keep improving with protected routes and user-specific data next! 💻✨ #Django #Python #FullStackDevelopment #WebDevelopment #Authentication #Login #Logout #UserExperience #CodingJourney #LearningToCode #Upskilling #ContinuousLearning
To view or add a comment, sign in
-
-
Django Beginner Mistake: get() vs filter() While working with database queries in Django, I learned an important difference between get() and filter() that often confuses beginners. Both are used to retrieve data from the database, but they behave very differently. Using get() student = Student.objects.get(id=1) get() is used when you expect exactly one object. ✔ Returns a single model object ✔ Best used with unique fields like id, email, or username However, it can raise errors: ❌ DoesNotExist → when no object matches the query ❌ MultipleObjectsReturned → when more than one object matches Example: student = Student.objects.get(email="ali@example.com") This works well if email is unique. Using filter() students = Student.objects.filter(age=20) filter() is used when multiple objects may match the query. ✔ Returns a QuerySet (collection of objects) ✔ If no record exists → returns empty QuerySet instead of error Example: students = Student.objects.filter(city="Karachi") This may return: ✔ 5 students ✔ 1 student ✔ or even 0 students But it will not raise an exception. Extra Tip 💡 If you only need one object but want to avoid errors, you can use: student = Student.objects.filter(id=1).first() This returns: ✔ the first object if it exists ✔ None if no object exists 📌 Key Lesson Use: get() → when you are sure only one object should exist filter() → when multiple objects may exist Understanding this small difference can help avoid many common beginner errors while working with Django databases. #Django #Python #BackendDevelopment #LearningInPublic #WebDevelopment
To view or add a comment, sign in
-
Day-123 📘 Python Full Stack Journey – Django CRUD (Create Operation) Today I started implementing CRUD operations in Django, beginning with the Create functionality by building an Employee Registration Form. 🚀 🎯 What I learned today: 🗄️ Model Creation Created an Employee model to store user data: Full Name Employee ID Phone Number Email ID 🌐 Form Creation (Manual HTML Form) Built a registration form using HTML Used: method="post" {% csrf_token %} for security Input validation with required attributes ⚙️ Handling Form Data in Views Captured user input using request.POST Created an object and saved data into the database: ob = Employee() ob.fullname = username ob.emp_id = empid ob.ph_no = phno ob.email_id = emailid ob.save() 🔗 Routing & Navigation Connected form via URL routing Added navigation link in base.html This session helped me understand how Django handles data creation from user input, a key part of real-world applications. Looking forward to implementing the remaining CRUD operations — Read, Update, and Delete! 💻✨ #Django #Python #FullStackDevelopment #WebDevelopment #CRUD #BackendDevelopment #CodingJourney #LearningToCode #Upskilling #ContinuousLearning
To view or add a comment, sign in
-
-
Day 118-119 📘 Python Full Stack Journey – Django Models, Relationships & Media Handling Today I explored some advanced and exciting concepts in Django, moving closer to building real-world dynamic applications. 🚀 🎯 What I learned today: 🗄️ Multiple Models & Relationships Created a new Teacher model and linked it with Course using ForeignKey Understood how one-to-many relationships work in Django Used on_delete=models.CASCADE to automatically remove related data 💡 Learned how deleting a course also removes associated teachers — maintaining database integrity 🧩 Model Enhancements Used __str__() method to display meaningful names in Django Admin instead of default object names 🖼️ Image Handling in Django Used ImageField to upload images Installed Pillow for image processing Configured MEDIA_ROOT and MEDIA_URL to serve uploaded files Displayed images dynamically in templates 🌐 Dynamic Data Rendering Retrieved data using: Teacher.objects.all() Displayed data in templates using Django loops and variables Built a Teachers page showing: Name Course Image 📩 Forms & Models Created a Contact model for user data Introduced Django ModelForms to handle user input efficiently This session helped me understand how Django connects models, relationships, media files, and forms to build fully functional applications. Every step feels closer to building production-level web apps! 💻✨ #Django #Python #FullStackDevelopment #WebDevelopment #Backend #Database #CodingJourney #LearningToCode #Upskilling #TechSkills #ContinuousLearning
To view or add a comment, sign in
-
-
Day-122 📘 Python Full Stack Journey – Django Admin Customization & Form Feedback Today I explored how to enhance data presentation in Django Admin and improve user experience after form submission. 🚀 🎯 What I learned today: 📊 Admin Panel – Data Table View Customized Django Admin using ModelAdmin Displayed specific fields in a table format using: class ContactAdmin(admin.ModelAdmin): list_display = ('user_name', 'email_id', 'phone_number') This made the admin panel more structured and easier to manage data 💬 Popup / Response Page After Form Submission Created a popup (response) page to show feedback after form submission Updated views.py to: Validate and save form data Redirect or render a success page after submission if form.is_valid(): form.save() return render(request, 'popup.html') 💡 This improves user experience by confirming that the form was successfully submitted. This session helped me understand how to make applications more user-friendly and organized, both on the admin side and user-facing side. Step by step, building more complete Django applications! 💻✨ #Django #Python #FullStackDevelopment #WebDevelopment #Backend #AdminPanel #Forms #UIUX #CodingJourney #LearningToCode #Upskilling #ContinuousLearning
To view or add a comment, sign in
-
-
FastAPI vs. Django: Which Framework Should You Choose and When? In Python backend development, a perennial debate exists: FastAPI or Django? Whether you are preparing for an interview or selecting a framework for your next project, this comparison will prove invaluable. Here are 4 major differences between the two: 1. Performance and Speed FastAPI: Built upon Starlette and Pydantic, it ranks among the fastest Python frameworks available. Its asynchronous support (async/await) is superior for handling high-concurrency scenarios. Django: This is a synchronous framework (though it now includes ASGI support). It follows a "Batteries Included" approach, which can make it somewhat heavier. 2. Nature: Micro vs. Monolith FastAPI: A micro-framework. You receive only the essential tools; other functionalities (such as Authentication and Database handling) must be plugged in manually. It is perfect for microservices. Django: A monolith. It comes with a built-in Admin panel, ORM, and Authentication system. It is an excellent choice for full-stack web applications. 3. Data Validation and Documentation FastAPI: It utilizes Pydantic for data validation and automatically generates Swagger UI (OpenAPI) documentation. Developers do not need to write documentation separately. Django: APIs are typically built using the Django REST Framework (DRF), which involves a slightly higher degree of manual configuration. 4. Learning Curve FastAPI: Being compact and modern, it can be learned quickly—provided you are familiar with modern Python type hints. Django: It possesses a vast ecosystem, so mastering it takes some time; however, once learned, it significantly accelerates the development process. Conclusion: Choose FastAPI if you prioritize high performance, microservices, and rapid API development. Choose Django if you need to build a robust, secure, and feature-rich application quickly. Which one is your favorite? Let us know in the comments! #Python #BackendDevelopment #FastAPI #Django #SoftwareEngineering #WebDevelopment #CodingLife #InterviewPrep
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development