Dynamic web applications with HTMX, Python and Django


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

He makemigrations The command creates a new migration file if scheme changes are detected. (These are in quoteapp/migrationsbut normally you will not need to interact with them directly). migrate The command applies the changes.

Building the view

Next, consider the view, which accepts a request and prepares the model (if necessary), and the delivery to be an answer. We will only need a view, found in 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})

From this point of view, we import the contribution model and use it to prepare an answer in the index function. He request The argument gives us access to all the information we need from the client. If the method is POSTWe gather a new Quote object and use Quote.objects.create() to insert it into the database. In response, we send only the marking for the new appointment, because HTMX will insert it into the list in the front.

#Dynamic #web #applications #HTMX #Python #Django

Leave a Reply

Your email address will not be published. Required fields are marked *