In this part, we focus on creating the Users app and all the models related to the User Profile, Authentication, Friends Model and so on

So, in the first part of the tutorial, we learnt how to set up our project and setup various authentication backends and other details regarding various installs and app setups needed in the settings file.

If you have not read the first part yet, make sure to complete it first before moving forward as we would be building on top of that in this part.

There would be lots of terms which you may be encountering for the first time, like you may have heard about views or models for the first time, so I would be briefing about them a little. I cannot talk about those in details because our focus is not to teach you basic concepts, but to build a social media website. So, I would be linking to good resources for you to refer to those specific topics and then continue with this tutorial.

So, let’s go ahead and build the Users app we created in the last tutorial. We will start by creating the models first.

models.py

In this python file, we will define our models. As you might already know, models are defined to tell Django what to save in the database and to define the relationship between different models and what characteristics they have.

To learn more about Django models, do visit this amazing tutorial on models by Mozilla Developers. It talks about models in depth.

After you are comfortable with how models work, you can proceed to make models for our social media website.

So, we will have two models — one for the user’s profile and the other for Friend Requests.

We will need to import many things before we begin writing the models. We will be using the Default User model of Django to have One to One Relationship with our Profile Model i.e. each user will have one profile.

We are also using _autoslug _to automatically produce slugs for the URLs based on the username.

For e.g.: A user with the name Tom would have slug as _tom. _This will help us make meaningful URLs as users/tom will lead to Tom’s profile rather than numbers.

So, to use _autoslug _we need to install it first. It can be done via a simple pip install. Refer below:

pip install django-autoslug

After installing it, we can import it in models.py by using the line:

from autoslug import AutoSlugField

After finishing off all the required imports, we can begin writing the models.

So, our first model is the** Profile** model. It has five parameters:-

  1. user — This is a One to One Relationship with Django User model. The on_delete=models.CASCADE means on the deletion of User, we destroy the Profile too.
  2. image — This will store the profile picture of the user. We have provided a default image also. We need to define where to save the pictures.
  3. slug — This will be the slug field. We use the AutoSlugField and will set it to make slug from the user field.
  4. bio — This will store the small introduction about the user. Here, _blank=True _means it can be left blank.
  5. friends — This is a Many to Many Field with Profile model and can be left blank. It means every user can have multiple friends and can be friends to multiple people.

Next, we describe the_ str_ which decides how Django will show our model in the admin panel. We have set it to show the username as the Query object.

We also define the _get_absolute_url _to get the absolute URL for that profile.

Next, we define a function to make a profile as soon as we create the user so that the user doesn’t have to manually create a profile.

Next, we define our **Friends **Model. It will have three parameters:-

  1. to_user — This denotes the user to whom the friend request will be sent. It will have the same on_delete parameter which decides when the user is deleted, we delete the friend request too.
  2. from_user — This denotes the user who is sending the friend request. It will also be deleted if the user is deleted.
  3. timestamp — It is not really necessary to add. It stores the time when the request was sent.

As you can notice both to_user and _from_user _uses the same ForeignKey so to differentiate we need to use the related_name field.

So, that finishes our models.py file. Have a look at the code below which shows the models.py file.

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils import timezone
from django.db.models.signals import post_save
from django.conf import settings
from autoslug import AutoSlugField

class Profile(models.Model):
	user = models.OneToOneField(User, on_delete=models.CASCADE)
	image = models.ImageField(default='default.png', upload_to='profile_pics')
	slug = AutoSlugField(populate_from='user')
	bio = models.CharField(max_length=255, blank=True)
	friends = models.ManyToManyField("Profile", blank=True)

	def __str__(self):
		return str(self.user.username)

	def get_absolute_url(self):
		return "/users/{}".format(self.slug)

def post_save_user_model_receiver(sender, instance, created, *args, **kwargs):
    if created:
        try:
            Profile.objects.create(user=instance)
        except:
            pass

post_save.connect(post_save_user_model_receiver, sender=settings.AUTH_USER_MODEL)

class FriendRequest(models.Model):
	to_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='to_user', on_delete=models.CASCADE)
	from_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='from_user', on_delete=models.CASCADE)
	timestamp = models.DateTimeField(auto_now_add=True)

	def __str__(self):
		return "From {}, to {}".format(self.from_user.username, self.to_user.username)

After models.py file, we move forward to admin.py file.

#django #python #web-development #programming #developer

Build a Social Media Website with Django  - Users App
2.40 GEEK