M
M
mr_forlife2021-06-04 21:19:44
Django
mr_forlife, 2021-06-04 21:19:44

How to initialize formset in Django admin?

There are two models:

Post

class Post(models.Model):
    title = models.CharField(max_length=150, db_index=True, verbose_name='Заголовок')
    body = models.TextField(verbose_name='Текст поста')
    author = models.ForeignKey(AdvancedUser, on_delete=models.PROTECT, verbose_name='Автор', related_name='posts')
    post_date = models.DateTimeField(auto_now=True, verbose_name='Дата публикации')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Пост'
        verbose_name_plural = 'Посты'
        ordering = ('-post_date',)


and
Comment

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name='Пост')
    author = models.ForeignKey(AdvancedUser, on_delete=models.PROTECT, verbose_name='Автор')
    comment_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата комментария')
    comment_text = models.TextField(verbose_name='Комментарий', help_text='Допускается использование HTML разметки.')

    def __str__(self):
        return f'Comment to {self.post} post'

    class Meta:
        ordering = ('comment_date',)


related ForeignKeys.

The comment has an author.
In the admin panel, I display the post editing form and the formset to it with the comments left.
How can I initialize the "Author" field in the formset only for a new comment with the name of the current logged in user, while not changing this field for already existing comments?

screenshot
60ba6e2f7b70d534915034.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question