1.3 C
New York
Wednesday, February 12, 2025

Dynamic web apps with HTMX, Python, and Django




$ python manage.py makemigrations
$ python manage.py migrate

The makemigrations command creates a new migration file if any schema changes are detected. (These are found in quoteapp/migrations, but you won’t typically need to interact with them directly.) The migrate command applies the changes.

Constructing the view

Next up, let’s consider the view, which accepts a request and prepares the model (if necessary), and hands it off to be rendered as a response. We’ll only need one view, found at quoteapp/views.py:


// cat quoteapp/views.py 
from django.shortcuts import render
from django.template.loader import render_to_string
from django.http import HttpResponse
from .models import Quote

def index(request):
    if request.method == 'POST':
        text = request.POST.get('text')
        author = request.POST.get('author')
        if text and author:
            new_quote = Quote.objects.create(text=text, author=author)
            # Render the new quote HTML
            html = render_to_string('quoteapp/quote_item.html', {'quote': new_quote})
            return HttpResponse(html)
    quotes = Quote.objects.all()
    return render(request, 'quoteapp/index.html', {'quotes': quotes})

In this view, we import the Quote model and use it to craft a response in the index function. The request argument gives us access to all the information we need coming from the client. If the method is POST, we assemble a new Quote object and use Quote.objects.create() to insert it into the database. As a response, we send back just the markup for the new quote, because HTMX will insert it into the list on the front end.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles