MAC address Model Field & Form Field for Django apps

Overview

django-macaddress

Build Status

MAC Address model and form fields for Django

We use netaddr to parse and validate the MAC address. The tests aren't complete yet.

Patches welcome: http://github.com/django-macaddress/django-macaddress

Release Notes:

For release info: https://github.com/django-macaddress/django-macaddress/releases

Getting Started

settings.MACADDRESS_DEFAULT_DIALECT

To specify a default dialect for presentation (and storage, see below), specify:

settings.MACADDRESS_DEFAULT_DIALECT = 'module.dialect_class'

where the specified value is a string composed of a parent python module name and the child dialect class name. For example:

settings.MACADDRESS_DEFAULT_DIALECT = 'netaddr.mac_eui48'

PS: old default of macaddress.mac_linux (uppercase and divided by ':' ) will be used by default.

If the custom dialect is defined in a package module, you will need to define the class in or import into the package's __init__.py.

default_dialect and format_mac

To get the default dialect for your project, import and call the default_dialect function:

>>> from macaddress import default_dialect

>>> dialect = default_dialect()

This function may, optionally, be called with an netaddr.EUI class instance as its argument. If no default is defined in settings, it will return the dialect of the provided EUI object.

The format_mac function takes an EUI instance and a dialect class (netaddr.mac_eui48 or a subclass) as its arguments. The dialect class may be specified as a string in the same manner as settings.MACADDRESS_DEFAULT_DIALECT:

>>> from netaddr import EUI, mac_bare
>>> from macaddress import format_mac

>>> mac = EUI('00:12:3c:37:64:8f')
>>> format_mac(mac, mac_bare)
'00123C37648F'
>>> format_mac(mac, 'netaddr.mac_cisco')
'0012.3c37.648f'

MACAddressField (ModelField)

This is an example model using MACAddressField:

from macaddress.fields import MACAddressField

class Computer(models.Model):
    name = models.CharField(max_length=32)
    eth0 = MACAddressField(null=True, blank=True)
    ...

The default behavior is to store the MAC Address in the database is a BigInteger. If you would, rather, store the value as a string (to, for instance, facilitate sub-string searches), you can specify integer=False and the value will be stored as a string:

class Computer(models.Model):
    name = models.CharField(max_length=32)
    eth0 = MACAddressField(blank=True, integer=False)
    ...

If you want to set unique=True on a MACAddressField that is stored as a string, you will need to set null=True and create custom clean_<foo> methods on your forms.ModelForm class for each MACAddressField that return None when the value provided is an '' (empty string):

from .models import Computer

class ComputerForm(forms.ModelForm):
    class Meta:
        model = Computer

    def clean_eth0(self):
        return self.cleaned_data['eth0'] or None

You should avoid changing the value of integer after running managy.py syncdb, unless you are using a schema migration solution like South or Django's built-in migrations.

To Do

  • Add greater support for partial string queries when storing MACs as strings in the database.
  • Add custom validator to check for duplicate MACs when mixing string and integer storage types.
  • Add deprecation warning and timeline for changeover to default string storage.
