Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto insert the current user when creating an object in django admin?

I have a database of articles with a

submitter = models.ForeignKey(User, editable=False) 

Where User is imported as follows:

from django.contrib.auth.models import User.  

I would like to auto insert the current active user to the submitter field when a particular user submits the article.

Anyone have any suggestions?

like image 283
FurtiveFelon Avatar asked Jun 07 '10 16:06

FurtiveFelon


People also ask

How does Django get current user information?

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting. request. user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.

Does Django automatically create ID?

Django will create or use an autoincrement column named id by default, which is the same as your legacy column.

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.


1 Answers

Just in case anyone is looking for an answer, here is the solution i've found here: http://demongin.org/blog/806/

To summarize: He had an Essay table as follows:

from django.contrib.auth.models import User  class Essay(models.Model):     title = models.CharField(max_length=666)     body = models.TextField()     author = models.ForeignKey(User, null=True, blank=True) 

where multiuser can create essays, so he created a admin.ModelAdmin class as follows:

from myapplication.essay.models import Essay from django.contrib import admin  class EssayAdmin(admin.ModelAdmin):     list_display = ('title', 'author')     fieldsets = [         (None, { 'fields': [('title','body')] } ),     ]      def save_model(self, request, obj, form, change):         if getattr(obj, 'author', None) is None:             obj.author = request.user         obj.save() 
like image 158
FurtiveFelon Avatar answered Sep 22 '22 15:09

FurtiveFelon