|
| 1 | +title: django.db.models GenericIPAddressField Python Code Examples |
| 2 | +category: page |
| 3 | +slug: django-db-models-genericipaddressfield-examples |
| 4 | +sortorder: 50127 |
| 5 | +toc: False |
| 6 | +sidebartitle: django.db.models GenericIPAddressField |
| 7 | +meta: Python code examples for the GenericIPAddressField class used in the Django ORM, found within the django.db.models module of the Django project. |
| 8 | + |
| 9 | + |
| 10 | +[GenericIPAddressField](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py) |
| 11 | +is a [Django ORM](/django-orm.html) for mapping from your Python code to an |
| 12 | +database column that needs to store a valid IP address. |
| 13 | + |
| 14 | +The [Django](/django.html) project has great documentation for |
| 15 | +[GenericIPAddressField](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.GenericIPAddressField) |
| 16 | +as well as all of the other column fields. |
| 17 | + |
| 18 | +Note that `GenericIPAddressField` is defined within the |
| 19 | +[django.db.models.fields](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py) |
| 20 | +module but is typically referenced from |
| 21 | +[django.db.models](https://github.com/django/django/tree/master/django/db/models) |
| 22 | +rather than including the `fields` module reference. |
| 23 | + |
| 24 | + |
| 25 | +## Example 1 from AuditLog |
| 26 | +[Auditlog](https://github.com/jjkester/django-auditlog) |
| 27 | +([project documentation](https://django-auditlog.readthedocs.io/en/latest/)) |
| 28 | +is a [Django](/django.html) app that logs changes to Python objects, |
| 29 | +similar to the Django admin's logs but with more details and |
| 30 | +output formats. Auditlog's source code is provided as open source under the |
| 31 | +[MIT license](https://github.com/jjkester/django-auditlog/blob/master/LICENSE). |
| 32 | + |
| 33 | +[**AuditLog / src / auditlog / models.py**](https://github.com/jjkester/django-auditlog/blob/master/src/auditlog/models.py) |
| 34 | + |
| 35 | +```python |
| 36 | +from __future__ import unicode_literals |
| 37 | + |
| 38 | +import json |
| 39 | +import ast |
| 40 | + |
| 41 | +from django.conf import settings |
| 42 | +from django.contrib.contenttypes.fields import GenericRelation |
| 43 | +from django.contrib.contenttypes.models import ContentType |
| 44 | +from django.core.exceptions import FieldDoesNotExist |
| 45 | +~~from django.db import models, DEFAULT_DB_ALIAS |
| 46 | +from django.db.models import QuerySet, Q |
| 47 | +from django.utils import formats, timezone |
| 48 | +from django.utils.encoding import python_2_unicode_compatible, smart_text |
| 49 | +from django.utils.six import iteritems, integer_types |
| 50 | +from django.utils.translation import ugettext_lazy as _ |
| 51 | + |
| 52 | +from jsonfield.fields import JSONField |
| 53 | +from dateutil import parser |
| 54 | +from dateutil.tz import gettz |
| 55 | + |
| 56 | + |
| 57 | +## ... source file abbreviated to get to GenericIPAddressExample ... |
| 58 | + |
| 59 | + |
| 60 | +@python_2_unicode_compatible |
| 61 | +class LogEntry(models.Model): |
| 62 | + """ |
| 63 | + Represents an entry in the audit log. The content type is saved along with the textual and numeric (if available) |
| 64 | + primary key, as well as the textual representation of the object when it was saved. It holds the action performed |
| 65 | + and the fields that were changed in the transaction. |
| 66 | +
|
| 67 | + If AuditlogMiddleware is used, the actor will be set automatically. Keep in mind that editing / re-saving LogEntry |
| 68 | + instances may set the actor to a wrong value - editing LogEntry instances is not recommended (and it should not be |
| 69 | + necessary). |
| 70 | + """ |
| 71 | + |
| 72 | + class Action: |
| 73 | + """ |
| 74 | + The actions that Auditlog distinguishes: creating, updating and deleting objects. Viewing objects is not logged. |
| 75 | + The values of the actions are numeric, a higher integer value means a more intrusive action. This may be useful |
| 76 | + in some cases when comparing actions because the ``__lt``, ``__lte``, ``__gt``, ``__gte`` lookup filters can be |
| 77 | + used in queries. |
| 78 | +
|
| 79 | + The valid actions are :py:attr:`Action.CREATE`, :py:attr:`Action.UPDATE` and :py:attr:`Action.DELETE`. |
| 80 | + """ |
| 81 | + CREATE = 0 |
| 82 | + UPDATE = 1 |
| 83 | + DELETE = 2 |
| 84 | + |
| 85 | + choices = ( |
| 86 | + (CREATE, _("create")), |
| 87 | + (UPDATE, _("update")), |
| 88 | + (DELETE, _("delete")), |
| 89 | + ) |
| 90 | + |
| 91 | + content_type = models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE, related_name='+', verbose_name=_("content type")) |
| 92 | + object_pk = models.CharField(db_index=True, max_length=255, verbose_name=_("object pk")) |
| 93 | + object_id = models.BigIntegerField(blank=True, db_index=True, null=True, verbose_name=_("object id")) |
| 94 | + object_repr = models.TextField(verbose_name=_("object representation")) |
| 95 | + action = models.PositiveSmallIntegerField(choices=Action.choices, verbose_name=_("action")) |
| 96 | + changes = models.TextField(blank=True, verbose_name=_("change message")) |
| 97 | + actor = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True, related_name='+', verbose_name=_("actor")) |
| 98 | +~~ remote_addr = models.GenericIPAddressField(blank=True, null=True, verbose_name=_("remote address")) |
| 99 | + timestamp = models.DateTimeField(auto_now_add=True, verbose_name=_("timestamp")) |
| 100 | + additional_data = JSONField(blank=True, null=True, verbose_name=_("additional data")) |
| 101 | + |
| 102 | + objects = LogEntryManager() |
| 103 | + |
| 104 | + class Meta: |
| 105 | + get_latest_by = 'timestamp' |
| 106 | + ordering = ['-timestamp'] |
| 107 | + verbose_name = _("log entry") |
| 108 | + verbose_name_plural = _("log entries") |
| 109 | + |
| 110 | + def __str__(self): |
| 111 | + if self.action == self.Action.CREATE: |
| 112 | + fstring = _("Created {repr:s}") |
| 113 | + elif self.action == self.Action.UPDATE: |
| 114 | + fstring = _("Updated {repr:s}") |
| 115 | + elif self.action == self.Action.DELETE: |
| 116 | + fstring = _("Deleted {repr:s}") |
| 117 | + else: |
| 118 | + fstring = _("Logged {repr:s}") |
| 119 | + |
| 120 | + return fstring.format(repr=self.object_repr) |
| 121 | + |
| 122 | +## ... source file continues with no further GenericIPAddress examples ... |
| 123 | +``` |
| 124 | + |
| 125 | + |
| 126 | +## Example 2 from django-axes |
| 127 | +[django-axes](https://github.com/jazzband/django-axes/) |
| 128 | +([project documentation](https://django-axes.readthedocs.io/en/latest/) |
| 129 | +and |
| 130 | +[PyPI package information](https://pypi.org/project/django-axes/) |
| 131 | +is a code library for [Django](/django.html) projects to track failed |
| 132 | +login attempts against a web application. The goal of the project is |
| 133 | +to make it easier for you to stop people and scripts from hacking your |
| 134 | +Django-powered website. |
| 135 | + |
| 136 | +The code for django-axes is |
| 137 | +[open source under the MIT license](https://github.com/jazzband/django-axes/blob/master/LICENSE) |
| 138 | +and maintained by the group of developers known as |
| 139 | +[Jazzband](https://jazzband.co/). |
| 140 | + |
| 141 | +[**django-axes / axes / migrations / 0002_auto_20151217_2044.py**](https://github.com/jazzband/django-axes/blob/master/axes/migrations/0002_auto_20151217_2044.py) |
| 142 | + |
| 143 | +```python |
| 144 | +from django.db import migrations, models |
| 145 | + |
| 146 | + |
| 147 | +class Migration(migrations.Migration): |
| 148 | + |
| 149 | + dependencies = [ |
| 150 | + ('axes', '0001_initial'), |
| 151 | + ] |
| 152 | + |
| 153 | + operations = [ |
| 154 | +~~ migrations.AlterField( |
| 155 | +~~ model_name='accessattempt', |
| 156 | +~~ name='ip_address', |
| 157 | +~~ field=models.GenericIPAddressField(db_index=True, null=True, verbose_name='IP Address'), |
| 158 | +~~ ), |
| 159 | + migrations.AlterField( |
| 160 | + model_name='accessattempt', |
| 161 | + name='trusted', |
| 162 | + field=models.BooleanField(db_index=True, default=False), |
| 163 | + ), |
| 164 | + migrations.AlterField( |
| 165 | + model_name='accessattempt', |
| 166 | + name='user_agent', |
| 167 | + field=models.CharField(db_index=True, max_length=255), |
| 168 | + ), |
| 169 | + migrations.AlterField( |
| 170 | + model_name='accessattempt', |
| 171 | + name='username', |
| 172 | + field=models.CharField(db_index=True, max_length=255, null=True), |
| 173 | + ), |
| 174 | +~~ migrations.AlterField( |
| 175 | +~~ model_name='accesslog', |
| 176 | +~~ name='ip_address', |
| 177 | +~~ field=models.GenericIPAddressField(db_index=True, null=True, verbose_name='IP Address'), |
| 178 | +~~ ), |
| 179 | + migrations.AlterField( |
| 180 | + model_name='accesslog', |
| 181 | + name='trusted', |
| 182 | + field=models.BooleanField(db_index=True, default=False), |
| 183 | + ), |
| 184 | + migrations.AlterField( |
| 185 | + model_name='accesslog', |
| 186 | + name='user_agent', |
| 187 | + field=models.CharField(db_index=True, max_length=255), |
| 188 | + ), |
| 189 | + migrations.AlterField( |
| 190 | + model_name='accesslog', |
| 191 | + name='username', |
| 192 | + field=models.CharField(db_index=True, max_length=255, null=True), |
| 193 | + ), |
| 194 | + ] |
| 195 | + |
| 196 | +``` |
| 197 | + |
| 198 | + |
| 199 | +## Example 3 from django-wiki |
| 200 | +[django-wiki](https://github.com/django-wiki/django-wiki) |
| 201 | +([project documentation](https://django-wiki.readthedocs.io/en/master/), |
| 202 | +[demo](https://demo.django-wiki.org/), |
| 203 | +and [PyPI page](https://pypi.org/project/django-wiki/)) |
| 204 | +is a wiki system code library for [Django](/django.html) |
| 205 | +projects that makes it easier to create user-editable content. |
| 206 | +The project aims to provide necessary core features and then |
| 207 | +have an easy plugin format for additional features, rather than |
| 208 | +having every exhaustive feature built into the core system. |
| 209 | +django-wiki is a rewrite of an earlier now-defunct project |
| 210 | +named [django-simplewiki](https://code.google.com/p/django-simple-wiki/). |
| 211 | + |
| 212 | +The code for django-wiki is provided as open source under the |
| 213 | +[GNU General Public License 3.0](https://github.com/django-wiki/django-wiki/blob/master/COPYING). |
| 214 | + |
| 215 | +[**django-wiki / src/wiki / migrations / 0001_initial.py**](https://github.com/django-wiki/django-wiki/blob/master/src/wiki/migrations/0001_initial.py) |
| 216 | + |
| 217 | +```python |
| 218 | +import django.db.models.deletion |
| 219 | +import mptt.fields |
| 220 | +from django.conf import settings |
| 221 | +from django.db import migrations, models |
| 222 | +~~from django.db.models.fields import GenericIPAddressField as IPAddressField |
| 223 | +from wiki.conf.settings import GROUP_MODEL |
| 224 | + |
| 225 | + |
| 226 | +class Migration(migrations.Migration): |
| 227 | + |
| 228 | + dependencies = [ |
| 229 | + ('sites', '0001_initial'), |
| 230 | + migrations.swappable_dependency(settings.AUTH_USER_MODEL), |
| 231 | + ('contenttypes', '0001_initial'), |
| 232 | + ('auth', '0001_initial'), |
| 233 | + ] |
| 234 | + |
| 235 | + operations = [ |
| 236 | + migrations.CreateModel( |
| 237 | + name='Article', |
| 238 | + fields=[ |
| 239 | + ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), |
| 240 | + ('created', models.DateTimeField(verbose_name='created', auto_now_add=True)), |
| 241 | + ('modified', models.DateTimeField(verbose_name='modified', auto_now=True, help_text='Article properties last modified')), |
| 242 | + ('group_read', models.BooleanField(default=True, verbose_name='group read access')), |
| 243 | + ('group_write', models.BooleanField(default=True, verbose_name='group write access')), |
| 244 | + ('other_read', models.BooleanField(default=True, verbose_name='others read access')), |
| 245 | + ('other_write', models.BooleanField(default=True, verbose_name='others write access')), |
| 246 | + ], |
| 247 | + options={ |
| 248 | + 'permissions': (('moderate', 'Can edit all articles and lock/unlock/restore'), ('assign', 'Can change ownership of any article'), ('grant', 'Can assign permissions to other users')), |
| 249 | + }, |
| 250 | + bases=(models.Model,), |
| 251 | + ), |
| 252 | + migrations.CreateModel( |
| 253 | + name='ArticleForObject', |
| 254 | + fields=[ |
| 255 | + ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), |
| 256 | + ('object_id', models.PositiveIntegerField(verbose_name='object ID')), |
| 257 | + ('is_mptt', models.BooleanField(default=False, editable=False)), |
| 258 | + ('article', models.ForeignKey(to='wiki.Article', on_delete=models.CASCADE)), |
| 259 | + ('content_type', models.ForeignKey(related_name='content_type_set_for_articleforobject', verbose_name='content type', to='contenttypes.ContentType', on_delete=models.CASCADE)), |
| 260 | + ], |
| 261 | + options={ |
| 262 | + 'verbose_name_plural': 'Articles for object', |
| 263 | + 'verbose_name': 'Article for object', |
| 264 | + }, |
| 265 | + bases=(models.Model,), |
| 266 | + ), |
| 267 | + migrations.CreateModel( |
| 268 | + name='ArticlePlugin', |
| 269 | + fields=[ |
| 270 | + ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), |
| 271 | + ('deleted', models.BooleanField(default=False)), |
| 272 | + ('created', models.DateTimeField(auto_now_add=True)), |
| 273 | + ], |
| 274 | + options={ |
| 275 | + }, |
| 276 | + bases=(models.Model,), |
| 277 | + ), |
| 278 | + migrations.CreateModel( |
| 279 | + name='ArticleRevision', |
| 280 | + fields=[ |
| 281 | + ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), |
| 282 | + ('revision_number', models.IntegerField(verbose_name='revision number', editable=False)), |
| 283 | + ('user_message', models.TextField(blank=True)), |
| 284 | + ('automatic_log', models.TextField(blank=True, editable=False)), |
| 285 | +~~ ('ip_address', IPAddressField(null=True, verbose_name='IP address', blank=True, editable=False)), |
| 286 | + ('modified', models.DateTimeField(auto_now=True)), |
| 287 | + ('created', models.DateTimeField(auto_now_add=True)), |
| 288 | + ('deleted', models.BooleanField(default=False, verbose_name='deleted')), |
| 289 | + ('locked', models.BooleanField(default=False, verbose_name='locked')), |
| 290 | + ('content', models.TextField(blank=True, verbose_name='article contents')), |
| 291 | + ('title', models.CharField(max_length=512, verbose_name='article title', help_text='Each revision contains a title field that must be filled out, even if the title has not changed')), |
| 292 | + ('article', models.ForeignKey(to='wiki.Article', verbose_name='article', on_delete=models.CASCADE)), |
| 293 | + ('previous_revision', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wiki.ArticleRevision')), |
| 294 | + ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, blank=True, to=settings.AUTH_USER_MODEL, verbose_name='user')), |
| 295 | + ], |
| 296 | + options={ |
| 297 | + 'get_latest_by': 'revision_number', |
| 298 | + 'ordering': ('created',), |
| 299 | + }, |
| 300 | + bases=(models.Model,), |
| 301 | + ), |
| 302 | + migrations.CreateModel( |
| 303 | + name='ReusablePlugin', |
| 304 | + fields=[ |
| 305 | + ('articleplugin_ptr', models.OneToOneField(primary_key=True, parent_link=True, to='wiki.ArticlePlugin', serialize=False, auto_created=True, on_delete=models.CASCADE)), |
| 306 | + ('articles', models.ManyToManyField(related_name='shared_plugins_set', to='wiki.Article')), |
| 307 | + ], |
| 308 | + options={ |
| 309 | + }, |
| 310 | + bases=('wiki.articleplugin',), |
| 311 | + ), |
| 312 | + migrations.CreateModel( |
| 313 | + name='RevisionPlugin', |
| 314 | + fields=[ |
| 315 | + ('articleplugin_ptr', models.OneToOneField(primary_key=True, parent_link=True, to='wiki.ArticlePlugin', serialize=False, auto_created=True, on_delete=models.CASCADE)), |
| 316 | + ], |
| 317 | + options={ |
| 318 | + }, |
| 319 | + bases=('wiki.articleplugin',), |
| 320 | + ), |
| 321 | + migrations.CreateModel( |
| 322 | + name='RevisionPluginRevision', |
| 323 | + fields=[ |
| 324 | + ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), |
| 325 | + ('revision_number', models.IntegerField(verbose_name='revision number', editable=False)), |
| 326 | + ('user_message', models.TextField(blank=True)), |
| 327 | + ('automatic_log', models.TextField(blank=True, editable=False)), |
| 328 | +~~ ('ip_address', IPAddressField(null=True, verbose_name='IP address', blank=True, editable=False)), |
| 329 | + ('modified', models.DateTimeField(auto_now=True)), |
| 330 | + ('created', models.DateTimeField(auto_now_add=True)), |
| 331 | + ('deleted', models.BooleanField(default=False, verbose_name='deleted')), |
| 332 | + ('locked', models.BooleanField(default=False, verbose_name='locked')), |
| 333 | + ('plugin', models.ForeignKey(related_name='revision_set', to='wiki.RevisionPlugin', on_delete=models.CASCADE)), |
| 334 | + ('previous_revision', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wiki.RevisionPluginRevision')), |
| 335 | + ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, blank=True, to=settings.AUTH_USER_MODEL, verbose_name='user')), |
| 336 | + ], |
| 337 | + options={ |
| 338 | + 'get_latest_by': 'revision_number', |
| 339 | + 'ordering': ('-created',), |
| 340 | + }, |
| 341 | + bases=(models.Model,), |
| 342 | + ), |
| 343 | + |
| 344 | +## ... source file continues with no further GenericIPAddressField examples ... |
| 345 | + |
| 346 | +``` |
| 347 | + |
0 commit comments