[PYTHON] Django Suggested Form

This article uses Django's CreateView (generic class view) The description is only for passing the value from view to template.

What is the suggestion function?

When entering what you want to search on the search site, the search site side A function that automatically displays the candidates that follow the characters.

App overview

Implemented the suggestion function in the customer name input form of the customer management application. In the image below, if you enter da, the customer names saved in the DB will be listed. It is a function that displays at the bottom of the form and inserts a value in the form when you select the corresponding name. ss 2.png

Creating a form that inherits ModelForm

models.py


from django.db import models
from datetime import datetime


class Client(models.Model):
    class Meta:
        db_table ="client"
        verbose_name ="client"
        verbose_name_plural ="client"

    client_name = models.CharField(verbose_name="Customer name", max_length=255,unique=True)
    receipt_name = models.CharField(verbose_name="Receipt address", max_length=500, blank=True)
    memo = models.TextField(verbose_name="Remarks", max_length=1000, blank=True)

    def __str__(self):
        return '{0}'.format(self.client_name)

forms.py


from django import forms
from .models import Client


class ClientForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = ['client_name', 'receipt_name', 'memo']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs["class"] = "form-control"
            field.widget.attrs['placeholder'] = field.label

I think you can understand the form by looking at the code, so the explanation is omitted.

CreateView (generic class view)

views.py


from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import ClientForm
from .models import Client

#abridgement
class ClientCreateView(CreateView):
    model = Client
    form_class = ClientForm
    success_url = reverse_lazy('client:create_done')

    def get_context_data(self, **kwargs):
        client_name_list = [] #Define an empty list type variable to pass to template
        context = super().get_context_data(**kwargs)
        client_data = Client.objects.all() #Get all client model data
        for client in client_data: #Extract client model data one by one and store the value in the list
            client_name_list.append(client.client_name)
        context["client_name_list"] = client_name_list
        return context

Create the value to be passed to template in the function using get_context_data method.

Creating template

The suggestion function is implemented using JavaScript.

client_form.html


{% extends 'base.html' %}
{% load static %}
{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/client/client_form.css' %}">
{% endblock %}
{% block content %}
<div class="form_contents">
    <h1 class="form_title">Customer information input</h1>
    <form action="" method="POST">
        {{ form.non_field_errors }}
        <div class="field">
            <p>{{ form.client_name.label }}</p>
            {{ form.client_name }}
            <div class="js-suggestions"></div>
            {{ form.client_name.errors }}
        </div>
        <div class="field">
            <p>{{ form.receipt_name.label }}(Any)</p>
            {{ form.receipt_name }}
            {{ form.receipt_name.errors }}
        </div>
        <div class="field">
            <p>{{ form.memo.label }}(Any)</p>
            {{ form.memo }}
            {{ form.memo.errors }}
        </div>
        <div class="field submit_btn">
            <button type="submit">Send</button>
        </div>
        {% csrf_token %}
    </form>
</div>
{% endblock %}
{% block script %}
<script>
    const list = [
        {% for name in client_name_list %}
            "{{name}}",
        {% endfor %}
    ];
    const elInput = document.querySelector("#id_client_name");
    const elSuggestions = document.querySelector(".js-suggestions");
    const state = {
        inputValue: elInput.value,
        inputting: false
    };
    const dataMap = new WeakMap();

    function render() {
        renderInput();
        renderSuggestions();
    }

    function renderInput() {
        elInput.value = state.inputValue;
    }

    function renderSuggestions() {
        const elNewList = document.createElement("ul");
        if (state.inputting) {
            list.filter(text => text.includes(state.inputValue)).forEach(text => {
            const elItem = document.createElement("li");
            dataMap.set(elItem, { text });
            elItem.textContent = text;
            elItem.addEventListener("click", handleClickItem);
            elNewList.appendChild(elItem);
            });
        }
        elSuggestions.innerHTML = "";
        elSuggestions.appendChild(elNewList);
    }

    function handleClickItem(e) {
        state.inputValue = dataMap.get(e.currentTarget).text;
        state.inputting = false;

        render();
    }

    elInput.addEventListener("input", () => {
        state.inputValue = elInput.value;
        state.inputting = elInput.value !== "";

        renderSuggestions();
    });
</script>
{% endblock %}

Extract the value passed in context using for statement in <script> </ script> Form the list again in JavaScript. If the value entered in the form matches the value in const list = [], A specification that inserts matching values below the form. The explanation of the JavaScript code is omitted. If you use it with code copy, it will work as a suggestion function.

Recommended Posts

Django Suggested Form
Django Contact Form 2
Django Form Gleaning
Django contact form
Django
[Django] How to test Form [TDD]
Dynamically add form fields in Django
Get the value from the [Django] Form
django update
Django note 4
Django memorandum
django search
Django installation
Django Summary
Django test
Django # 2 (template)
Django Note 5
Django hands-on
Touch django
Django Summary
Django Shoho
Django + Docker
Django Glossary
Django search
Install Django
Django: References
Django Note 1
Django note 3
DJango Note: From the beginning (form processing)
Django note 2
Get only the text from the Django form.
Django startup
Django notes
Django NullCharField
Dynamically add fields to Form objects in Django
Save multiple models in one form with Django