python - Django 3:无法生成动态对象视图
问题描述
我已经成功地为我的模型创建了预期的结构,并且在错误变量中我可以看到 DB 对象已返回,但我无法解析页面。我收到错误“TypeError at /ticket-edit/2 - init () got an unexpected keyword argument 'instance'” - 我是否错误地引用了该对象?我想使用现有的 TicketForm,但使用 URL 中的字段值填充结果。
在错误中,本地变量显示已检索到预期的票证:
Variable: Value
- aTicketID: '2'
- 语境: {}
- obj: <Ticket: 2 2021-10-06 Ticket Title Ticket Desc> 请求
- <WSGIRequest: GET '/ticket-edit/2'>
- 异常位置:/views.py,第 118 行,在 ticket_edit 中
- 第 118 行是:updateform=TicketForm(instance=obj)
Urls.py(我使用URL而不是路径来生成ID链接)
urlpatterns = [
url(r'^ticket-edit/(?P<aTicketID>\d+)', views.ticket_edit, name='ticket-edit')
]
模型.py
class Ticket(models.Model):
#---Base Meta-----------------------------------------
appTicketID = models.AutoField(primary_key=True)
date_submitted = models.DateTimeField(
max_length=20,
auto_now_add=True)
issue_title = models.CharField(max_length=90)
issue_description = models.CharField(max_length=1000)
def __str__(self):
return (f"{self.appTicketID} "
f"{self.date_submitted} "
f"{self.issue_title} "
f"{self.issue_description} "
def get_absolute_url(self):
return reverse_lazy('ticket-edit', kwargs={'aTicketID': self.appTicketID}
视图.py
@login_required
def ticket_edit(request, aTicketID):
context = {}
obj=Ticket.objects.get(appTicketID=aTicketID)
updateform=TicketForm(instance=obj)
if aTicketID == None:
aTicketID = 1
aticket = Ticket.objects.filter(appTicketID=aTicketID)
print('\n-----------------------------------------------------------------')
print('TicketFiltered: ', aticket)
print('-----------------------------------------------------------------\n')
context = {
"has_error": False,
"updateform": updateform,
"aticket": aticket
}
return render(request,'appname/ticket-edit.html', context)
试过这个但导致错误:'Ticket' object has no attribute 'get'
obj = Ticket.objects.get(appTicketID=aTicketID)
updateform = TicketForm(obj)
解决方案
推荐阅读
- pandas - Value_counts 不按区间除
- javascript - 使用 JavaScript 在数组外添加值
- java - PermCheck Codility Scala 解决方案
- php - method="get" 和 $_GET 有什么区别?
- php - WordPress wp_mail 错误地复制电子邮件,如何防止此错误?
- c++ - 在动态数组(向量)上使用 Mutex
- html - 导航栏切换按钮居中
- firebase - 为什么我重定向到登录页面后登录页面上的身份验证状态不会持久?
- angular - 如何在所有应用程序中共享数据价值
- spring - 给定 IntelliJ 中的数据库连接,如何生成 Spring REST 服务?