Day 92 – Mastering Django Template Variables & Tags Today I explored how Django dynamically passes and displays data in HTML using Template Variables, Tags, and Loops 🔥 🔹 Django Template Variables Used to display dynamic data in HTML 👉 Syntax: {{ variable_name }} ✔️ Data is passed from views.py as a dictionary ✔️ Keys are accessed directly in HTML 🔹 Django Template Tags Used for logic like conditions and loops 👉 Syntax: {% condition %} ✔️ Supports if-else, for loop, and more ✔️ Must properly close tags like {% endif %} and {% endfor %} 🔹 What I Did Today ✔️ Passed data from views.py using dictionary ✔️ Displayed values in HTML using {{ }} ✔️ Applied conditions using {% if %} ✔️ Implemented loops using {% for %} to iterate lists ✔️ Learned direct data passing inside render() 🔹 Example Learnings 📌 Display Data: {{ Name }} 📌 Condition: {% if Age > 18 %} → Eligible / Not Eligible 📌 Loop: {% for i in Name %} → Prints each value one by one 🔹 How It Works 👤 User → URL ➡️ urls.py maps request ➡️ views.py sends data via dictionary ➡️ Template receives data ➡️ Variables & Tags process it ➡️ Final output displayed 🎉 🔹 Key Takeaway Django Templates make websites dynamic, allowing us to control both data and logic inside HTML itself. This is where backend truly connects with frontend in a powerful way 💡 #Django #Python #WebDevelopment #BackendDevelopment #Frontend #FullStackDevelopment
Naveen T’s Post
More Relevant Posts
-
📘 Day 84: Django – Templates & Dynamic Data 🔹 What are Templates? • Templates are used to create the frontend (HTML pages) in Django • They display data sent from the backend • Helps separate design from logic 🔸 Templates Folder Setup • A templates folder is created inside the app • This folder stores all HTML files 🔹 Important Step: • Must register the templates folder in settings.py (DIRS section) • Without this → Django cannot find HTML files 🔸 HTML Page Creation • Create HTML files inside the templates folder • These act as the UI of the application 🔹 Key Idea: • HTML is static • Django makes it dynamic 🔸 Rendering Templates • To display an HTML page → use render() in views 🔹 Flow: • URL → View → Template 💡 render(): • Connects backend (views) with frontend (HTML) • Sends data to HTML 🔸 Django Variables {{ }} • Used to display dynamic data in HTML 🔹 Key Points: • Written inside {{ }} • Values come from views (dictionary data) • Keys in dictionary = variables in template 💡 Example Concept: • Backend sends → name = "Adam" • Frontend displays → {{ name }} 🔸 Passing Data to Templates • Data is passed as a dictionary from views 🔹 Key Points: • Keys → variable names • Values → actual data • Can pass directly or using a variable 🔸 Django Template Tags {% %} • Used to add logic inside HTML 🔹 Used For: • Conditions (if, else) • Loops (for) 🔸 Conditional Rendering • Templates can check conditions like Python 🔹 Key Points: • {% if %}, {% elif %}, {% else %} • Must end with {% endif %} 💡 Example Concept: • If age ≥ 18 → show eligible • Else → show not eligible 🔸 Execution Flow User opens URL URL calls view View sends data Template displays data ✨ Today you learned: • What templates are and how they work • How to connect HTML with Django using render() • How to use dynamic variables {{ }} • How to use logic inside HTML with {% %} This is where Django becomes powerful—combining backend + frontend seamlessly 🚀 #Django #Python #WebDevelopment #Frontend #BackendDevelopment #Day84 #Templates #FullStack #CodingJourney
To view or add a comment, sign in
-
Moving from the flexibility of Flask to the "Batteries-Included" power of Django! 🐍🔥 After spending significant time building with Flask, where I enjoyed the "build-it-from-scratch" approach, I decided to dive deep into Django today to see how it handles large-scale architectures. The transition is eye-opening! Here’s what I learned today while building a User Management System: ✅ The Architecture Shift: In Flask, I was used to manual setups for everything. Django’s "Batteries-Included" philosophy (like the built-in User model and Admin panel) is a massive time-saver for rapid development. ✅ From SQL/Manual JSON to Django ORM: I moved away from manual dictionary mapping to using Django’s ORM for JsonResponse. It’s interesting to see how User.objects.all() simplifies data retrieval. ✅ API-First Thinking: I bridged the gap between Backend and Frontend using the Fetch API. Instead of standard page redirects, I built a system where my Django backend serves JSON, and JavaScript handles the UI dynamically via Popups (Modals). ✅ The "Nickname" Logic: One thing I loved? Django’s URL names. In Flask, I’d often hardcode paths, but in Django, using name='user_list_link' makes the code so much more maintainable. The Verdict: Flask taught me how things work under the hood. Django is now showing me how to scale those concepts efficiently. #Python #Django #Flask #WebDevelopment #Backend #CodingJourney #SoftwareEngineering #LearningInPublic #SaaS
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗕𝗲𝗻𝗲𝗳𝗶𝗍𝘀 𝗢𝗳 𝗖𝗹𝗮𝘀𝘀-𝗕𝗮𝘀𝗲𝗱 𝗩𝗶𝗲𝘄𝘀 You can write views as functions or classes in Django. Class-Based Views (CBVs) are a cleaner alternative to function-based views. Here's how you can write a view using both methods: - Function-based view: def post_list(request): posts = Post.objects.all() return render(request, 'core/post_list.html', {'posts': posts}) - Class-based view: class PostListView(ListView): model = Post template_name = 'core/post_list.html' context_object_name = 'posts' Both views do the same thing. The CBV version is shorter because it handles the queryset fetching and context building automatically. Django provides generic views for common patterns. You can use these views to handle tasks like listing, creating, updating, and deleting objects. CBVs need .as_view() when connecting to a URL. You can also use mixins to add functionality to your views. Now that you understand CBVs, Django REST Framework (DRF) becomes easier to understand. DRF is essentially CBVs built for APIs instead of HTML pages. DRF handles tasks like serializing Python objects to JSON, deserializing and validating incoming JSON, and authentication for APIs. You can use serializers to convert model instances to JSON and validate incoming data. API views work like CBVs, and generic API views cut boilerplate to almost nothing. You can use DRF to build a JSON API from the same Django project that serves HTML pages. Source: https://lnkd.in/gswbYync
To view or add a comment, sign in
-
Day 24: Django Signals Today I dived deeper into Django Signals and how they help build event-driven applications. 🔹 What I learned: • Signals enable communication between different parts of a Django app • They trigger actions automatically when specific events occur • Help keep code decoupled, clean, and maintainable 🔹 Core Concepts: • Sender → The model/class that sends the signal • Receiver → Function that listens and responds • Signal → Event trigger (like "post_save", "pre_delete") 🔹 Hands-on Implementation: ✔ Used "post_save" signal to auto-create a user profile ✔ Connected signals using "@receiver" decorator ✔ Registered signals properly in "apps.py" ✔ Used "Q" and ORM concepts alongside signals 🔹 Advanced Understanding: • Difference between "pre_save" and "post_save" • Avoiding infinite loops in signals • Why signals should not contain heavy business logic • When to use signals vs overriding "save()" method 🔹 Best Practices: ✔ Keep signals lightweight ✔ Use a separate "signals.py" file ✔ Always ensure signals are imported (apps ready) ✔ Prefer signals only for side-effects (not core logic) 🔹 Common Mistakes I Learned to Avoid: ❌ Forgetting to register signals ❌ Writing complex logic inside signals ❌ Debugging difficulties due to hidden execution ❌ Multiple triggers causing performance issues 🔹 Real-World Use Cases: 📌 Auto profile creation after user registration 📌 Sending emails/SMS notifications 📌 Logging database changes 📌 Updating related models automatically 💡 Key Takeaway: Django Signals are powerful for handling background actions, but they should be used wisely to maintain performance and readability. 🔄 Flow Summary: Model Event → Signal Triggered → Receiver Function → Action Executed
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟲𝟴 𝗼𝗳 𝟭𝟬𝟬 𝗗𝗮𝘆𝘀 𝗢𝗳 𝗖𝗼𝗱𝗲 - 𝗗𝗷𝗮𝗻𝗴𝗼 𝗙𝗼𝗿𝗺𝘀 You learned about models and ORM yesterday. But all data was created through the admin panel. Today you learned about Django Forms. This lets users submit data from the browser directly. A Django Form is a Python class that handles three things: - Rendering HTML input fields - Validating submitted data - Giving you clean, safe data to work with Django has two kinds of forms: - Form - a standalone form, not tied to any model - ModelForm - a form generated directly from a model You can use fields like: - CharField for short text input - EmailField for email input with validation - IntegerField for number input A form view handles two scenarios: a GET request and a POST request. The standard Django form view pattern is: - If POST - bind the submitted data to the form - Validate with is_valid() - If valid - save and redirect - If GET or invalid - render the form You can render fields manually for more control over layout. is_valid() runs two levels of validation: field-level and custom validation. Source: https://lnkd.in/gNhPdWnc
To view or add a comment, sign in
-
Understanding Django Signals — Automating Actions Behind the Scenes 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗗𝗷𝗮𝗻𝗴𝗼 𝗦𝗶𝗴𝗻𝗮𝗹𝘀? Signals let different parts of your app react to events without tightly coupling code. For example, when a user registers, you can automatically send a welcome email — all without adding email logic inside the registration view. How it works: Define a signal handler — a Python function that runs when the event occurs. from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth import get_user_model User = get_user_model() @receiver(post_save, sender=User) def send_welcome_email(sender, instance, created, **kwargs): if created: # send email logic here print(f"Welcome email sent to {instance.email}") Connect it to a signal — here we used post_save on the User model. Triggered automatically whenever the event occurs (e.g., new user created). Why use signals: • Keeps your code modular — registration logic doesn’t need to know about emails. • Handles side effects cleanly — emails, notifications, analytics, logging. • Scales well — add new handlers without touching core logic.
To view or add a comment, sign in
-
Have you ever stepped back and really thought about your Django query system? Most of the time, we just write queries to “get the data”… but what if we treated queries as a structured journey instead of one-off solutions? Here’s a pattern I’ve been working on to eliminate query headaches and make everything more reusable and maintainable: 🔹 Start with a Base Query Class At the core, keep it simple: ModelName.objects.all() This is your foundation. 🔹 Add Mixins for Query Layers Each mixin is responsible for one specific concern: Filtering Ordering Permissions Business rules Think of them as building blocks. You stack them to shape your query step by step. 🔹 Build a Query Path via Inheritance Instead of messy, repeated logic, you create a clear “path”: Parent → Child → Specialized Query Because a query is not just data retrieval… it’s a journey. 🔹 Use Decorators for Enhancements Want to add: select_related / prefetch_related Computed fields Performance tweaks Wrap them as decorators. Each decorator does one job only and can be applied cleanly to your query methods like: query_set_v2() query_set_v3() 🔹 Result: A Clean, Scalable Query System By combining: Mixins + Inheritance + Decorators You get: ✔ Reusability ✔ Readability ✔ Performance control ✔ A system instead of scattered queries As developers, we shouldn’t just solve problems—we should design systems that solve them repeatedly and cleanly. Curious how others are structuring their query layers 👇 #Django #Python #BackendDevelopment #SoftwareArchitecture #CleanCode #SystemDesign #WebDevelopment #Programming #DevTips #CodeQuality
To view or add a comment, sign in
-
-
Most Django developers hit the database way more than they need to. I see this pattern constantly in codebases: ❌ The slow way: # N+1 query — hits DB once per order orders = Order.objects.all() for order in orders: print(order.user.name) # separate query every loop This runs 1 + N database queries. With 500 orders, that's 501 queries on a single page load. ✅ The fix — select_related(): # 1 query total using SQL JOIN orders = Order.objects.select_related('user').all() for order in orders: print(order.user.name) # no extra DB hit Use select_related() for ForeignKey / OneToOne fields. Use prefetch_related() for ManyToMany or reverse FK relations. This single change dropped our API response time by 60% on a production endpoint last month. Django's ORM makes it easy to write code that looks clean but silently destroys performance. Always check your query count with Django Debug Toolbar before shipping a new endpoint. What's your go-to Django optimization? Drop it below 👇 #Django #Python #WebDevelopment #FullStackDeveloper #BackendDevelopment #PythonDeveloper #SoftwareEngineering #DjangoTips
To view or add a comment, sign in
-
✂️ Just shipped my first full-stack web project a URL Shortener called Snip! Snip lets you paste any link and get a clean, short URL in under a second with one-click copy, a full history page, and click tracking built in. Here's what went into building it: → Backend: Python + Flask for routing and API logic → ORM: SQLAlchemy to interact with the database cleanly → Database: SQLite to store all original & shortened URLs → Frontend: HTML, CSS, JavaScript + Bootstrap Icons → URL Validation: urlparse to verify scheme and domain before saving → Deduplication: same URL always returns the same short code 📌 Key features I'm proud of: Instant URL shortening with 6-char alphanumeric codes One-click copy to clipboard History page with search, delete & click counters Live stats — total links and total clicks Clean dark UI with smooth animations Building this taught me so much about how the web actually works — HTTP redirects, database relationships, REST API design, and tying a backend to a frontend. This is just the beginning. Next up: user auth, custom aliases, and QR code generation. 👀 The full code is on my GitHub 👇 🔗 https://lnkd.in/gRqiFjMW #Python #Flask #WebDevelopment #FullStack #OpenSource #100DaysOfCode #BuildInPublic #SQLAlchemy #StudentDeveloper
To view or add a comment, sign in
-
-
Day 7 of My Full Stack Journey! 🚀 Today was all about Django Models & Databases — and it was a big day! Here's what I covered: 🔹 Created Django Models with fields like CharField, IntegerField, EmailField & BooleanField 🔹 Ran Migrations and explored the SQLite Database visually 🔹 Set up Django Admin Panel & created a Superuser 🔹 Registered Models in Admin and managed data through GUI 🔹 Used Django ORM — all(), filter(), get(), create(), update(), delete() 🔹 Built 2 complete models — Student & Book — independently! 🔹 Learned 3 ways to add data: Admin Panel (GUI) Django Shell (Python) DB Shell (SQL) The biggest insight today — ORM eliminates the need to write raw SQL. Python directly talks to the database! 🤯 Consistency > Motivation. Showing up every day is the real skill! 💪 Next up → HTML Forms in Django! 🎯 #Django #Python #FullStackDevelopment #100DaysOfCode #WebDevelopment #LearningInPublic #Day7
To view or add a comment, sign in
-
Explore related topics
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