如何使用初始数据子类化django的通用CreateView?

Mat*_*att 19 django-forms django-views django-class-based-views

我正在尝试创建一个对话框,该对话框使用jquery的.load()函数以渲染的django形式进行slurp..load函数传递给"alert"对象的pk.在类函数中也可以使用self.request.user这样的东西,所以我可以预先填充这些字段,如下面的消息模型(models.py)中所示:

class Message(models.Model):

    user = models.ForeignKey(User)
    alert = models.ForeignKey(Alert)
    date = models.DateTimeField()
    message = models.TextField()
Run Code Online (Sandbox Code Playgroud)

子类化django的CreateView使得使用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)
Run Code Online (Sandbox Code Playgroud)

这里的问题是self.initial没有使用表单呈现.我已经确保表单确实在调用get_initial,并且表单实例具有正确的初始数据post,但是当表单在模板中呈现时,message.html它不会像我期望的那样获取任何初始数据.是否有一个特殊的技巧让这个工作?我已经搜索了文档(似乎缺乏基于泛型的类视图的示例)和源代码,但我无法看到我所缺少的内容.

Smi*_*ris 25

get_initial()应该只返回一本字典,不要被设置困扰self.initial.

你的方法应该是这样的:

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
Run Code Online (Sandbox Code Playgroud)

  • 请原谅我的无知,但是不抄字典有什么风险呢? (2认同)
  • 谢谢哲,但我不明白为什么副本在这种特殊情况下很重要 - 如果对象仍在其他地方使用,那么这只会很重要吗? (2认同)