There is such a model:

class NewsContent(models.Model): title = models.CharField(_('Title'), max_length=255) author = models.ForeignKey(User, blank=True, null=True, verbose_name = _('Author')) content = models.TextField(_('Content')) 

It is necessary that in the django admin area when creating new news content, the current user is selected by default as the author.

    5 answers 5

    I answer my own question. In the depths of django found the code where you can infiltrate without any problems, and with access to request. It turned out very beautiful.

     class NewsContentAdmin(admin.ModelAdmin): def formfield_for_dbfield(self, db_field, **kwargs): field = super(NewsContentAdmin, self).formfield_for_dbfield(db_field, **kwargs) if db_field.name == "author": field.initial = kwargs["request"].user.id return field 
    • one
      cool, mark as correct - rnd_d 5:44 pm
    • The hashcode does not allow the response to be marked as correct. Perhaps this is correct. - Antik
    • one
      @Antik Your answer can be answered as correct (a check mark will appear) two days after the answer is published. - Nicolas Chabanovsky

    Create a custom form for your model and redefine the admin view to edit this model, in this view, request.user, which you pass to the form as initial data (or pass it as a parameter to the form constructor). Perhaps for such a small task this solution is rather difficult, but this is a documented opportunity (not a crutch) and when moving to newer versions of the framework, you will not be able to do anything.
    How to create custom admin forms / views for your models is described in detail in the official documentation .

      Since there are no answers, I can offer or do it all on js, or make the user choose only himself:

      if so

       author = models.ForeignKey(User, blank=False, null=False, verbose_name = _('Author')) 

      then in admins.py

       class NewsContentAdmin(admin.ModelAdmin): """Ващ класс для админки для данной модели """ def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "author": kwargs["queryset"] = Users.objects.filter(pk = request.user.pk) return super(NewsContentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) 

        Here they write about the js solution.

          Override the save_model method of the ModelAdmin class and add the user there.

          In your case it will look something like this:

           class NewsContentAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if not change: obj.author = request.user obj.save()