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)
A simple demonstration of how a django-based website can be set up for local development with microk8s

Django with MicroK8s Start Building Your Project This project provides a Django web app running as a single node Kubernetes cluster in microk8s. It is

Noah Jacobson 19 Oct 22, 2022
Agenda feita usando o django para adicionar eventos

Agenda de Eventos Projeto Agenda com Django Inicio O projeto foi iniciado no Django, usando o models.py foi adicionado os dados dos eventos e feita as

Bruno Fernandes 1 Apr 14, 2022
Simple alternative to Doodle polls and scheduling (Python 3, Django 3, JavaScript)

What is jawanndenn? jawanndenn is a simple web application to schedule meetings and run polls, a libre alternative to Doodle. It is using the followin

Sebastian Pipping 169 Jan 06, 2023
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
Sistema de tratamento e análise de grandes volumes de dados através de técnicas de Data Science

Sistema de tratamento e análise de grandes volumes de dados através de técnicas de data science Todos os scripts, gráficos e relatórios de todas as at

Arthur Quintanilha Neto 1 Sep 05, 2022
Full-text multi-table search application for Django. Easy to install and use, with good performance.

django-watson django-watson is a fast multi-model full-text search plugin for Django. It is easy to install and use, and provides high quality search

Dave Hall 1.1k Dec 22, 2022
System checks for your project's environment.

django-version-checks System checks for your project's environment. Requirements Python 3.6 to 3.9 supported. Django 2.2 to 3.2 supported. Are your te

Adam Johnson 33 Dec 22, 2022
🌟 A social media made with Django and Python and Bulma. 🎉

Vitary A simple social media made with Django Installation 🛠️ Get the source code 💻 git clone https://github.com/foxy4096/Vitary.git Go the the dir

Aditya Priyadarshi 15 Aug 30, 2022
Simple Login Logout System using Django, JavaScript and ajax.

Djanog-UserAuthenticationSystem Technology Use #version Python 3.9.5 Django 3.2.7 JavaScript --- Ajax Validation --- Login and Logout Functionality, A

Bhaskar Mahor 3 Mar 26, 2022
An orgizational tool to keep track of tasks/projects and the time spent on them.

Django-Task-Manager Task Tracker using Python Django About The Project This project is an orgizational tool to keep track of tasks/projects and the ti

Nick Newton 1 Dec 21, 2021
A Django Online Library Management Project.

Why am I doing this? I started learning 📖 Django few months back, and this is a practice project from MDN Web Docs that touches the aspects of Django

1 Nov 13, 2021
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
Returns unicode slugs

Python Slugify A Python slugify application that handles unicode. Overview Best attempt to create slugs from unicode strings while keeping it DRY. Not

Val Neekman (AvidCoder) 1.3k Dec 23, 2022
Django Girls Tutorial Workshop

Django Girls Tutorial Workshop A log of activities during the workshop. this is an H2 git remote add origin https://github.com/ahuimanu/django_girls_t

Jeffry Babb 1 Oct 27, 2021
Add a help desk or knowledge base to your Django project with only a few lines of boilerplate code.

This project is no longer maintained. If you are interested in taking over the project, email Zapier 487 Dec 06, 2022

Keep track of failed login attempts in Django-powered sites.

django-axes Axes is a Django plugin for keeping track of suspicious login attempts for your Django based website and implementing simple brute-force a

Jazzband 1.1k Dec 30, 2022
The magical reactive component framework for Django ✨

Unicorn The magical full-stack framework for Django ✨ Unicorn is a reactive component framework that progressively enhances a normal Django view, make

Adam Hill 1.4k Jan 05, 2023
Forward and backwards compatibility layer for Django 1.4, 1.7, 1.8, 1.9, 1.10, and 1.11

django-compat Forward and backwards compatibility layer for Django 1.4 , 1.7 , 1.8, 1.9, 1.10 and 1.11 Consider django-compat as an experiment based o

arteria GmbH 106 Mar 28, 2022
React.JS - Django Application Template

OTS React.JS - DJango Web Application (UNTESTED) This repository servers as a template for creating React.JS - Django Web Applications. Note that the

Darryl See Wei Shen 5 Aug 19, 2022