如何使用初始数据子类化 django 的通用 CreateView? [英] How to subclass django's generic CreateView with initial data?
问题描述
我正在尝试创建一个对话框,该对话框使用 jquery 的 .load() 函数以呈现的 django 形式发出声音..load 函数传递了警报"对象的 pk.类函数中还可以使用诸如 self.request.user
之类的东西,因此我可以预先填充这些字段,如下面的消息模型 (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()
应该只返回一个字典,而不是设置 self.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屋!