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)
DCM is a set of tools that helps you to keep your data in your Django Models consistent.

Django Consistency Model DCM is a set of tools that helps you to keep your data in your Django Models consistent. Motivation You have a lot of legacy

Occipital 59 Dec 21, 2022
Service request portal on top of Ansible Tower

Squest - A service request portal based on Ansible Tower Squest is a Web portal that allow to expose Tower based automation as a service. If you want

Hewlett Packard Enterprise 183 Jan 04, 2023
Django-Docker - Django Installation Guide on Docker

Guía de instalación del Framework Django en Docker Introducción: Con esta guía p

Victor manuel torres 3 Dec 02, 2022
A simple Django dev environment setup with docker for demo purposes for GalsenDev community

GalsenDEV Docker Demo This is a basic Django dev environment setup with docker and docker-compose for a GalsenDev Meetup. The main purposes was to mak

3 Jul 03, 2021
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

Daniel Feldroy 10k Dec 31, 2022
This is django-import-export module that exports data into many formats

django-import-export This is django-import-export module which exports data into many formats, you can implement this in your admin panel. - Dehydrat

Shivam Rohilla 3 Jun 03, 2021
Create a netflix-like service using Django, React.js, & More.

Create a netflix-like service using Django. Learn advanced Django techniques to achieve amazing results like never before.

Coding For Entrepreneurs 67 Dec 08, 2022
Exploit Discord's cache system to remote upload payloads on Discord users machines

Exploit Discord's cache system to hide payloads PoC Remote upload embedded payload from image using EOF to Discord users machines through cache. Depen

cs 169 Dec 20, 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
Backend with Django .

BackendCode - Cookies Documentation: https://docs.djangoproject.com/fr/3.2/intro/ By @tcotidiane33 & @yaya Models Premium class Pack(models.Model): n

just to do it 1 Jan 28, 2022
Django Email Sender

Email-Sender Django Email Sender Installation 1.clone Repository & Install Packages git clone https://github.com/telman03/Email-Sender.git pip install

Telman Gadimov 0 Dec 26, 2021
An extremely fast JavaScript and CSS bundler and minifier

Website | Getting started | Documentation | Plugins | FAQ Why? Our current build tools for the web are 10-100x slower than they could be: The main goa

Evan Wallace 34.2k Jan 04, 2023
Coltrane - A simple content site framework that harnesses the power of Django without the hassle.

coltrane A simple content site framework that harnesses the power of Django without the hassle. Features Can be a standalone static site or added to I

Adam Hill 58 Jan 02, 2023
Python CSS/Javascript minifier

Squeezeit - Python CSS and Javascript minifier Copyright (C) 2011 Sam Rudge This program is free software: you can redistribute it and/or modify it un

Smudge 152 Apr 03, 2022
Full-featured django project start tool.

django-start-tool Introduction django-start-tool is a full-featured replacement for django-admin startproject which provides cli for creating the same

Georgy Gnezdilov 0 Aug 30, 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 standalone package to scrape financial data from listed Vietnamese companies via Vietstock

Scrape Financial Data of Vietnamese Listed Companies - Version 2 A standalone package to scrape financial data from listed Vietnamese companies via Vi

Viet Anh (Vincent) Tran 45 Nov 16, 2022
Projeto Crud Django and Mongo

Projeto-Crud_Django_and_Mongo Configuração para rodar o projeto Download Project

Samuel Fernandes Oliveira 2 Jan 24, 2022
Django-discord-bot - Framework for creating Discord bots using Django

django-discord-bot Framework for creating Discord bots using Django Uses ASGI fo

Jamie Bliss 1 Mar 04, 2022
A Blog Management System Built with django

Blog Management System Backend use: Django Features Enhanced Ui

Vishal Goswami 1 Dec 06, 2021