首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >DJANGO 2.0.5 'User' object has no attribute 'META'

DJANGO 2.0.5 'User' object has no attribute 'META'
EN

Stack Overflow用户
提问于 2018-06-11 05:05:23
回答 2查看 0关注 0票数 0

我试图在我的HTML视图中显示Django(2.0.5)的我的SQL聚合查询的结果,但我得到了这个错误信息:

'User' object has no attribute 'META'

但是,我可以在终端中看到我的查询结果,因为我将它打印在我的view.py。所以与sqlite的连接正在工作。

在我看来,我写过这样的东西:

class MyClass(UserPassesTestMixin, DetailView):
def test_func(self, request):
    cursor = connection.cursor()
    cursor.execute('''select 
    a, count(b), c, d
    from table1 inner join table2 ON table2.id = table1.b_id
    where c < 2
    group by a, d
    order by d ''')

    results = cursor.fetchone()
    print(results)

    context = {"results":results}
    return render(request, "path/file.html", context)

在我的urls.py文件中,我有这样的东西:

path('/path/', MyClass.as_view(), name = 'my-class'),

并且在我的模板“file.html”中,当我点击一个按钮时,我试图访问我的结果:

<a href="{% url 'path:my-class' object.id %}" class="btn btn-primary" role="button">{% trans 'Show results' %}</a>
EN

回答 2

Stack Overflow用户

发布于 2018-06-11 13:36:44

class MyClass(UserPassesTestMixin, DetailView):
    def test_func(self, request):
        cursor = connection.cursor()
        data = cursor.execute('''select 
        a, count(b), c, d
        from table1 inner join table2 ON table2.id = table1.b_id
        where c < 2
        group by a, d
        order by d ''')

        results, = data.fetchone() # it returns a tuple and not a string as you might expect. since you have selected multiple columns
        data = [row[0] for row in results.fetchall()]

        translation_table = dict.fromkeys(map(ord, '+-(),'), None)
        results = results.translate(translation_table)

        print(results)

        context = {"results":results}
        cursor.close()
        return render(request, "path/file.html", context)
票数 0
EN

Stack Overflow用户

发布于 2018-06-11 14:43:19

使用基于函数的视图而不是基于类的视图。

def my_view(request):
    cursor = connection.cursor()
    cursor.execute('''...''') 
    results = cursor.fetchone()
    print(results)

    context = {"results":results}
    return render(request, "path/file.html", context)

并更改你的URL模式以使用

path('/path/', my_view, name = 'my-view'),
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档