【问题标题】:Django : matching query does not existDjango:匹配的查询不存在
【发布时间】:2021-02-15 06:12:41
【问题描述】:

在 DJango 中创建 ModelForm 实例时出错。 我并不总是面临这个问题,但有时它工作正常,有时它给我错误。

模型代码:

class ClientinfoForm(ModelForm):
    Account_Name = forms.CharField(disabled=True)
    class Meta:
        model = AccountDescription
        fields = ['Account_Name','short_Name','group_Master_Project_Code','account_Logo','vertical','client_Website','client_Revenue','Employee_Count','client_Industry_Segment','delivery_Manager_Mail','project_Manager_Mail']
        labels = {'client_Revenue':'Client Revenue(in USD Billion)','vertical':'Industry Vertical'}
        help_texts = {'client_revenue' : '(In Billion USD)' }   

views.py 代码

def save_client_info(request):
    fm = ClientinfoForm(request.POST, instance = AccountDescription.objects.get(Account_Name = acc_name),files = request.FILES or None)
    save_form(request,fm)


def clientinfo(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            print("inside form")
            save_client_info(request)
        global s4_option
        s4_option = AccountDescription.objects.filter(Account_Name = acc_name).values('s4_data')
        s4_option = s4_option[0]['s4_data']
        accdata = AccountDescription.objects.filter(Account_Name = acc_name)
        clientdata = ClientinfoForm(instance = AccountDescription.objects.get(Account_Name = acc_name))
        return render(request, 'AccountData/ClientInfo.html',{'name' : 'clientinfo','form':clientdata,'acntdata':accdata,'content':editoption})

有时,当我保存它时,它工作得很好,但有时它给出的匹配查询不存在。

如果需要更多信息,请告诉我。

【问题讨论】:

    标签: django django-forms modelform


    【解决方案1】:

    换行

    instance = AccountDescription.objects.get(Account_Name = acc_name)
    

    save_client_info 函数中类似于

    from django.shortcuts import get_object_or_404
    
    instance = get_object_or_404(AccountDescription, Account_Name=acc_name)
    

    注意:我假设您已经在代码中的此行之前正确定义了acc_name

    因为总会有一些情况下这条记录不存在,而 Django 会引发does not exist 错误类型。或者,如果您的数据库中不存在此查询,您也可以返回所需的响应,例如:

    from django.http import HttpResponse
    
    try:
        fm = ClientinfoForm(request.POST, instance = AccountDescription.objects.get(Account_Name = acc_name),files = request.FILES or None)
    except AccountDescription.DoesNotExist:
        return HttpResponse("Requested account does not exist") # or any other responses
    

    【讨论】:

    • 但记录(帐户)始终存在于数据库中。对于同一条记录,如果我更新记录,则显示查询不存在。但是当我重新加载它工作正常。例如。假设我为帐户 X 进行了编辑,如果我编辑表单并在大多数情况下保存表单,它运行正常,但对于同一个帐户,有时它会给出“查询不存在错误”。
    猜你喜欢
    • 2015-01-28
    • 2020-10-15
    • 1970-01-01
    • 2022-01-05
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多