【发布时间】:2021-11-18 12:41:54
【问题描述】:
代码说明
在以下代码中,我创建了一个用户仪表板,该仪表板在用户创建帐户后显示。无论用户是否已上传,在仪表板上也会显示用户图像。
如果用户尚未上传图片,则会显示默认图片,如下代码所示。
但是如果用户没有上传图片,它会显示错误,如果用户上传了图片,它会正常工作。
代码
dashboard.html
{% if values.user_image.url %}
<a class="image" href="{% url 'setting' %}"><img src="{{ values.user_image.url }}" alt=""></a>
{% else %}
<a class="image" href="{% url 'setting' %}"><img src="{% static 'img/user.png' %}" alt=""></a>
{% endif %}
views.py
@login_required(login_url = "login")
def user_home(request):
if request.method == "GET":
record = User.objects.get(email=request.user)
wallet = Wallet.objects.get(user_id=request.user)
walletbalance = wallet.wallet_balance
context = {
'walletbalance': walletbalance,
'values': record,
}
return render(request, "userdashboard/index.html", context)
错误
ValueError at /user/setting
The 'user_image' attribute has no file associated with it.
Request Method: GET
Request URL: http://127.0.0.1:8000/user/setting
Django Version: 3.2.6
Exception Type: ValueError
Exception Value:
The 'user_image' attribute has no file associated with it.
Exception Location: C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file
Python Executable: C:\Users\Qasim Iftikhar\anaconda3\python.exe
Python Version: 3.8.5
Python Path:
['C:\\xampp\\htdocs\\Projects\\Barter',
'C:\\Users\\Qasim Iftikhar\\anaconda3\\python38.zip',
'C:\\Users\\Qasim Iftikhar\\anaconda3\\DLLs',
'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib',
'C:\\Users\\Qasim Iftikhar\\anaconda3',
'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages',
'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32',
'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32\\lib',
'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\Pythonwin']
Server time: Sat, 25 Sep 2021 14:38:10 +0000
【问题讨论】:
-
您可以尝试给 user_image 一个默认文件。喜欢这里:stackoverflow.com/a/1276907/11607969
标签: python python-3.x django django-templates