Comments
  • This includes fix for #3 and some clean up based on advancement in netaddr codebase

    This includes fix for #3 and some clean up based on advancement in netaddr codebase

    Hi @tubaman,

    I'm filling in your lack of time to fix issue #3 by addressing search in django admin.

    Also, I'd like to know why you chose to implement db type as BigInteger? If there's no good reason behind it I'd like to change it to a char field as this enables to search MACs' using partial bits of a MAC (for example last 4 chars).

    First 2 commits are clean up based on the netaddr code base. Those hacks which I removed are no more necessary with updated netaddr library (seems like it's safe to use netaddr from almost a year back).

    Custom db type is not so urgent that I'll see to it later (also it will be required to change db type for other db's to 'CharField' rather than 'BigInteger' - to support all use cases including lookups)

    opened by kra3 10
  • Add Support for Storing Values as Strings in the Database

    Add Support for Storing Values as Strings in the Database

    This will add the ability to specify (at runtime) whether you would like to save MACs as strings (varchar) or integers (bigint) via an "integer" keyword (defaults to True, i.e. existing behavior). I've also reworked how to specify a default dialect (via a settings variable and a utility function that handles importing it), and added a function to format any given EUI instance via a specified mac_eui48 subclass. I know that my change to how a default dialect is set is backwards-incompatible, but I think it's more elegant solution than using a class method.

    opened by bltravis 7
  • changed mac dividning char from : to -

    changed mac dividning char from : to -

    Since the update to 1.1.0 the mac address representation is no longer 00:11:22:33:44:55 but 00-11-22-33-44-55 which caused my app to crash.... so had to roll back to 1.0.1 ....

    opened by iamit 5
  • Use the official notation of the Django package

    Use the official notation of the Django package

    Even if pypi is case insensitive, all other packages include django with an uppercase D. This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools. Please accept the change to make it compatible.

    opened by lociii 4
  • Deprecation Warnings in Django 1.9

    Deprecation Warnings in Django 1.9

    https://docs.djangoproject.com/en/1.8/releases/1.8/#subfieldbase

    fields.py:12: Removed In Django1.10 Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.

    opened by nachopro 4
  • Fixed netaddr.EUI accepting EUI_64 addresses (which are not MAC addresses)

    Fixed netaddr.EUI accepting EUI_64 addresses (which are not MAC addresses)

    It was then unable to insert them in database. The following fix just makes the form validation refuse EUI 64 addresses (EUI throws an AddrFormatError)

    opened by Ten0 3
  • mac always a string under python3

    mac always a string under python3

    Under python3 I see the following although I have set MACADDRESS_DEFAULT_DIALECT = 'netaddr.mac_eui48'

    In [1]: from infrabrowser.models import Unit
    In [2]: Unit.objects.first().mac
    Out[2]: '207369326246'
    

    Following patch (suggested by 2to3) fixes this issue

    --- /usr/local/lib/python2.7/site-packages/macaddress/fields.py (original)
    +++ /usr/local/lib/python2.7/site-packages/macaddress/fields.py (refactored)
    @@ -9,10 +9,9 @@
    
     import warnings
    
    -class MACAddressField(models.Field):
    +class MACAddressField(models.Field, metaclass=models.SubfieldBase):
         description = "A MAC address validated by netaddr.EUI"
         empty_strings_allowed = False
    -    __metaclass__ = models.SubfieldBase
         dialect = None
    
         def __init__(self, *args, **kwargs):
    
    opened by jlec 3
  • documentation old style notation

    documentation old style notation

    First: Great improvements in 1.3.0 !

    Can you add to the documentation the following:

    To get the old known macaddress notation, use (uppercase and divided by ':' ) in settings.py:

    MACADDRESS_DEFAULT_DIALECT = 'macaddress.mac_linux'
    
    opened by iamit 3
  • Django 1.9 compatibility

    Django 1.9 compatibility

    Using your module with Django 1.8 I had the following warning:

    formfields.py:1: RemovedInDjango19Warning: The django.forms.util module has been renamed. Use django.forms.utils instead.

    opened by mrnfrancesco 2
  • Version visibility for django debug toolbar

    Version visibility for django debug toolbar

    I work with django debug toolbar.

    I noticed it is very easy to have the version of your app vissible for django debug toolbar (and other tools)

    If you put the variable in setup.py:

    version = "1.2.0"
    

    and for maintainablilty it is easier to use this version also further on in your setup.py config:

    setup(
        name = "django-macaddress",
        version = version,
    ..
    

    and put this in your

    ./macaddress/__init__.py
    

    file:

    # package
    import pkg_resources
    
    __version__ = pkg_resources.get_distribution("macaddress").version
    VERSION = __version__  # synonym
    

    your version is visible for several purpuses (also django-debug-toolbar)

    opened by iamit 2
  • Get rid of ugettext*

    Get rid of ugettext*

    As support for Python 2 has been dropped, the library should not rely on ugettext* anymore but can use gettext* variants. ugettext* have been deprecated in Django 3.0 and will be removed in Django 4.0.

    opened by lociii 1
  • add lookup support for integerfield mac address type

    add lookup support for integerfield mac address type

    According to this: https://docs.djangoproject.com/en/3.1/releases/1.10/#field-get-prep-lookup-and-field-get-db-prep-lookup-methods-are-removed

    get_prep_lookup is deleted from django. Due to IntegerField option searching lookup only works with contains and icontains. However those lookups act as exact in sql.

    opened by dogukankotan 1
Releases(v1.8.0)
Owner
null
Resolve form field arguments dynamically when a form is instantiated

django-forms-dynamic Resolve form field arguments dynamically when a form is instantiated, not when it's declared. Tested against Django 2.2, 3.2 and

DabApps 108 Jan 3, 2023
A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Stefan Foulis 1.3k Dec 31, 2022
A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Stefan Foulis 1.3k Dec 31, 2022
Twitter Bootstrap for Django Form - A simple Django template tag to work with Bootstrap

Twitter Bootstrap for Django Form - A simple Django template tag to work with Bootstrap

tzangms 557 Oct 19, 2022
A reusable Django model field for storing ad-hoc JSON data

jsonfield jsonfield is a reusable model field that allows you to store validated JSON, automatically handling serialization to and from the database.

Ryan P Kilby 1.1k Jan 3, 2023
Twitter Bootstrap for Django Form

Django bootstrap form Twitter Bootstrap for Django Form. A simple Django template tag to work with Bootstrap Installation Install django-bootstrap-for

tzangms 557 Oct 19, 2022
This is a sample Django Form.

Sample FORM Installation guide Clone repository git clone https://github.com/Ritabratadas343/SampleForm.git cd to repository. Create a virtualenv by f

Ritabrata Das 1 Nov 5, 2021
Basic Form Web Development using Python, Django and CSS

thebookrain Basic Form Web Development using Python, Django and CSS This is a basic project that contains two forms - borrow and donate. The form data

Ananya Dhulipala 1 Nov 27, 2021
Django Phyton Web Apps template themes

Django Phyton Web Apps template themes Free download source code project for build a modern website using django phyton web apps. Documentation instal

Mesin Kasir 4 Dec 15, 2022
Django web apps for managing schedules.

skdue Description Skdue is a web application that makes your life easier by helping you manage your schedule. With the ability which allows you to cre

Patkamon_Awai 1 Jun 30, 2022
A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Django Countries A Django application that provides country choices for use with forms, flag icons static files, and a country field for models. Insta

Chris Beaven 1.2k Jan 7, 2023
A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Django Countries A Django application that provides country choices for use with forms, flag icons static files, and a country field for models. Insta

Chris Beaven 1.2k Dec 31, 2022
Custom Django field for using enumerations of named constants

django-enumfield Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. Installation Currently

5 Monkeys 195 Dec 20, 2022
Location field and widget for Django. It supports Google Maps, OpenStreetMap and Mapbox

django-location-field Let users pick locations using a map widget and store its latitude and longitude. Stable version: django-location-field==2.1.0 D

Caio Ariede 481 Dec 29, 2022
A pickled object field for Django

django-picklefield About django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects. The i

Gintautas Miliauskas 167 Oct 18, 2022
A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for quickly creating new images from the one assigned to the field.

django-versatileimagefield A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for creat

Jonathan Ellenberger 490 Dec 13, 2022
A pickled object field for Django

django-picklefield About django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects. The i

Gintautas Miliauskas 167 Oct 18, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 2, 2023