Pre-populating data in the admin panel

I have always found it awkward working with sites and user's in django admin panel. James Bennet from b-list.org explained his way of doing it on his blog, but I found his way a bit limiting, I still want superusers to be able to change the author of a post.

After looking around in the source code for ModelAdmin I found two method's, one of which was not documented. These were formfield_for_manytomany and formfield_for_foreignkey. These methods allow us to supply our own FormField, which could have initial data. These methods also get passed the HttpRequest, which contains the user. So we can fill in author of a blog post and the current site.

In this post I will quickly show you how to use this method to fill in current data based upon the request inside the admin.

My model

Here is a model from which the rest of the article will work from.

from django.db import models
from django.contrib.sites.models import Site
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField(blank=True)

    sites = models.ManyToManyField(Site)
    author = models.ForeignKey(User)

As you can see, the author is a ForeignKey field, and sites is a ManyToMany field. The methods we use to set the default reflects this. We use formfield_for_foreignkey to set the default user.

Here is my ModelAdmin class

class PostAdmin(admin.ModelAdmin):
    fieldsets = (
    (None, {
        'fields': ('title', 'content',)
    }),
    ('Advanced options', {
        'classes': ('collapse',),
        'fields': ('author', 'sites',)
    })
)

admin.site.register(Post, PostAdmin)

Selecting the current site

To select the current site, what we will do is create a method called formfield_for_manytomany inside our PostAdmin class. This method will be called each time the admin panel goes to draw a ManyToMany field in a Post. So all we do is set the initial value to the current site. But it is important to remember that the field may be something else, so it is important to check if it is the sites field.

