D
D
dark462019-03-28 10:07:17
Django
dark46, 2019-03-28 10:07:17

How to bind post authors (in mini blogs) in django models?

In general, there is a post model:

class Post(models.Model):

    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', args=[str(self.id)])

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    class Meta:
        ordering = ['published_date']

How can I make it so that any user can add any author to himself and, accordingly, display only their posts?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Makarenko, 2019-03-28
@mbrutus

As an option to inherit from the User model and add ManyToManyField to itself

сlass CustomUser(User):
    preferred_author = models.ManyToManyField('self', symmetrical=False, related_name='preferred', ...)

When the user selects a new author, simply add
Next when filtering to display all articles of the authors selected by the user
Where SELECTED_USER is the user for which you want to display articles.
I wrote the code from my head, so I can’t vouch for the accuracy, more for an example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question