'Django: Instantiating a form in a custom class based view

This is my first post, and I am new to Django so go easy on me!

I am trying to convert my function based views into class based views so I can reuse the views easily in other apps, and am struggling with instantiating a form inside the class.

I have the following function based view:

def object_create(request):

    def get_date():
        today = datetime.datetime.now()
        enquiry_date = today.strftime("%d/%m/%Y")
        return enquiry_date

    initial_dict = {
            "account_handler" : request.user,
            "prep_location" : request.user.profile.location,
            "load_location":   request.user.profile.location,
            "return_location": request.user.profile.location,
            "status":"Enquiry",
            "enquiry_date": get_date()
        }
    
    object_form = QuoteForm(request.POST or None, initial = initial_dict)

    context = {
            'form': object_form,
        }

    if request.method == 'GET':

        return render(request, "rental_quotes/form.html", context )

        # If we are saving the form
    if request.method == 'POST':
        
        if object_form.is_valid():
            new_object = object_form.save()
            context = {
                'object': new_object
            }
            found_count = Quote.objects.all().count()
            request.session['rental_quotes_current_index'] = (found_count-1)
            request.session['rental_quotes_found_count'] = found_count
            new_page = json.dumps({
            'url': reverse("rental_quotes-detail", args=[new_object.id]),
            'index': found_count-1,
            'found_count': found_count,
            'content': render_to_string('rental_quotes/pages/detail.html', context)
            })
        
            return JsonResponse(new_page, safe=False, status=200)

        else:
            return render(request, 'rental_quotes/form_block.html', context )

Which works fine.

In my attempt at creating a class I can import into a class based view I have:

class ObjectCreate(LoginRequiredMixin, View):
        
    def get_date():
        today = datetime.datetime.now()
        enquiry_date = today.strftime("%d/%m/%Y")
        return enquiry_date

    def get (self, request):

        object_form = self.request.form(request.POST or None, initial = self.initial_dict)

        context = {
            'form': object_form,
        }
        
        return render(request, f'{self.app_name}/form.html', context )

    def post (self, request):
        
        object_form = self.form(request.POST or None, initial = self.initial_dict)

        if self.object_form.is_valid():
            new_object = object_form.save()
            context = {
                'object': new_object
            }
            found_count = self.model.objects.all().count()
            request.session[f'{self.app_name}_current_index'] = (found_count-1)
            request.session[f'{self.app_name}_found_count'] = found_count
            new_page = json.dumps({
            'url': reverse(f'{self.app_name}-detail', args=[new_object.id]),
            'index': found_count-1,
            'found_count': found_count,
            'content': render_to_string(f'{self.app_name}/pages/detail.html', context)
            })
        
            return JsonResponse(new_page, safe=False, status=200)

        else:
            return render(request, f'{self.app_name}/form_block.html', context )

And in my views.py I have (which inherits from the class above):

class ObjectCreateView(ObjectCreate):

    app_name = 'rental_quotes'
    form = QuoteForm
    

The problem is, when I load that view, I get the following error:

Internal Server Error: /rental_quotes/create/
Traceback (most recent call last):
  File "/Users/simon/Desktop/JEDI/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/simon/Desktop/JEDI/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/simon/Desktop/JEDI/lib/python3.10/site-packages/django/views/generic/base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/simon/Desktop/JEDI/lib/python3.10/site-packages/django/contrib/auth/mixins.py", line 71, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "/Users/simon/Desktop/JEDI/lib/python3.10/site-packages/django/views/generic/base.py", line 101, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/simon/Desktop/JEDI/JEDI/framework/views.py", line 109, in get
    object_form = self.form(request.POST or None)
AttributeError: 'ObjectCreate' object has no attribute 'form'

My goal here is to have classes which define custom views that I just need to set attributes such as models and forms, so I can easily re-use the views in other apps by just changing attributes such as model and form.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source