簡體   English   中英

django登錄用戶到他們的門戶

[英]django login users to their portal

我有幾個模型,其中之一是擴展django admin的用戶模型的外鍵。 我想在登錄時在其會話中顯示屬於用戶的內容。 我已經定義了此身份驗證,該身份驗證將檢查數據庫中是否存在特定用戶,並將其重定向到與實例的會話。

 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/')

基本上,注冊是第一個模型,也是學生模型的外鍵,而學生也是用戶日志的外鍵。 UserLog擴展了默認的django admin。 我在這里定義了登錄會話,以在登錄時過濾掉各個用戶的詳細信息。

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)

這是在登錄時呈現信息的模板。

 <img
 {% for student in students %}

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

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

 {% endfor %}

但是我收到以下錯誤:

/ studentloggedin /中的ProgrammingError

子查詢返回的多於一行用作表達式

只是想添加模型供您閱讀。

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
    )

您應該這樣查詢學生和所有用戶:

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

注冊和學生是多個對象,即queryset 因此,當查詢具有多個對象的外鍵字段時,我們使用__in

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM