A
A
AlexRAV2016-11-03 13:59:43
Django
AlexRAV, 2016-11-03 13:59:43

How to connect the user model and his posts?

I can’t figure out how to do it, I need each post to have its own author. At the same time, so that when I added a post from the admin panel, the author could not be selected, but he was selected automatically. I found how to make it so that an authorized user is automatically inserted into the select, but if I hide the field with the user, then nothing works, and if I myself add the field with the user when adding a post to POST, it is not saved in the model.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-11-03
@AlexRAV

class Publication(models.Model):
    author = models.ForeignKey(User, verbose_name=u'Автор')

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question