简体   繁体   中英

django login users to their portal

I have couple of models and one of them is a foreign key to the user model that's extending django admin. I want to display what belongs to a user in their session upon login. I have defined this authentication that will check whether a particular user exist within the database and redirect them to their session with their instances.

 def auth_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)

   if user is not None:
      auth.login(request, user)
      return HttpResponseRedirect('/studentloggedin/')

Basically, Registration is the first model and a foreign key to Student model, while Student is also a foreign key to UserLog. UserLog is extending the default django admin. I've defined the loggedin session here to filter out details of the individual users upon login.

def studentloggedin(request):
   registration = Registration.objects.all()
   students = Student.objects.filter(registration=registration)
   alluser = UserLog.objects.filter(student=students)
   context = {
     'registration': registration,
     'students': students,
     'alluser': alluser,

   }
   return render(request, "studentloggedin.html", context)

Here is the template rendering the information upon login.

 <img
 {% for student in students %}

 src="{{ student.student_photo.url }}">

 <p>{{ student.previous_school }}</p>

 {% endfor %}

But I'm getting the below error:

ProgrammingError at /studentloggedin/

more than one row returned by a subquery used as an expression

Just thought to add the models in for your perusal.

class Registration(models.Model):

    lastName = models.CharField(
        _('Last Name'),
        max_length=30,
        null=False,
        blank=False
    )

    middleName = models.CharField(
        _('Middle Name'),
        max_length=30,
        null=True,
        blank=True
    )

    firstName = models.CharField(
        _('First Name'),
        max_length=30,
        null=False,
        blank=False
    )

    gender = models.CharField(
        _('Gender'),
        max_length=30,
        choices=GENDER_CHOICES,
        default=u' ',
        null=False,
        blank=False
    )

    grade = models.CharField(
        _('Class'),
        max_length=30,
        choices=CLASS_CHOICES,
        default=u' ',
        null=False,
        blank=False
    )

    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{9,15}$',
        message="Phone number format: '+999999999'. Up to 15 digits allowed."

    )
    phone_number = models.CharField(
        _('Phone Number'),
        max_length=255,
        validators=[phone_regex],
        blank=True
    )

    email = models.EmailField(
        _('Email Address'),
        max_length=254,
        null=True,
        blank=True
    )

    address = models.CharField(
        _('Address'),
        max_length=255,
        null=False,
        blank=False
    )

    city = models.CharField(
        _('City'),
        max_length=30,
        null=False,
        blank=False
    )

    county = models.CharField(
        _('County'),
        max_length=30,
        choices=COUNTY_CHOICES,
        default=None,
        null=False,
        blank=False
    )

    nationality = models.CharField(
        _('Nationality'),
        max_length=30,
        null=False,
        blank=False
    )

    dateOfBirth = models.DateField(
        _('Date of Birth'),
        max_length=30,
        null=False,
        blank=False
    )

    placeOfBirth = models.CharField(
        _('Place of Birth'),
        max_length=255,
        null=False,
        blank=False
    )

    regDate = models.DateField(
        _('Registration Date'),
        max_length=30,
        null=False,
        blank=False
    )

    country = models.CharField(
        _('Country'),
        max_length=255,
        null=False,
        blank=False
    )

    emergency = models.CharField(
        _('Emergency Contact'),
        max_length=255,
        null=True,
        blank=True
    )

    emergency_phone = models.CharField(
        _('Phone (Emergency Contact)'),
        max_length=255,
        validators=[phone_regex],
        blank=True
    )

    transcript = models.FileField(
        _('Transcript'),
        max_length=255,
        null=True,
        blank=True
    )

    created = models.DateTimeField(
        _('Date Created'),
        auto_now=True,
        null=True,
        blank=True
    )
    modified = models.DateTimeField(
        _('Date Modified'),
        auto_now_add=True,
        null=False,
        blank=False
    )

    def __str__(self):
        return self.firstName

    def age(self):
        import datetime
        return int((datetime.date.today() - self.dateOfBirth).days / 365.25)


    def upload_location(instance, filename):
        return "%s/%s" % (instance.id, filename)


class Student(models.Model):

    import datetime
    YEAR_CHOICES = []
    for r in range(1980, (datetime.datetime.now().year+1)):
        YEAR_CHOICES.append((r, r))

    studentID = models.CharField(
        _('Student ID'),
        max_length=30,
        blank=True,
        default=''

    )

    registration = models.ForeignKey(
        Registration
    )

    student_photo = models.ImageField(
        _('Picture'),
        max_length=255,
        null=False,
        blank=False,
        upload_to=upload_location
    )

    previous_school = models.CharField(
        _('Previous School Attended'),
        max_length=255,
        null=False,
        blank=False
    )

    previous_school_address = models.CharField(
        _('Previous School Address'),
        max_length=255,
        null=False,
        blank=False
    )

    last_year_attendance = models.IntegerField(
        _('Last Year of Attendance'),
        choices=YEAR_CHOICES,
        default=datetime.datetime.now().year
    )

    level = models.CharField(
        _('Level'),
        max_length=255,
        choices=LEVEL_CHOICES,
        default=None,
        null=False,
        blank=False
    )

    enrollment_status = models.CharField(
        _('Enrollment Status'),
        max_length=255,
        choices=ENROLLMENT_CHOICES,
        default=None,
        null=False,
        blank=False
    )

    enrollment_Date = models.DateField(
        _('Enrollment Date'),
        max_length=30,
        null=False,
        blank=False
    )

    created = models.DateTimeField(
        _('Date Created'),
        auto_now=True,
        null=True,
        blank=True
    )
    modified = models.DateTimeField(
        _('Date Modified'),
        auto_now_add=True,
        null=False,
        blank=False
    )

    class Meta:
        ordering = ["-id"]

    def __str__(self):
        return self.studentID

    def save(self, force_insert=False, force_update=False):
        if self.studentID == "":
            existing_studentIDs = Student.objects.all().order_by('-studentID')
            if existing_studentIDs.count() > 0:
                new_code = int(existing_studentIDs[0].studentID[1:]) + 1
            else:
                new_code = 0
            self.studentID = 'S%03d' % new_code
        super(Student, self).save(force_insert, force_update)

class UserLog(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    student = models.ForeignKey(
        Student,
        null=True,
        blank=True,
        default=None
    )

    staff = models.ForeignKey(
        Staff,
        null=True,
        blank=True,
        default=None
    )

    parent = models.ForeignKey(
        Parent,
        null=True,
        blank=True,
        default=None
    )

You should query students and alluser this way:

students = Student.objects.filter(registration__in=registration)
alluser = UserLog.objects.filter(student__in=students)

registration and students are multiple objects ie queryset . Therefore when querying a foreign key field with multiple objects, we use __in .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM