Ed.
Ed.

Reputation: 4597

Convert django function generic view into class-based generic view

I've added a "user" field to all of my models. When a user creates an object, I want to attach their ID through a foreign key

user = models.ForeignKey(User)

Previously, I was using create_object and update_object. I believe I need to switch to class-based generic views in order to most easily insert the required user into the record. But I'm confused on how I institute some of the pre-calculations that were occuring in my previous function before create_object or update_object were called.

I have one function that handles all object editing, whether creating or updating:

@login_required 
def edit_item(request, modelname, submodelname=None, slug=None, id=None):
    # Get parameter "next" to determine where to send user after object is created or updated

    # Define which template to use

    # Determine whether user is converting an object to another type

    # Determine which form_class to use based on modelname and whether user is converting or not

    # Redirect user if slug and id are not both correct

    # Abort if user hit cancel instead of submit

    # If object exists (slug and id are defined):
        # Update_object with form_class, object_id, template_name, post_save_redirect, and extra_context
    # Else
        # Create_object with form_class, template_name, post_save_redirect, and extra_context

Within a class-based generic view, how/where/when do I perform some of these calculations (logic around defining template or form_class based on criteria)? I'm confused because the docs seem to go straight to the definitions:

class ContactView(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = '/thanks/'

Could I just throw the logic there?

class ContactView(FormView):
    A = 1 + 2
    if A == 3:
        template_name = 'contact.html'
    else:
        template_name = 'contact_two.html'
    form_class = ContactForm
    success_url = '/thanks/'

And how would/should I alter my logic to divert into using CreateView or UpdateView vs what I've done here in using create_object or update_object in the same function depending on whether slug/id are defined?

Upvotes: 0

Views: 776

Answers (1)

Berislav Lopac
Berislav Lopac

Reputation: 17273

Class-based generic views have methods that are used for the tasks you need. For example, for a form that creates an object you use CreateView, and to define which form is used override get_form_class() method.

I strongly suggest you to, instead of trying to convert your current logic exactly, take some time to learn the details of the class-based views, as many common features are already solved there in detail.

Upvotes: 1

Related Questions