having problem in login rest API

33 views
Skip to first unread message

laya

unread,
Jul 8, 2019, 12:12:31 AM7/8/19
to django...@googlegroups.com

Hi,

Please help me in this part, I stuck in some days,

My project is about a university system which professors and students can sign up and login. I use Custom User Django which inherits User Django Model. It should be mentioned that login is by identity number and Student-no and Professor-no.

My codes are as follow:

Models.py:

class CustomUser(AbstractUser):
    USER_TYPE_CHOICES = ((
1, 'student'),
                        
(2, 'professor'),)
    username = models.CharField(
max_length=50, unique=True)
    user_type = models.PositiveSmallIntegerField(
choices=USER_TYPE_CHOICES, null=True)
    first_name = models.CharField(
max_length=50)
    last_name = models.CharField(
max_length=100)
    identity_no = models.PositiveIntegerField(
default=0)
    email = models.EmailField(
max_length=300,
                             
validators=[RegexValidator
                                          (
regex="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.["r"a-zA-Z0-9-.]+$",
                                           
message='please enter the correct format')],
                             
)
    date_joined = models.DateTimeField(
'date joined', default=timezone.now)
    is_active = models.BooleanField(
default=True)
    is_admin = models.BooleanField(
default=False)
    is_staff = models.BooleanField(
default=False)


class Student(models.Model):
    user = models.OneToOneField(CustomUser
, on_delete=models.CASCADE)
    entry_year = models.PositiveIntegerField()
    student_no = models.PositiveIntegerField()

   
def get_full_name(self):
       
return self.user.first_name +" "+ self.user.last_name

   
def __unicode__(self):
       
return self.user.first_name +" "+ self.user.last_name

   
def __str__(self):
       
return self.user.first_name +" "self.user.last_name

 

serializers.py:

 

"""STUDENT LOGIN"""
class StudentLoginSerializer(serializers.ModelSerializer):
    user = CustomUserSerializerForLogin()

   
class Meta:
        model = Student
        fields = [
           
"user",
            
"student_no", ]

   
def validate(self, data):  # validated_data
       
user_data = data.pop('user', None)
        identity_no = user_data.get(
'identity_no')
       
print("identity_no", identity_no)
        student_no = data.get(
"student_no")
        user = Student.objects.filter(
            Q(
user__identity_no=identity_no) |
            Q(
student_no=student_no)
        ).distinct()
       
# user = user.exclude(user__identity_no__isnull=True).exclude(user__identity_no__iexact='')
       
if user.exists() and user.count() == 1:
            user_obj = user.first()
       
else:
           
raise ValidationError("This username or student_no is not existed")
       
if user_obj:
           
if not user_obj.check_password(student_no):  # Return a boolean of whether the raw_password was correct.
               
raise ValidationError("Incorrect Credential please try again")
       
return user_obj

Views.py:


class StudentLoginView(APIView):
    queryset = Student.objects.all()
    serializer_class = StudentLoginSerializer
   
def post(self, request, *args, **kwargs):
        data = request.data
        serializer = StudentLoginSerializer(
data=data)
       
if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
           
return Response(new_data, status= HTTP_200_OK)
       
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

Error:

The error is about check_password attribute which is not existing in Student Object.

 

 

Sent from Mail for Windows 10

 

Aldian Fazrihady

unread,
Jul 8, 2019, 12:19:10 AM7/8/19
to django...@googlegroups.com
It is in user object instead of student object,  right? 

Regards,

Aldian Fazrihady
http://aldianfazrihady.com

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5d22c291.1c69fb81.81d84.d526%40mx.google.com.
For more options, visit https://groups.google.com/d/optout.

laya

unread,
Jul 8, 2019, 12:21:39 AM7/8/19
to django...@googlegroups.com

Yes Check_password attribute is in Django user model and when I write Customuser. Objects.filter() it errors that Student_no is not an attribute for User Django Model.

 

Sent from Mail for Windows 10

 

Sidnei Pereira

unread,
Jul 8, 2019, 11:02:54 AM7/8/19
to Django users
If would like to access CustomUser's attributes directly from an student instance you should use Multi-table Inheritance - a concrete model class that inherits from another, so `class Student(CustomUser)`. But if you want to keep the relationship using explict OneToOne like you did, maybe it's better to query on CustomUser instead of Student model, like this:

```
user = CustomUser.objects.filter(
            Q(identity_no=identity_no) |
            Q(student__student_no=student_no)
        ).distinct()
``` 

It will bring CustomUser objects (wich have the `check_password` method) instead of Student objects

To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.

To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

Reply all
Reply to author
Forward
0 new messages