Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thêm trường Money (tiền tệ) trong Django

Khi xây dựng website, đôi khi chúng ta cần lưu trữ dữ liệu liên quan đến tiền tệ như lương, phí, thu nhập. Django cung cấp IntegerField nhưng thường không đáp ứng được yêu cầu xử lý tiền tệ chính xác. Để giải quyết, chúng ta có thể sử dụng thư viện bên thứ ba django-money để thêm trường Money vào model.

Thiết lập dự án

Tạo dự án tên "MoneyFieldDemo" và app "myapp". Cấu hình cơ bản: urls và INSTALLED_APPS.

Cài đặt thư viện

pip install django-money

Thêm vào settings.py

INSTALLED_APPS += ["djmoney"]

Ví dụ chi tiết

1. Cấu hình URLs (urls.py của app)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="home"),
]

2. Template (home.html)

<!DOCTYPE html>
<html>
    <head>
        <title>Demo Money Field</title>
    </head>
    <body>
        <h2>Quản lý lương nhân viên</h2>
        <form action="/" method="post">
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Gửi">
        </form>
    </body>
</html>

3. Model (models.py)

from django.db import models
from djmoney.models.fields import MoneyField

class Data(models.Model):
    Name = models.CharField(max_length=100)
    salary = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')

Model có 2 trường: tên nhân viên và lương (MoneyField) với 14 chữ số, 2 số thập phân, mặc định USD.

4. View (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})

View đơn giản: tạo form, render và xử lý POST request.

Kết quả

Giao diện sẽ hiển thị form với trường lương bao gồm ô nhập số và dropdown chọn đơn vị tiền tệ.

Thêm trường Money (tiền tệ) trong Django