Home > Enterprise >  Converting Form Function to a Class Based View in a Django Project
Converting Form Function to a Class Based View in a Django Project

Time:10-25

I am trying to convert my Form which is laid out in a function to be in a class based view:

Here is what I have reach out.

Function:

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
        }
    )

here is form

class infoForm(forms.ModelForm):

    class Meta:
        model = Info
        fields = [
            'businessName',
            ]

        widgets = {
            'problem_summary': RichTextFormField(),
        }

CodePudding user response:

You may try the following:

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})
  • Related