Default values when creating new row in Django Admin

In one of the apps I’m developing at work, I wanted to make it easy for our content admins to create a new row in the Django Admin. Most of the time, they need to create a new row that is associated to their own user account. It would save them a couple of steps if the user field is set to a default value. Thanks to my coworker, Dave Ziegler,  for helping me  figure this out.

Extra tip:
use raw_id_fields in Django Admin. This is especially useful when you have plenty of users. What you’ll see is the id of the user in the text field with a link to look up users next to it (instead of a dropdown containing usernames of all the users).
If you don’t set the raw_id_fields, it would take a long time for Django Admin to load the ‘Change ‘ page since all the users in your database needs to be loaded.

  • panchicore

    thanks danny, this solved me a headache.
    what about edit view and delete confirm view?

    • dannyroa

      panchicore,

      It's about setting a default for a new record. For edit & delete view, that value is already set.

      However, if you want to show rows for a particular user, see below:

      class MyModelAdmin(admin.ModelAdmin):
      def queryset(self, request):
      qs = super(MyModelAdmin, self).queryset(request)
      return qs.filter(author=request.user)

      • panchicore

        Ok thanks for you answer, but I reffer to other thing, example:

        If I want to do something aditional when deleting an object in admin-site, I have to hack it like this?

        def delete_view(self, request, object_id, extra_context=None):
        print “-deleting-“
        return super(PostAdmin, self).delete_view(request, object_id, extra_context=extra_context)

        I tried (off course with the right class) but “-deleting-” is not printing.

        what about that?

        • dannyroa

          Print will not work server-side.

          You need to use some logging. You can try jogging (http://github.com/zain/jogging).

          • panchicore

            thanks for your quick reply :). ok I tried with a mesagger_user. and nothing :(

            def delete_view(self, request, object_id, extra_context=None):
            self.message_user(request, “DELETING:” + object_id)
            super(PostAdmin, self).delete_view(request, object_id, extra_context=extra_context)

          • dannyroa

            You need to install django-jogging as an app in your project.