Django how to validate if a user already exists

Question:

this is my model

class UserAttributes(models.Model):
    airport = models.ForeignKey('airport.Airport', related_name='user_attributes_airport', on_delete=models.SET_NULL, null=True, blank=True)
    location = PointField(blank=True, null=True)
    user =  models.ForeignKey(
        'users.AerosimpleUser', related_name='user_attributes',
        on_delete=models.CASCADE, null=True, blank=True) 

views.py

class LocationViewSet(viewsets.ModelViewSet):

    serializer_class=LocationRetrieveSerializer
    http_method_names = ['get', 'post', 'patch', 'put']

    def get_permissions(self):
            switcher = {
                'create': [IsAuthenticated],
                'list': [IsAuthenticated],
                'retrieve': [IsAuthenticated],
                'update': [IsAuthenticated],
                'partial_update': [IsAuthenticated],
            }
            self.permission_classes = switcher.get(self.action, [IsAdminUser])
            return super(self.__class__, self).get_permissions()
    def get_queryset(self):
        return UserAttributes.objects.filter(
            airport__id=self.request.user.aerosimple_user.airport_id).order_by('pk')

serializers.py

class LocationRetrieveSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserAttributes
        fields = '__all__'

i want to know if the user or the airport already exists?

Asked By: healer

||

Answers:

On serializer, implement create method so that you can check the user is exist or not.
Example

class LocationRetrieveSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserAttributes
        fields = '__all__'

    def create(self, validated_data):
        if UserAttributes.objects.filter(user=self.context["request"].user).exists():
            raise serializers.ValidationError("User Already exists.")
        user_attributes = UserAttributes.objects.create(**validated_data)
        return user_attributes
Answered By: nayan32biswas

You can check if the user is authenticated by printing the request.user once you go on a specific page (login or signup I’m assuming).

For example:

def view(request):

   user = request.user
   print(user)   # should return username if already logged in

   if user is not None:
      UserAttributes.objects.filter(user=user).exists   # return True/False
      return redirect('home')
   else:
      return redirect('login')

The same method can be used to check if the airport already exists. A try and except like so:

try:
  airport = Airport.objects.get(field=value)
except (Airport.DoesNotExist):
  return 'Airport does not exist'

# or a simple one liner 

from django.shortcuts import get_object_or_404
get_object_or_404(Airport, field=value)
Answered By: vladthelad

From your question, I can see you have a model ‘Airport’ for the airport and ‘AerosimpleUser’ for users and you want to check if the user or airport already exists or not. There are two ways to do that.

  1. Make username in AerosimpleUser as a primary key. So when you try to make another user with the same username it will through an error. You have to do the same with the Airport, you can make the airport code/name the primary key.

  2. Another approach is whenever you are creating a new user or airport to can filter it and check if the user or airport exist or not.

    For Example:

    try:
        airport_obj = Airport.objects.get(name='XYZ')
    except Exception:
        print('Airport Not EXIST.')```
    
    
    
Answered By: Sahil Rajput

You can check username by checking if the object is present in the query.

from django.contrib.auth import authenticate
from rest_framework.decorators import api_view
from django.contrib.auth import get_user_model

User = get_user_model() #custom model

@api_view(['POST'])
def youView(request):
    username = request.data.get('username')

    #if username already exists
    user = User.objects.filter(username=username).exists()
    
    if user: #username exists
        #your logic here
    else: #username does not exist
        #your logic here
Answered By: Maaz Bin Mustaqeem