在 Django 项目中将表单函数转换为基于 Class 的视图
Converting Form Function to a Class Based View in a Django Project
我正在尝试将函数中的表单转换为基于 class 的视图:
以下是我的资料。
函数:
def add_business_plan(request):
info = Info.objects.all()
if request.method == 'POST':
form = infoForm(request.POST)
if form.is_valid():
form.save()
business_name = form.cleaned_data.get('businessName')
info_id = form.instance.id
messages.success(request, f'PDF created for {business_name}!, No.({info_id})')
return render(request, 'businessplan/businessplan.html', {'form': form, 'successful_submit': True})
else:
form = infoForm()
print(form.errors)
return render(request, 'businessplan/businessplan.html',
{
'form': form,
'successful_submit': False,
"Info": info
}
)
这是表格
class infoForm(forms.ModelForm):
class Meta:
model = Info
fields = [
'businessName',
]
widgets = {
'problem_summary': RichTextFormField(),
}
您可以尝试以下方法:
class AddBusinessPlan(View):
template_name = 'businessplan/businessplan.html'
form_class = infoForm
def get(self, request, *args, **kwargs):
form = self.form_class
print(form.errors)
return render(request, template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
business_name = form.cleaned_data.get('businessName')
info_id = form.instance.id
messages.success(request, f'PDF created for {business_name}!, No.({info_id})')
return render(request, self.template_name, {'form': form, 'successful_submit': True})
else:
return render(request, self.template_name, {'form': form})
我正在尝试将函数中的表单转换为基于 class 的视图:
以下是我的资料。
函数:
def add_business_plan(request):
info = Info.objects.all()
if request.method == 'POST':
form = infoForm(request.POST)
if form.is_valid():
form.save()
business_name = form.cleaned_data.get('businessName')
info_id = form.instance.id
messages.success(request, f'PDF created for {business_name}!, No.({info_id})')
return render(request, 'businessplan/businessplan.html', {'form': form, 'successful_submit': True})
else:
form = infoForm()
print(form.errors)
return render(request, 'businessplan/businessplan.html',
{
'form': form,
'successful_submit': False,
"Info": info
}
)
这是表格
class infoForm(forms.ModelForm):
class Meta:
model = Info
fields = [
'businessName',
]
widgets = {
'problem_summary': RichTextFormField(),
}
您可以尝试以下方法:
class AddBusinessPlan(View):
template_name = 'businessplan/businessplan.html'
form_class = infoForm
def get(self, request, *args, **kwargs):
form = self.form_class
print(form.errors)
return render(request, template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
business_name = form.cleaned_data.get('businessName')
info_id = form.instance.id
messages.success(request, f'PDF created for {business_name}!, No.({info_id})')
return render(request, self.template_name, {'form': form, 'successful_submit': True})
else:
return render(request, self.template_name, {'form': form})