Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้าง Country Field ใน Django


หากต้องการเพิ่มฟิลด์สถานที่ในฟอร์มหรือฐานข้อมูล สามารถใช้ CharField แต่ไม่ค่อยดี ใน Django มีแพ็กเกจ django-countries ที่ให้ Country Field บทความนี้สอนใช้งาน

ตัวอย่าง

สร้างโปรเจกต์และแอป เพิ่มแอปใน INSTALLED_APPS ตั้งค่า urls

ติดตั้ง django-countries:

pip install django-countries

ใน settings.py:

INSTALLED_APPS += ['django_countries']

ใน urls.py ของแอป:

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name="home"),
]

ใน views.py:

from django.shortcuts import render
from django import forms
from .models import Data

class SalaryForm(forms.ModelForm):
    class Meta:
        model = Data
        fields = "__all__"

def home(request):
    if request.method == 'POST':
        form = SalaryForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = SalaryForm()
    return render(request, 'home.html', {'form': form})

สร้าง templates/home.html:

<!DOCTYPE html> <html>
<head> <title>TUT</title> </head>
<body>
    <h2>FORM</h2>
    <form action="/" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit">
    </form>
</body> </html>

ใน models.py:

from django.db import models
from django_countries.fields import CountryField

class Data(models.Model):
    Name = models.CharField(max_length=100)
    salary = models.CharField(max_length=20)
    country_of_work = CountryField(blank=True)

สร้างโมเดลพร้อม Country Field สำหรับเก็บข้อมูลประเทศ

รัน makemigrations และ migrate เสร็จแล้วทดสอบได้

เอาต์พุต

วิธีสร้าง Country Field ใน Django