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 integrating a sentiment analysis tool in a django project

sentiment-analysis A simple demonstration of integrating a sentiment analysis tool in a django project (watch the video .mp4) To run this project : pi

2 Oct 16, 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
Chatbot for ordering and tracking a Pizza.

Pizza Chatbot To start the app, follow the below steps: Clone the repo using the below command: git clone Shreya Shah 1 Jul 15, 2021

Send push notifications to mobile devices through GCM or APNS in Django.

django-push-notifications A minimal Django app that implements Device models that can send messages through APNS, FCM/GCM and WNS. The app implements

Jazzband 2k Dec 26, 2022
Neighbourhood - A python-django web app to help the residence of a given neighborhood know their surrounding better

Neighbourhood A python-django web app to help the residence of a given neighborh

Levy Omolo 4 Aug 25, 2022
Social Media Network Focuses On Data Security And Being Community Driven Web App

privalise Social Media Network Focuses On Data Security And Being Community Driven Web App The Main Idea: We`ve seen social media web apps that focuse

Privalise 8 Jun 25, 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
Django Federated Login provides an authentication bridge between Django projects and OpenID-enabled identity providers.

Django Federated Login Django Federated Login provides an authentication bridge between Django projects and OpenID-enabled identity providers. The bri

Bouke Haarsma 18 Dec 29, 2020
Imparare Django ricreando un sito facsimile a quello Flask

SitoPBG-Django Imparare Django ricreando un sito facsimile a quello Flask Note di utilizzo Necessita la valorizzazione delle seguenti variabili di amb

Mario Nardi 1 Dec 08, 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
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 backend of Helium's planner application

Helium Platform Project Prerequisites Python (= 3.6) Pip (= 9.0) MySQL (= 5.7) Redis (= 3.2) Getting Started The Platform is developed using Pytho

Helium Edu 17 Dec 14, 2022
django+bootstrap5 实现的 个人博客

项目状态: 正在开发中【目前已基本可用】 项目地址: https://github.com/find456789/django_blog django_blog django+bootstrap5 实现的 个人博客 特点 文章的历史版本管理(随时回退) rss、atom markdown 评论功能

名字 3 Nov 16, 2021
User Authentication In Django/Ajax/Jquery

User Authentication In Django/Ajax/Jquery Demo: Authentication System Using Django/Ajax/Jquery Demo: Authentication System Using Django Overview The D

Suman Raj Khanal 10 Mar 26, 2022
A feature flipper for Django

README Django Waffle is (yet another) feature flipper for Django. You can define the conditions for which a flag should be active, and use it in a num

950 Dec 26, 2022
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
A real-time photo feed using Django and Pusher

BUILD A PHOTO FEED USING DJANGO Here, we will learn about building a photo feed using Django. This is similar to instagram, but a stripped off version

samuel ogundipe 4 Jan 01, 2020
Utilities to make function-based views cleaner, more efficient, and better tasting.

django-fbv Utilities to make Django function-based views cleaner, more efficient, and better tasting. 💥 📖 Complete documentation: https://django-fbv

Adam Hill 49 Dec 30, 2022
Dashboad Full Stack utilizando o Django.

Dashboard FullStack completa Projeto finalizado | Informações Cadastro de cliente Menu interatico mostrando quantidade de pessoas bloqueadas, liberada

Lucas Silva 1 Dec 15, 2021
django-compat-lint

django_compat_lint -- check Django compatibility of your code Django's API stability policy is nice, but there are still things that change from one v

James Bennett 40 Sep 30, 2021