Wednesday, June 18, 2025

Dynamic net apps with HTMX, Python, and Django


$ python handle.py makemigrations
$ python handle.py migrate

The makemigrations command creates a brand new migration file if any schema modifications are detected. (These are present in quoteapp/migrations, however you received’t sometimes have to work together with them immediately.) The migrate command applies the modifications.

Establishing the view

Subsequent up, let’s take into account the view, which accepts a request and prepares the mannequin (if vital), and palms it off to be rendered as a response. We’ll solely want one view, discovered 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 .fashions import Quote

def index(request):
    if request.technique == 'POST':
        textual content = request.POST.get('textual content')
        creator = request.POST.get('creator')
        if textual content and creator:
            new_quote = Quote.objects.create(textual content=textual content, creator=creator)
            # Render the brand 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})

On this view, we import the Quote mannequin and use it to craft a response within the index operate. The request argument provides us entry to all the knowledge we want coming from the shopper. If the tactic is POST, we assemble a brand new Quote object and use Quote.objects.create() to insert it into the database. As a response, we ship again simply the markup for the brand new quote, as a result of HTMX will insert it into the checklist on the entrance finish.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com