[JAVA] [Django] Create a form that automatically fills in the address from the zip code

I may be asked to enter the address in the inquiry form or user registration form, but when I enter the zip code, I made a form in which the address is automatically entered, so it is a memo. Model forms are sometimes used in Django forms, but this time I took the method of writing them in forms.py in the individual application. This time, I used ajaxzip3 for the address auto-fill plugin.

Create forms.py in your application

Create forms.py in the application directory and write the following.

apps/forms.py


from django import forms

class TestForm(forms.Form):
	zip21 = forms.RegexField(
        regex=r'^[0-9]+$',
        max_length=3,
    )
    zip22 = forms.RegexField(
        regex=r'^[0-9]+$',
        max_length=4,
        widget=forms.TextInput(attrs={'onKeyUp' : "AjaxZip3.zip2addr('zip21','zip22','addr21','addr21')"}),
    )
    addr21 = forms.CharField()

When I wrote it for the first time, I thought that zip22 was a bad way to write, but it worked.

Read form in view & pass to html

For the time being, in view, just pass the form to html.

apps/views.py


from django.shortcuts import render, get_object_or_404, redirect
from forms.forms import *

def form(request):
    if request.method == 'POST':
        //Describe the processing after receiving the POST request
    else:
        form = ContactForm()
        return render(request,
            'test/form.html',
            dict(form = form)
        )

Apply form to html

Call form in html.

templates/form.html


<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE|default:"en-us" }}">
<head>
    <meta charset="UTF-8">
    <title>form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajaxzip3.github.io/ajaxzip3.js" charset="UTF-8"></script>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{ form.zip21 }}-{{ form.zip22 }}<br>
        {{ form.addr21 }}<br>
        <button type="submit">submit</button>
    </form>
</body>
</html>

This time I'm looking at the remote file on github, but you can also download it from here, store it in a static folder, and read it.


## Verification When implemented in the above example, the following form will be created. (It looks like it's because I haven't applied any CSS) ![スクリーンショット 2017-02-15 20.36.10.png](https://qiita-image-store.s3.amazonaws.com/0/80787/93d2b035-d525-9de3-3685-5b6db936adbf.png "スクリーンショット2017-02-1520.36.10.png ") If you enter the zip code in the upper input field, the address will be automatically entered in the lower input field.

Supplement

If you want to combine the zip code into one field

apps/forms.py


from django import forms

class TestForm(forms.Form):
    zip11 = forms.RegexField(
        regex=r'^[0-9]+$',
        max_length=7,
        widget=forms.TextInput(attrs={'onKeyUp' : "AjaxZip3.zip2addr(this,'','addr11','addr11')"}),
    )
    addr11 = forms.CharField()

templates/form.html


<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE|default:"en-us" }}">
<head>
    <meta charset="UTF-8">
    <title>form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajaxzip3.github.io/ajaxzip3.js" charset="UTF-8"></script>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{ form.zip11 }}<br>
        {{ form.addr11 }}<br>
        <button type="submit">submit</button>
    </form>
</body>
</html>

It seems that you should write as above. Other than that, you may want to divide only prefectures into different fields, but please refer to the ajazip3 documentation and reference links for that.

Supplement 2

Even when displaying prefectures by pull-down, we were able to respond as follows

apps/forms.py


from django import forms

class TestForm(forms.Form):
    zip11 = forms.RegexField(
        regex=r'^[0-9]+$',
        max_length=7,
        widget=forms.TextInput(attrs={'onKeyUp' : "AjaxZip3.zip2addr(this,'','addr11','addr11')"}),
    )
    addr11 = forms.CharField()

## Reference link https://github.com/ajaxzip3/ajaxzip3.github.io http://www.webdesign-fan.com/ajaxzip3

Recommended Posts

[Django] Create a form that automatically fills in the address from the zip code
Get the address from the zip code
Let's create a customer database that automatically issues a QR code in Python
Create code that outputs "A and pretending B" in python
Get the value from the [Django] Form
Create a LINE Bot in Django
[Python / Django] Create a web API that responds in JSON format
Get the client's IP address in Django
A note that you want to manually decorate the parameters passed in the Django template form item by item
A code that corrects the yoon / sokuon (sokuon)
DJango Note: From the beginning (form processing)
Get only the text from the Django form.
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
Create a Python image in Django without a dummy image file and test the image upload
Let Code Day1 Starting from Zero "1389. Create Target Array in the Given Order"
Create a Django project and application in a Python virtual environment and start the server
A tool to insert the country name and country code in the IP address part
DJango Memo: From the beginning (creating a view)
ImageKit automatically generates thumbnails from ImageField in Django
Create a datetime object from a string in Python (Python 3.3)
Output in the form of a python array
How to create a Rest Api in Django
Until you create a new app in Django
Simple code that gives a score of 0.81339 in Kaggle's Titanic: Machine Learning from Disaster
[Django] Hit a command you made from within the process that runs on manage.py.
Create a flag in settings that will be True only when testing with Django
[Go] Create a tool that returns the Pokemon race value received from the standard input
Code that enumerates URL resolver view names in Django
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Create a QR code for the URL on Linux
Create a Todo app with the Django REST framework
A programming language that protects the people from NHK
# Function that returns the character code of a string
DJango Note: From the beginning (using a generic view)
DJango Note: From the beginning (creating a view from a template)
Find the part that is 575 from Wikipedia in Python
In Python, create a decorator that dynamically accepts arguments Create a decorator
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
How to create a kubernetes pod from python code
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
[Django] Give Form a dynamic initial value from Model
A program that automatically resizes the iOS app icon to the required image size in Python
Create a script for your Pepper skill in a spreadsheet and load SayText directly from the script
How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django
A story that makes it easier to see Model debugging in the Django + SQLAlchemy environment
Parse the Researchmap API in Python and automatically create a Word file for the achievement list
Let's create a program that automatically registers ID/PW from CSV to Bitwarden with Python + Selenium
I made a tool to automatically generate a simple ER diagram from the CREATE TABLE statement
A story that made it possible to automatically create anison playlists from your music files
[Django] A story about getting stuck in a swamp trying to validate a zip with form [TDD]
Create a Django schedule
A tool that automatically turns the gacha of a social game
Create a QR code that displays "Izumi Oishi" by scratch
Code that sets the default value in case of AttributeError
Create a plugin that always highlights arbitrary text in Sublime Text 2
Create a data frame from the acquired boat race text data
Create a local scope in Python without polluting the namespace
A program that removes specific characters from the entered text
Let's create a script that registers with Ideone.com in Python.