python - 在 Django 中,如何查询登录用户的 MYSQL 数据库?(即特定用户的结果,无需对用户 ID 进行硬编码)
问题描述
到目前为止,我有这个,抱歉我是编程新手 - 试图学习 Django 和 Python。
看法:
def dashboard(request):
return render(request, 'app/dashboard.html', {'my_custom_sql': my_custom_sql})
下面的函数不会在模板中输出任何内容
def my_custom_sql(self):
return self.request.CustomUser.customuser_set.all()
使用硬编码的原始 SQL 替代上述方法:
def my_custom_sql():
current_user = 1
with connection.cursor() as cursor:
cursor.execute("SELECT first_name FROM customuser WHERE id =
%s",[current_user])
row = cursor.fetchone()
上面的作品,但我找不到将用户标识传递给查询而不将其硬编码到用户变量中的方法。
模板:
<h3> Displaying User's First Name </h3>
{% if user.is_authenticated %}
<p>The first name: {{my_custom_sql}}</p>
{% endfor %}
解决方案
和tmc。欢迎来到 SO。
您确实需要关闭if
标签:
模板
{% if user.is_authenticated %}
<p>The first name: {{my_custom_sql.first_name}}</p>
{% endif %}
视图.py
def dashboard(request):
return render(request, 'app/dashboard.html', {'my_custom_sql': my_custom_sql(request)})
def my_custom_sql(request):
return CustomUser.objects.get(pk=request.user.pk)
根据您的型号,您可以:
{% if user.is_authenticated %}
<p>The first name: {{user.first_name}}</p>
{% endif %}
推荐阅读
- c - 如何帮助不同的 C(++) 编译器生成干净的 SIMD 代码?
- android - Android Studio:应用程序在 android 版本 <=7 上崩溃,但在 >=7 上工作
- regex - 正则表达式属性(理论)
- c++ - 为什么我不能在 ncurses 中向 printw 提供字符串参数?
- regex - 提取国名的表达式?
- algorithm - 是否有一种有效的算法来查找所有相交的多边形?
- c++ - 是否投射 shared_ptr
到 shared_ptr 改变它指向的对象? - java - 为什么这个 String HashMap 不能通过 *char* 键获得正确的值
- c# - 使某物同时在 X 轴和 Y 轴上移动
- python - 如何在 django.contrib.auth.forms UserCreationForm 中放置一个复选框