我在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})
有时,当我保存它时,它工作得很好,但有时它给出匹配查询不存在。
如果需要更多信息请告诉我。
修改行
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