0

我为我的所有模型添加了一个“用户”字段。当用户创建对象时,我想通过外键附加他们的 ID

user = models.ForeignKey(User)

以前,我使用的是 create_object 和 update_object。我相信我需要切换到基于类的通用视图,以便最轻松地将所需的用户插入到记录中。但是我对如何在调用 create_object 或 update_object 之前在之前的函数中进行一些预先计算感到困惑。

我有一个处理所有对象编辑的函数,无论是创建还是更新:

@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

在基于类的通用视图中,我如何/在何处/何时执行其中一些计算(围绕定义模板或基于标准的 form_class 的逻辑)?我很困惑,因为文档似乎直接进入定义:

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

我可以把逻辑扔在那里吗?

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/'

以及我将/应该如何改变我的逻辑以转移到使用 CreateView 或 UpdateView 与我在这里在同一函数中使用 create_object 或 update_object 所做的,这取决于是否定义了 slug/id?

4

1 回答 1

1

基于类的通用视图具有用于您需要的任务的方法。例如,对于创建您使用的对象的表单CreateView,以及定义使用哪个表单的覆盖get_form_class()方法。

我强烈建议您不要尝试完全转换您当前的逻辑,而是花一些时间来了解基于类的视图的细节,因为那里已经详细解决了许多常见功能。

于 2012-11-03T08:15:03.077 回答