Step by Step guide to add friends with Django
Want to have Add Friend , Send Friend Request , Accept Friend Requests features in your Django website ? Then please read this article :
Step 1 : Having some sort of profile model or custom user
Why do we need a custom user model or a profile model? This profile model or custom user model will have a friends field where we will store all friends for a particular user
I am using custom user model and it has a ManyToManyField friends which refers back to this user model.
Step 2 : Creating the friend request model
This friend request model will store the friend requests info i.e who send request to whom.
This friend request model will have two fields :
- from user : it will have a foreignkey relation with a user(first user) who is sending this request,
- to user : it will also have a foreignkey relation with another user(second user) to whom the first user is sending the request.
Make Sure the fields have related_name and they have different names.
Then Migrate the models.
Authenticating User (Optional)
If you have started from scratch with this tutorial or you don’t have setup your authentication system yet then you might follow those steps as well.
I have moved those steps below !
Step 3: Creating Views for Friend Request
1. Send Friend Request
- we get the user id whom we will send friend request
- create a new friend request instance where we set to_user = the user whom the request will be sent to ,
- from_user will be the user who is sending the request i.e request.user or current user
2. Accept Friend Request
- we get the request id of the request we are going to accept
- also we make sure that to_user of the request is the current user i.e the user whom the request is sent is the current user accesing the request ,
- then we add the current user to from_user’s ( the user who sent the request) friends field
- we also add the from_user to the current user’s friends field
Step 4 : Creating urls
Step 5 : Templates
- I display all users in a list and every user has a href which when clicked will send a friend request to that user.
2. I display here all friend requests sent to the current user which has a href which when clicked will accept the friend request and both the users will be friends.
Thats it ! We are done here !
Optional Step before Step 3 : Authenticating User
Add AUTH_USER_MODEL in settings.py
Here users.User means User model in users app
1. Creating User Forms :
2. Creating Signup View :
import these in views.py
Then create the signup view: (very basic authentication)