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)
This "I P L Team Project" is developed by Prasanta Kumar Mohanty using Python with Django web framework, HTML & CSS.

I-P-L-Team-Project This "I P L Team Project" is developed by Prasanta Kumar Mohanty using Python with Django web framework, HTML & CSS. Screenshots HO

1 Dec 15, 2021
Code coverage measurement for Python

Coverage.py Code coverage testing for Python. Coverage.py measures code coverage, typically during test execution. It uses the code analysis tools and

Ned Batchelder 2.3k Jan 05, 2023
Extensions for using Rich with Django.

django-rich Extensions for using Rich with Django. Requirements Python 3.6 to 3.10 supported. Django 2.2 to 4.0 supported. Are your tests slow? Check

Adam Johnson 88 Dec 26, 2022
Simple application TodoList django with ReactJS

Django & React Django We basically follow the Django REST framework quickstart guide here. Create backend folder with a virtual Python environment: mk

Flavien HUGS 2 Aug 07, 2022
Getdp-project - A Django-built web app that generates a personalized banner of events to come

getdp-project https://get-my-dp.herokuapp.com/ A Django-built web app that gener

CODE 4 Aug 01, 2022
A quick way to add React components to your Django templates.

Django-React-Templatetags This django library allows you to add React (16+) components into your django templates. Features Include react components u

Fröjd Agency 408 Jan 08, 2023
A small and lightweight imageboard written with Django

Yuu A small and lightweight imageboard written with Django. What are the requirements? Python 3.7.x PostgreSQL 14.x Redis 5.x FFmpeg 4.x Why? I don't

mint.lgbt 1 Oct 30, 2021
Django API without Django REST framework.

Django API without DRF This is a API project made with Django, and without Django REST framework. This project was done with: Python 3.9.8 Django 3.2.

Regis Santos 3 Jan 19, 2022
A music recommendation REST API which makes a machine learning algorithm work with the Django REST Framework

music-recommender-rest-api A music recommendation REST API which makes a machine learning algorithm work with the Django REST Framework How it works T

The Reaper 1 Sep 28, 2021
The Django Leaflet Admin List package provides an admin list view featured by the map and bounding box filter for the geo-based data of the GeoDjango.

The Django Leaflet Admin List package provides an admin list view featured by the map and bounding box filter for the geo-based data of the GeoDjango. It requires a django-leaflet package.

Vsevolod Novikov 33 Nov 11, 2022
Django-gmailapi-json-backend - Email backend for Django which sends email via the Gmail API through a JSON credential

django-gmailapi-json-backend Email backend for Django which sends email via the

Innove 1 Sep 09, 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
Add infinite scroll to any django app.

django-infinite-scroll Add infinite scroll to any django app. Features - Allows to add infinite scroll to any page.

Gustavo Teixeira 1 Dec 26, 2021
A debug/profiling overlay for Django

Django Debug Toolbar The Django Debug Toolbar is a configurable set of panels that display various debug information about the current request/respons

David Cramer 228 Oct 17, 2022
Django And React Notes App

Django & React Notes App Cloning the repository -- Clone the repository using the command below : git clone https://github.com/divanov11/Django-React

Dennis Ivy 136 Dec 27, 2022
Simple tagging for django

django-taggit This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidelines. django-tagg

Jazzband 3k Jan 02, 2023
Django-powered application about blockchain (bitcoin)

Django-powered application about blockchain (bitcoin)

Igor Izvekov 0 Jun 23, 2022
Template de desarrollo Django

Template de desarrollo Django Python Django Docker Postgres Nginx CI/CD Descripción del proyecto : Proyecto template de directrices para la estandariz

Diego Esteban 1 Feb 25, 2022
Django API that scrapes and provides the last news of the city of Carlos Casares by semantic way (RDF format).

"Casares News" API Api that scrapes and provides the last news of the city of Carlos Casares by semantic way (RDF format). Usage Consume the articles

Andrés Milla 6 May 12, 2022
Django model mixins and utilities.

django-model-utils Django model mixins and utilities. django-model-utils supports Django 2.2+. This app is available on PyPI. Getting Help Documentati

Jazzband 2.4k Jan 04, 2023