def formfield_for_manytomany(self, db_field, request, **kwargs):
    if db_field.name == 'sites':
        kwargs['initial'] = [Site.objects.get_current()]
        return db_field.formfield(**kwargs)

    return super(PostAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

Selecting the current user

This is very similar to selecting the current site, instead we create a method called formfield_for_foreignkey for ForeignKey's instead of ManyToMany fields.

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == 'author':
        kwargs['initial'] = request.user.id
        return db_field.formfield(**kwargs)

    return super(PostAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Now that we have selected the current user, it would be nice to only let superusers use this field, but I couldn't find a way to only show this for certain users. So instead we will just disallow normal user's from saving the post as another user.

I dont think it is possible to optionally hide the author field from a user, so what I have done was to disallow a non superuser from editing the post's author.

Disallowing a user from changing another post

def has_change_permission(self, request, obj=None):
    has_class_permission = super(PostAdmin, self).has_change_permission(request, obj)

    if not has_class_permission:
        return False

    if obj is not None and not request.user.is_superuser and request.user.id != obj.author.id:
        return False

This snippet was not written by myself, but by James Bennet from b-list.org.

Only let the user view their own posts

Another measure to limit the possibilities of the user can be to let the user only view their own posts. To do this we just change the queryset to filter posts where the author is themselves. We still want superusers to see all posts, so only filter it for normal users.

def queryset(self, request):
    if request.user.is_superuser:
        return Post.objects.all()
    return Post.objects.filter(author=request.user)

To see a complete example of this you can view the source code for lithium.

Posted on: 2009 Jul 01

Comments

Asinox http://www.asinox.net/

Hi, nice post , thanks, i would like to do something like formfield_for_foreignkey, but how ill get a field from another Models and compare , or from the form of the another Models in the admin?

thanks

Scot Hacker http://birdhouse.org/blog

Super helpful, thanks.

kwargs['initial'] = request.user.id

Was exactly what I was looking for. Rock.

RUBY29RB http://www.4writers.net/

The [HTML_REMOVED]freelance writers [HTML_REMOVED] won’t solve all problems, thus, it is available to get required information just about this good topic.

tessypeWrassy http://www.eministreet.com/

Hello swantosad [HTML_REMOVED]effexor pills[HTML_REMOVED] The chemical messenger which Effexor works on is known as Serotonin. [HTML_REMOVED]generic effexor online[HTML_REMOVED] SSRI's(selective serotonin reuptake inhibitors) are a group of medications that help combat the symptoms associated with anxiety disorders and depression. http://goanmaps.com/ - effexor price This in turn leads to a more calm peaceful state of mind, and can help even those in the darkest pit of depression find a solution.

thesis http://www.topthesis.com/

Oh, fantastic theme referring to this good topic. Will please say me how long period of time that can take? Just because I would like to do the thesis report or may be this would be good to detect the [HTML_REMOVED]buy dissertation[HTML_REMOVED] service. Thank you so much.

essay writing http://www.exclusivepapers.com/

There’re numbers of reasons to [HTML_REMOVED]order essay[HTML_REMOVED] referring to this good topic from the creative writing service. People should know that an academic success depends on famous quality [HTML_REMOVED]university essay[HTML_REMOVED]. Thus, this is your selection to perform the custom research papers or to utilize a help of the professional writing organization.

dissertation writing http://www.exclusivethesis.com/

It takes hard work and time to write the thesis report referring to this good post, thus, I prefer to detect the [HTML_REMOVED]thesis writing[HTML_REMOVED] service to reach the PhD degree.

buy an essay http://www.qualityessay.com/

It's not so easy to make a smashing custom essay, especially if you are intent. I advise you to notice [HTML_REMOVED]buy an essay[HTML_REMOVED] and to be void from scruple that your work will be done by writing service

thesis writing http://www.master-dissertations.com/

Students have got nowadays great Internet sources to buy the thesis topic or well done data about this good topic in the trustworthy [HTML_REMOVED]thesis service[HTML_REMOVED].

submit article http://www.4submission.com/

Do you seek to make your article just about this post really best-selling with the assistance of the [HTML_REMOVED]article submission[HTML_REMOVED]? If not, I would like to offer to detect the article submission tools! Hope that the suggestion would help!

Baxysocuous http://loveepicentre.com/

desire easy discreet couples dating [HTML_REMOVED]submissive female personals[HTML_REMOVED] asemblies of god singles http://loveepicentre.com/ dating for big people

Energy http://earth4energyweb.co.cc/

I dont think it is possible to optionally hide the author field from a user, so what I have done was to disallow a non superuser from editing the post's author.

That is really a clever move, might have to use it when editing code.

Speedlile http://www.hqlaptopbatteries.com/battery-5023wlmi-batterytype1.html

Clevo Laptop [HTML_REMOVED]laptop comparison[HTML_REMOVED] High quality discount laptop battery store http://www.hqlaptopbatteries.com/-3003wlci-laptopbatterymodel1373.html best laptops buy Laptop Battery [HTML_REMOVED]Laptop AC Adapter[HTML_REMOVED] Fujitsu laptop battery http://www.hqlaptopbatteries.com/-n3270-laptopbatterymodel579.html laptop brands toshiba laptop batteries [HTML_REMOVED]Alienware Laptop[HTML_REMOVED] laptop batteries reviews http://www.hqlaptopbatteries.com/-6400-laptopbatterymodel712.html Fujitsu laptop battery

alteseediewib http://www.cardvdplanet.com/1-din-large-screen-online-store5.html

auto audio advice [HTML_REMOVED]selling auto audio[HTML_REMOVED] audiovox auto dvd http://www.cardvdplanet.com/car-cd-mp3-player-with-usb-sd-mmc-cd145--discount-price58.html custom auto audio systems auto dvd player [HTML_REMOVED]d mercedes benz reviews auto extended warranty car audio and[HTML_REMOVED] calgary 32nd ave ne auto audio store http://www.cardvdplanet.com/shadow-chrome-stylish-touch-screen-car-dvd-with--discount-price7.html jvc auto audio manuals beststuff fuel car dvd ipod vacation houseboat lake powell home [HTML_REMOVED]auto dvd[HTML_REMOVED] car audio subwoofer alpine plt 5 ford 2002 f150 supercrew http://www.cardvdplanet.com/?action=contact_us d mercedes benz reviews auto extended warranty car audio and