模型 Django 不可迭代
Posted
技术标签:
【中文标题】模型 Django 不可迭代【英文标题】:Models Django not iterable 【发布时间】:2021-12-09 06:48:04 【问题描述】:我对 Django 模型有一些问题,我想迭代从基于模型的表单的文本字段中获取的数据。但我不能它仍然是一个错误:
TypeError at /kod/start/
'Passwords' object is not iterable
Request Method: POST
Request URL: http://127.0.0.1:8000/kod/start/
Django Version: 3.2.8
Exception Type: TypeError
Exception Value:
'Passwords' object is not iterable
Exception Location: /home/natalia/PycharmProjects/django_project/kodszyfru/views.py, line 52, in start
Python Executable: /home/natalia/PycharmProjects/django_project/venv/bin/python3
Python Version: 3.8.10
Python Path:
['/home/natalia/PycharmProjects/django_project',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/natalia/PycharmProjects/django_project/venv/lib/python3.8/site-packages']
Server time: Fri, 22 Oct 2021 16:03:53 +0000
代码模型.py
from django.db import models
# Create your models here.
class Passwords(models.Model):
text = models.TextField(max_length=2000,null=True)
cipher = models.CharField(max_length=64)
def __str__(self):
return self.text
views.py
def start(request):
password_form = PasswordsForm(request.POST or None)
if password_form.is_valid():
text = password_form.save()
try:
for i in text:
value = (alphabet[i])
klucz = 10
new_value = int(value) + klucz
if new_value > 70:
new_value = new_value - 70
for key, value in alphabet.items():
if value == str(new_value):
print(key, end='')
return ''
except KeyError:
return ('Nie znaleziono wartości' + i + ' w słowniku!')
return render(request, 'kod.html', 'kod': kod)
return render(request, 'start.html', 'password_form': password_form)
我将不胜感激!
娜塔莉亚
【问题讨论】:
【参考方案1】:text
是 Password
对象,而不是字符串。您应该遍历密码:
password_form = PasswordsForm(request.POST or None)
if password_form.is_valid():
password = password_form.save()
try:
for i in password.text:
# …
except KeyError:
# …
【讨论】:
谢谢你,Willem,你能不能再看看另一个问题?以下?提前谢谢你:) @NataliaOsysko:请提出一个新问题。通常解决一个问题每个问题。以上是关于模型 Django 不可迭代的主要内容,如果未能解决你的问题,请参考以下文章
TypeError:'BasePermissionMetaclass' 对象在 django rest 框架中不可迭代
Django - TypeError - NoneType' 对象不可迭代 - 不明白为啥 Object 被识别为 None
Django REST 框架:“BasePermissionMetaclass”对象不可迭代