Py学习  »  Django

在Django html页面显示外键

ice916 • 8 年前 • 3467 次点击  

下是modles.py资料库

class bookinfo (models.Model):
    info = models.CharField(max_length=225)

class  book (models.Model):
    name = models.CharField(max_length=20,null=True)
    date_time = models.DateTimeField()

    info = models.ForeignKey(bookinfo)
    user = models.ForeignKey(User)

由于书的资讯只存「推荐」「考虑」「不推荐」三种结果,因此想用一对多外键处理这三种结果

下是views.py查询程式码

 test02 =book.objects.filter(user = request.user).order_by('-id')

结果显示错误,下是错误资讯 invalid literal for int() with base 10: '推荐'

我html显示全部是这样写

 {% for r in test02 %}

            <tr>                             
      <td align="center"> <h4>{{ r.date_time }}</h4> </td>  
      <td align="center"> <h4>{{ r.name }}</h4> </td>
      <td align="center"> <h4>{{ r.info }}</h4></td>
            </tr>
{% empty %}
             <h3>目前未有任何紀錄!</h3>
{% endfor %}

有解决方法吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/1236
 
3467 次点击  
文章 [ 13 ]  |  最新文章 8 年前
MCC
Reply   •   1 楼
MCC    8 年前

invalid literal for int() with base 10: '推荐'

我觉得最好还是先定位这个报错的位置

不过这个t如果这么用肯定有问题。。。

t = open(file_time +"book_info.txt", 'r')
for i in t.read():
     #blahblah
ice916
Reply   •   2 楼
ice916    8 年前

@MCC

这的t是开启文字檔

t = open(file_time +"book_info.txt", 'r')

流程是这样的

views读取txt内容,判断有无'推荐'、'考虑'评价

最后再把外键指定好后

使用

book.objects.create(host = host, date_time = date_time , result = result ,user = request.user)

存进资料库

MCC
Reply   •   3 楼
MCC    8 年前

t是什么 @ice916

ice916
Reply   •   4 楼
ice916    8 年前

@MCC

下面是我的views写法

def book (request):

for i in t:
          if i.find('推荐') != -1:
                result = bookinfo.objects.get(id =1)
                break
            if i.find('考虑') != -1:
                result = bookinfo.objects.get(id =2)
                break
            else:
                result = bookinfo.objects.get(id =3)                    
        book.objects.create(host = host, date_time = date_time , result = result ,user = request.user)

return HttpResponseRedirect('/test02')


def test02 (request):
 test02 =book.objects.filter(user = request.user).order_by('-id')
return render(request,'test02.html', locals())
MCC
Reply   •   5 楼
MCC    8 年前

整个views的方法是怎么写的

MCC
Reply   •   6 楼
MCC    8 年前

感觉像是views里面报出来的,具体找行号吧

似乎是你强制企图把'推荐'转成int

ice916
Reply   •   7 楼
ice916    8 年前

@MCC 還是出現invalid literal for int() with base 10: '推荐' 這個錯誤

MCC
Reply   •   8 楼
MCC    8 年前

结果是啥,怎么报错的

ice916
Reply   •   9 楼
ice916    8 年前

@MCC 我尝试了你的方法,结果还是不行...

最后希望output出来的会是

时间、书名、评价

2015.08.31、Django书、推荐

2015.08.30、百科书、不推荐

MCC
Reply   •   10 楼
MCC    8 年前

<td align="center"> <h4>{{ r.info.info }}</h4></td>

ice916
Reply   •   11 楼
ice916    8 年前

@MCC 抱歉网路的句子贴太快,忘记改成自己的需求

MCC
Reply   •   12 楼
MCC    8 年前

host又是什么

MCC
Reply   •   13 楼
MCC    8 年前

Heartbleed是什么