【问题标题】:Django Index Error: List Index out of Range using try catchDjango 索引错误:使用 try catch 列出超出范围的索引
【发布时间】:2021-09-10 09:28:27
【问题描述】:

如果字段已发行簿中没有数据,我如何抛出 try catch 异常?我没有将任何数据放入已发行的书以进行调试,我只想让它说“未找到数据”或“您没有发行任何书”

这是我的views.py:

def viewissuedbookbystudent(request):
        student=models.StudentExtra.objects.filter(user_id=request.user.id)
        issuedbook=models.IssuedBook.objects.filter(enrollment=student[0].enrollment)

        li1=[]
        li2=[]

        for ib in issuedbook:
            books=models.Book.objects.filter(isbn=ib.isbn)
            for book in books:
                t=(request.user,student[0].enrollment,student[0].branch,book.name,book.author)
                li1.append(t)
            issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year)
            expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year)
            #fine calculation
            days=(date.today()-ib.issuedate)
            print(date.today())
            d=days.days
            fine=0
            if d>15:
                day=d-15
                fine=day*10
            t=(issdate,expdate,fine)
            li2.append(t)
        context={'li1':li1,'li2':li2}
        return render(request,'library/viewissuedbookbystudent.html',context)

我每次运行时都会收到此错误,我知道这是因为已发行簿字段中没有数据:

IndexError at /viewissuedbookbystudent

list index out of range

Request Method:     GET
Request URL:    http://127.0.0.1:8000/viewissuedbookbystudent
Django Version:     3.2.4
Exception Type:     IndexError
Exception Value:    

list index out of range

Exception Location:     C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py, line 318, in __getitem__
Python Executable:  C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe
Python Version:     3.9.4
Python Path:    

