Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-populating created_by field with Django admin site

Tags:

I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..

Consider the following:

class Contact(models.Model):     name = models.CharField(max_length=250, blank=False)     created_by = models.ForeignKey(User, blank=False) 

I can't find a way to auto-populate the created_by field and make the Django admin aware of it. Most of the method I've seen implies overloading the Object's save method and pass it the request user. They all requires to build your custom views and/or forms.

Optimally the form to create new contacts in the admin site should not show the created_by field (which is quite easy) and auto-populate it with the current user (which seems harder than it should).

like image 455
h3. Avatar asked May 13 '09 02:05

h3.


People also ask

How do I automatically register all models in Django admin?

To automate this process, we can programmatically fetch all the models in the project and register them with the admin interface. Open admin.py file and add this code to it. This will fetch all the models in all apps and registers them with the admin interface.

How do you make a field required in Django admin?

Making Fields Required In Django Admin In order to make the summary field required, we need to create a custom form for the Post model. I am making them on the same file you can do this on a separate forms.py file as well.

How do you make a field non editable in Django admin?

editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form.

What is Fieldsets in Django admin?

fieldsets is a list of two-tuples, in which each two-tuple represents a <fieldset> on the admin form page. (A <fieldset> is a “section” of the form.)


2 Answers

http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser

Involves implementing save methods on your ModelAdmin objects.

like image 99
jsamsa Avatar answered Oct 07 '22 16:10

jsamsa


You need to specify a default for the field, in this case a method call that gets the current user (see the auth documentation to get the current user).

like image 38
Tom Leys Avatar answered Oct 07 '22 16:10

Tom Leys