Wednesday, October 23, 2013

Re: Common fields auto values

On 24/10/2013 12:21am, Domagoj Kovač wrote:
> Hi guys,
>
> I have a question. I am working on an application that i can use as a
> starting point for my future projects.
>
> I have a core application that has CommonFields abstract model defined as:
>
> from django.db import models
> from django.contrib.auth.models import User
>
> class CommonFields(models.Model):
>
> created = models.DateTimeField(editable=False, auto_now_add=True)
> created_by = models.ForeignKey(User, related_name="created",
> editable=False)
> modified = models.DateTimeField(editable=False, auto_now=True)
> modified_by = models.ForeignKey(User, related_name="modified",
> editable=False)
> deleted = models.DateTimeField(editable=False)
> deleted_by = models.ForeignKey(User, related_name="deleted",
> editable=False)
>
> class Meta:
> abstract = True
>
> All other models inherit this one.
> I want to populate this fields automatically, something
> like auto_now_add=True but for *_by fields where i want to add current
> user, is there any way that i could do this?

Yes.

See p257-263 of the first edition of Pro Django by Marty Alchin. He
discusses a custom field (CurrentUserField) and middleware to
auto-populate it whenever a model is saved. I see there is a second
edition recently released. I found the entire book to be very valuable.

Recommended

Mike

>
>
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users+unsubscribe@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/15abf5dd-bbe4-4a24-bec2-901ea225f607%40googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5268B99C.1000603%40dewhirst.com.au.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment