Skip to content
Advertisement

(django) Showing posts according to interests of users

I am pretty new to Django and still learning it, but I have to create something like medium.com. I want to show posts to users according to their interests. I added an interests field with a checkbox in a sign-up form. And of course, I added a category to the Post model. So, how can I show (to logged-in users only) publications that they interested in? Here is my models.py file in posts app

JavaScript

And here is my vies.py file in posts app

JavaScript

Here is my index.html file

JavaScript

This is my forms.py file in accounts app

JavaScript

And lastly this views.py file in accounts app

JavaScript

I have no idea how to do this, but I know that I have to do something in the views.py file in the posts app, however, I do not know what to do. Will be really grateful if you could help me.

Advertisement

Answer

I would make another model Category. Since it will be its own model, you will be able to add future categories on the fly if needed, rather than having those hardcoded choices.

JavaScript

Then your User and Post model will each have a ManytoMany field related to category. Posts can be tagged as certain categories when they are created, and Users will be able to select a number of categories that they are interested in and have them stored in this field:

JavaScript
JavaScript

You can make use of a forms.modelChoiceField which will enable your user to select a category.

In your PostListView, all you need to do is change the get_queryset method to filter for posts that the user likes.

JavaScript

Then, you should get the posts that share categories with the user’s interests.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement