如何使用初始数据子类化django的通用CreateView? [英] How to subclass django's generic CreateView with initial data?

查看:338
本文介绍了如何使用初始数据子类化django的通用CreateView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个使用jquery的.load()函数在渲染的django表单中显示的对话框。 .load函数传递alert对象的pk。在类函数中也可以使用 self.request.user ,所以我可以预先填充这些字段,如下面的Message模型(models.py)所示:

I'm trying to create a dialog which uses jquery's .load() function to slurp in a rendered django form. The .load function is passed the pk of the "alert" object. Also available in the class functions are things like self.request.user so I can pre-fill those fields, shown below in the Message model (models.py):

class Message(models.Model):

    user = models.ForeignKey(User)
    alert = models.ForeignKey(Alert)
    date = models.DateTimeField()
    message = models.TextField()

子类化django的CreateView可以很容易地使用ModelForm(views.py)的实例生成上下文:

Subclassing django's CreateView makes it pretty easy to generate a context with an instance of the ModelForm (views.py):

class MessageDialogView(CreateView):
    """ show html form fragment """
    model = Message
    template_name = "message.html"

    def get_initial(self):
        super(MessageDialogView, self).get_initial()
        alert = Alert.objects.get(pk=self.request.POST.get("alert_id"))
        user = self.request.user
        self.initial = {"alert":alert.id, "user":user.id, "message":"test"}
        return self.initial


    def post(self, request, *args, **kwargs):
        super(MessageDialogView, self).post(request, *args, **kwargs)
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        context = self.get_context_data(form=form)
        return self.render_to_response(context)

这里的问题是 self.initial 不会被渲染表格。我保证表单确实调用 get_initial ,表单实例在 post 中具有正确的初始数据,但是该表单在模板 message.html 中呈现,它不会像我所期望的那样抓住任何初始数据。有没有一个特别的技巧让这个工作?我已经浏览了文档(似乎缺少通用的类视图的例子)和源代码,但我看不到我缺少的东西。

The problem here is that self.initial does not get rendered with the form. I have insured that the form is indeed calling get_initial and the form instance has the proper initial data in post, but when the form is rendered in the template message.html it doesn't grab any of the initial data like I would expect. Is there a special trick to get this to work? I've scoured the docs (seems to be lacking examples on generic based class views) and source but I can't see what I'm missing.

推荐答案

get_initial

get_initial() should just return a dictionary, not be bothered with setting self.initial.

您的方法应该如下所示:

Your method should look something like this:

def get_initial(self):
    # Get the initial dictionary from the superclass method
    initial = super(YourView, self).get_initial()
    # Copy the dictionary so we don't accidentally change a mutable dict
    initial = initial.copy()
    initial['user'] = self.request.user.pk
       # etc...
    return initial

这篇关于如何使用初始数据子类化django的通用CreateView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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