扩展 Django 的通用视图 [英] Extending Django's Generic Views

查看:22
本文介绍了扩展 Django 的通用视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Django 中编写我的第一个应用程序,但我在使用 create_object 通用视图时遇到了问题;在我的 urls.py 中,我有:

I'm writing my first app in Django, and I have a problem with the create_object Generic View; In my urls.py, I have:

(r'^new$', CreateView.as_view()),

问题是,当用户提交新"表单时,我需要对将保存到数据库中的数据进行操作(我实际上需要添加user_id外键);没有我以前写的通用视图:

The problem is that when the user submits the "new" form, I need to manipulate the data that will be saved to the database (I actually need to add the user_id foreign key); without Generic Views I used to write:

    form = ClientForm(request.POST)
    if form.is_valid():
        data = form.save(commit=False)
        data.user = request.user
        data.save()
        form.save_m2m()

在我看来(注意data.user=request.user).我已经搜索了 Django 文档,但我找不到一种方法来做到这一点(也许通过扩展 CreateView 类) - 有些在 The Book 中只有一个例子覆盖了 get_object<ListView 类的/code> 方法来更新 last_accessed_date 字段.

in my view (notice data.user=request.user). I've searched Django docs but I can't find a way to do this (maybe by extending the CreateView class) - somewere in The Book there is only an example that overrides the get_object method of a ListView class to update a last_accessed_date field.

推荐答案

您可以通过覆盖 get_form 方法来实现:

You can do this by overriding the get_form method:

from django.views.generic import CreateView

class CustomCreateView(CreateView):
    def get_form(self, form_class):
        form = super(CustomCreateView, self).get_form(form_class)
        form.instance.user = self.request.user
        return form

编辑:现在我会覆盖 form_valid 根据 Issac Kelly 的回答:

from django.views.generic import CreateView

class CustomCreateView(CreateView):
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(CustomCreateView, self).form_valid(form)

这篇关于扩展 Django 的通用视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