Skip to content

Commit

Permalink
Added saving current user while saving
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Feb 19, 2018
1 parent 4910f12 commit c1a3766
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
31 changes: 30 additions & 1 deletion docs/current_user.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,31 @@
How to associate model with current user while saving?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

The :code:`Hero` model has the following field.::

added_by = models.ForeignKey(settings.AUTH_USER_MODEL,
null=True, blank=True, on_delete=models.SET_NULL)


You want the :code:`added_by` field to be automatically set to current user whenever object is created from admin. You can do this.::

def save_model(self, request, obj, form, change):
if not obj.pk:
# Only set added_by during the first save.
obj.added_by = request.user
super().save_model(request, obj, form, change)

If instead you wanted to always save the current user, you can do.::

def save_model(self, request, obj, form, change):
obj.added_by = request.user
super().save_model(request, obj, form, change)

If you also want to hide the :code:`added_by` field to not show up on the change form, you can do.::


@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
exclude = ['added_by',]

9 changes: 8 additions & 1 deletion heroes_and_monsters/entities/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,14 @@ class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
list_filter = ("is_immortal", "category", "origin", IsVeryBenevolentFilter)
actions = ["mark_immortal"]

list_per_page = sys.maxsize
exclude = ['added_by',]

def save_model(self, request, obj, form, change):
if not obj.pk:
# Only set added_by during the first save.
obj.added_by = request.user
super().save_model(request, obj, form, change)


def mark_immortal(self, request, queryset):
queryset.update(is_immortal=True)
Expand Down
6 changes: 6 additions & 0 deletions heroes_and_monsters/entities/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django.db import models

from django.conf import settings


class Category(models.Model):
name = models.CharField(max_length=100)
Expand Down Expand Up @@ -41,6 +43,10 @@ class Entity(models.Model):
)
description = models.TextField()

added_by = models.ForeignKey(settings.AUTH_USER_MODEL,
null=True, blank=True, on_delete=models.SET_NULL)
added_on = models.DateField(auto_now=True)

def __str__(self):
return self.name

Expand Down

0 comments on commit c1a3766

Please sign in to comment.