Django: Инстанцирование формы в представлении на основе пользовательского класса

Это мое первое сообщение, и я новичок в Django, так что будьте проще со мной!

Я пытаюсь преобразовать мои представления на основе функций в представления на основе классов, чтобы я мог легко использовать эти представления в других приложениях, и у меня возникают трудности с инстанцированием формы внутри класса.

У меня есть следующее представление на основе функций:

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 )

Который работает нормально.

В моей попытке создать класс, который я могу импортировать в представление, основанное на классах, у меня есть:

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 )

А в моем views.py у меня есть (который наследуется от класса выше):

class ObjectCreateView(ObjectCreate):

    app_name = 'rental_quotes'
    form = QuoteForm
    

Проблема в том, что когда я загружаю это представление, я получаю следующую ошибку:

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'

Любая помощь будет очень признательна!!!

Моя цель состоит в том, чтобы иметь классы, определяющие пользовательские представления, для которых мне нужно только установить атрибуты, такие как модели и формы, чтобы я мог легко повторно использовать представления в других приложениях, просто изменяя атрибуты, такие как модель и форма.

Вернуться на верх