['E:\\C drive\\Users\\Admin\\PycharmProjects\\librarymanagement-master',
 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python39\\site-packages',
 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'

这是我的模板,如果有帮助的话:

<div class="row">

  <div class="col-lg-6" style="padding-right:0px;">
    {% if li1%}
    <table class="redTable">
  <thead>
  <tr>
  <th>Name</th>
  <th>Enrollment</th>
  <th>Branch</th>
    <th>Book Title</th>
      <th>Book Author</th>
  </tr>
  </thead>
  <tfoot>
  <tr>
  <td colspan="5">
  <div class="links"></div>
  </td>
  </tr>
  </tfoot>
  <tbody>
    {% for t in li1 %}
<tr>
  <td>  {{t.0}}</td>
  <td>  {{t.1}}</td>
  <td>  {{t.2}}</td>
  <td>  {{t.3}}</td>
  <td>  {{t.4}}</td>
</tr>

    {% endfor %}
  </tbody>
  </table>

</div>

<div class="col-lg-6" style="padding-left:0px;">

      <table class="redTable">
    <thead>
    <tr>
    <th>Issue Date</th>
    <th>Expiry Date</th>
    <th>Fine</th>
    </tr>
    </thead>
    <tfoot>
    <tr>
    <td colspan="5">
    <div class="links"></div>
    </td>
    </tr>
    </tfoot>
    <tbody>
      {% for t in li2 %}
<tr>
  <td>  {{t.0}}</td>
  <td>  {{t.1}}</td>
  <td>  {{t.2}}</td>
</tr>
      {% endfor %}
    </tbody>
    </table>
    {%else%}
    <h1> No book Issued to you</h1>
    {%endif%}

</div>

</div>
这是models.py:
class StudentExtra(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    enrollment = models.CharField(max_length=40,verbose_name=_('Student ID'))
    course = models.CharField(max_length=40)
    #used in issue book
    def __str__(self):
        return self.user.last_name+'['+str(self.enrollment)+']'
    @property
    def get_name(self):
        return self.user.last_name
    @property
    def getuserid(self):
        return self.user.id

class Category(models.Model):
    class Meta:
        verbose_name = _('Category')
        verbose_name_plural = _('Categories')
        ordering = ['id']

    name = models.CharField(max_length=255, verbose_name=_('Category'))

    def __str__(self):
        return self.name

class Book(models.Model):
    class Meta:
        verbose_name = _('Book')
        verbose_name_plural = _('Books')
        ordering = ['id']

    title=models.CharField(max_length=130)
    isbn=models.PositiveIntegerField()
    author=models.CharField(max_length=140)
    category=models.ForeignKey(Category,on_delete=models.CASCADE)
    def __str__(self):
        return str(self.title)+"["+str(self.isbn)+']'


def get_expiry():
    return datetime.today() + timedelta(days=15)

class IssuedBook(models.Model):
    #moved this in forms.py
    #enrollment=[(student.enrollment,str(student.get_name)+' ['+str(student.enrollment)+']') for student in StudentExtra.objects.all()]
    enrollment=models.CharField(max_length=30)
    #isbn=[(str(book.isbn),book.name+' ['+str(book.isbn)+']') for book in Book.objects.all()]
    isbn=models.CharField(max_length=30)
    issuedate=models.DateField(auto_now=True)
    expirydate=models.DateField(default=get_expiry)
    def __str__(self):
        return self.enrollment

我也有 Traceback: Traceback.png

我可以使用 try catch 修复它吗?如果是,怎么做?

【问题讨论】:

  • 与错误没有直接关系,但是你为什么用.filter()而不是.get()呢?用户 ID 和 ISBN 是唯一的,对吗?对于这些过滤器,您永远不会获得超过一条记录。

标签: python django postgresql django-models django-views


【解决方案1】:

您可以通过以下方式使用消息

查看部分

from django.contrib import messages
def viewissuedbookbystudent(request):
        student=models.StudentExtra.objects.filter(user_id=request.user.id)
        issuedbook=models.IssuedBook.objects.filter(enrollment=student[0].enrollment)

        li1=[]
        li2=[]
        try:
            for ib in issuedbook:
                books=models.Book.objects.filter(isbn=ib.isbn)
                for book in books:
                    t=(request.user,student[0].enrollment,student[0].branch,book.name,book.author)
                    li1.append(t)
                issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year)
                expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year)
                #fine calculation
                days=(date.today()-ib.issuedate)
                print(date.today())
                d=days.days
                fine=0
                if d>15:
                    day=d-15
                    fine=day*10
                t=(issdate,expdate,fine)
                li2.append(t)
            context={'li1':li1,'li2':li2}
            return render(request,'library/viewissuedbookbystudent.html',context)
        except IndexError as e:
            messages.info(request, 'You have no books issued')

模板部分

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

【讨论】:

  • 很抱歉仍然出现同样的错误,并且没有消息出来
  • 然后尝试将try: 行移动到def viewissuedbookbystudent(request): 下方
  • 刚刚在最后一部分使用了它并且它起作用了:除了 IndexError as e: return render(request, 'library/viewissuedbookbystudent.html',{'e':e})
【解决方案2】:

如果您希望引发异常并冒泡给调用者,请执行以下操作:

try:
    this_student = student[0]
except IndexError:
    # Raise whatever exception you want here:
    raise ValueError(f"No student found when processing {whatever}") from None

# now use this_student where you used student[0]

如果您想“处理”IndexError,请执行您需要的任何错误处理/日志记录,以便在该块中“说出”您想要的内容。

或者,您可以检查if len(student) &gt; 0: 并完全避免尝试块。

【讨论】:

  • 对不起,这不是学生,最近刚刚编辑它是已发行的,但我尝试了 this_issuedbook=issuedbook[0] 仍然是同样的错误
【解决方案3】:

你可以使用下面的sn-p:

issuedbook = None
student=StudentExtra.objects.filter(user_id=request.user.id)
try:
   issuedbook=IssuedBook.objects.filter(enrollment=student[0].enrollment)
except IndexError:
   print("No books have been issued yet")

如果您稍后在视图中使用 issuebook,请确保将其声明为 None。您还可以将字符串存储在任何变量的 except 块中,并将其返回到您想要的任何位置。您仍然需要事先将变量声明为 None。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多