首页 > 解决方案 > Django 3:无法生成动态对象视图

问题描述

我已经成功地为我的模型创建了预期的结构,并且在错误变量中我可以看到 DB 对象已返回,但我无法解析页面。我收到错误“TypeError at /ticket-edit/2 - init () got an unexpected keyword argument 'instance'” - 我是否错误地引用了该对象?我想使用现有的 TicketForm,但使用 URL 中的字段值填充结果。

在错误中,本地变量显示已检索到预期的票证:

Variable: Value 

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)

标签: pythondjango

解决方案


推荐阅读