在DJango中创建ModelForm实例时出现错误。我并不总是面对这个问题,但有时它工作得很好,有时它会给我带来错误。
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})有时,当我保存它时,它工作得很好,但有时它给出的匹配查询并不存在。
如果需要更多信息,请让我知道。
发布于 2021-02-15 14:23:53
更改线路
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 responseshttps://stackoverflow.com/questions/66203462
复制相似问题