Skip to main content

A Django custom field that displays integers with comma separators and real-time formatting

Project description

Django Comma Integer Field

A Django custom field that displays integers with comma separators in the admin interface while providing real-time comma formatting as you type.

Features

  • 🔢 Comma-separated display: Shows integers with proper thousand separators (e.g., 1,234,567)
  • Real-time formatting: Automatically adds commas as you type
  • 🎯 Smart input validation: Only allows valid integer input
  • 💾 Database efficiency: Stores plain integers in the database
  • 🎨 Django admin integration: Works seamlessly with Django admin
  • 🔧 Easy to use: Drop-in replacement for Django's IntegerField
  • 🌐 Cross-browser compatible: Works in all modern browsers

Installation

Install using pip:

pip install django-comma-integer-field

Add to your Django settings:

INSTALLED_APPS = [
    # ... your other apps
    'django_comma_integer_field',
    # ... rest of your apps
]

Usage

Basic Usage

Replace Django's IntegerField with CommaIntegerField:

from django.db import models
from django_comma_integer_field import CommaIntegerField

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = CommaIntegerField(default=0, help_text="Price in cents")
    stock_quantity = CommaIntegerField(null=True, blank=True)
    
class Demographics(models.Model):
    city = models.CharField(max_length=100)
    population = CommaIntegerField(help_text="Total population")

Admin Integration

The field automatically works with Django admin:

from django.contrib import admin
from .models import Product

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['name', 'price', 'stock_quantity']
    # CommaIntegerField will automatically display with commas

Advanced Usage

You can use all the same options as Django's IntegerField:

class Statistics(models.Model):
    # With validation
    revenue = CommaIntegerField(
        help_text="Annual revenue in USD",
        validators=[MinValueValidator(0)]
    )
    
    # With choices
    PRIORITY_CHOICES = [
        (1, 'Low'),
        (100, 'Medium'), 
        (1000, 'High'),
    ]
    priority_score = CommaIntegerField(
        choices=PRIORITY_CHOICES,
        default=1
    )
    
    # Nullable field
    optional_metric = CommaIntegerField(
        null=True, 
        blank=True,
        help_text="Optional statistical data"
    )

How It Works

Display Format

  • Database: Stores as regular integer (e.g., 1234567)
  • Admin Interface: Displays with commas (e.g., 1,234,567)
  • Form Input: Accepts input with or without commas
  • Real-time: Adds commas automatically as you type

Technical Details

  1. Widget: Uses a custom CommaIntegerWidget that renders as a text input
  2. JavaScript: Provides real-time formatting with intelligent cursor positioning
  3. Validation: Ensures only valid integers are accepted
  4. Storage: Removes commas before saving to database

Browser Support

  • ✅ Chrome (all versions)
  • ✅ Firefox (all versions)
  • ✅ Safari (all versions)
  • ✅ Edge (all versions)
  • ✅ Internet Explorer 11+

Examples

Real-time Formatting Demo

When you type in the admin interface:

  • Type: 1234567 → Displays: 1,234,567
  • Type: 999999999 → Displays: 999,999,999
  • Type: -50000 → Displays: -50,000

Form Integration

from django import forms
from django_comma_integer_field import CommaIntegerFormField

class BudgetForm(forms.Form):
    annual_budget = CommaIntegerFormField(
        label="Annual Budget",
        help_text="Enter the budget amount"
    )

Migration from IntegerField

To migrate existing IntegerField to CommaIntegerField:

  1. Update your model:
# Before
quantity = models.IntegerField()

# After  
quantity = CommaIntegerField()
  1. Create and run migration:
python manage.py makemigrations
python manage.py migrate

No data migration needed - the database column type remains the same!

Customization

Custom Widget Attributes

from django_comma_integer_field import CommaIntegerWidget

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        CommaIntegerField: {
            'widget': CommaIntegerWidget(attrs={
                'style': 'width: 200px;',
                'placeholder': 'Enter amount...'
            })
        },
    }

Custom CSS Classes

The widget automatically adds the comma-integer-field CSS class for styling:

.comma-integer-field {
    text-align: right;
    font-family: monospace;
    background-color: #f8f9fa;
}

Requirements

  • Django 3.2+
  • Python 3.8+

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

If you encounter any issues or have questions, please open an issue on GitHub.


Made with ❤️ for the Django community

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_comma_integer_field-1.0.0.tar.gz (10.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_comma_integer_field-1.0.0-py3-none-any.whl (8.8 kB view details)

Uploaded Python 3

File details

Details for the file django_comma_integer_field-1.0.0.tar.gz.

File metadata

File hashes

Hashes for django_comma_integer_field-1.0.0.tar.gz
Algorithm Hash digest
SHA256 1ab11d119759d9c9e53ad1c469b80a2f99ecc0a973d48fe51c7a1023e1f99e14
MD5 353d5af90bfbcf7b5ab7877667ef719b
BLAKE2b-256 41367e64312959b5068570dc37a208b56b7f4ea810861aa816825ddd1db29c71

See more details on using hashes here.

File details

Details for the file django_comma_integer_field-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_comma_integer_field-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bd5bba79882380b66c55684eeed0d886c3cbcd8981ac87c1251b219ca526534d
MD5 73643a9abf7e33d20aba5adeabcebc7c
BLAKE2b-256 903fe7215df9d592879623b38774e45901604bc3f04f5ca304584985fd99d920

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page