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

发布于 2024-11-01 00:18:45 字数 1514 浏览 1 评论 0原文

我正在尝试创建一个对话框,它使用 jquery 的 .load() 函数来读取渲染的 django 表单。 .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()

子类化 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)

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

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()

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)

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜光 2024-11-08 00:18:45

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

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
ぶ宁プ宁ぶ 2024-11-08 00:18:45

你可以这样使用:

from django.shortcuts import HttpResponseRedirect

    class PostCreateView(CreateView):
        model = Post
        fields = ('title', 'slug', 'content', 'category', 'image')
        template_name = "create.html"
        success_url = '/'

        def form_valid(self, form):
            self.object = form.save(commit=False)
            self.object.user = self.request.user
            self.object.save()
            return HttpResponseRedirect(self.get_success_url())

这对我有用

you can use like :

from django.shortcuts import HttpResponseRedirect

    class PostCreateView(CreateView):
        model = Post
        fields = ('title', 'slug', 'content', 'category', 'image')
        template_name = "create.html"
        success_url = '/'

        def form_valid(self, form):
            self.object = form.save(commit=False)
            self.object.user = self.request.user
            self.object.save()
            return HttpResponseRedirect(self.get_success_url())

that's work for me

乜一 2024-11-08 00:18:45

(编辑是因为你正在尝试的确实有效)

我昨天遇到了同样的问题,但它现在正在工作 - 我认为我在 get_initial 中返回了一个对象而不是一个字典代码>.

在解决您的问题方面,我有点怀疑您在 post() 中做了多少工作 - 您可以尝试使用默认(非覆盖)的 post( )

您还可以使用pdb(或 print 语句)来检查 self.get_form_kwargs 的值,确保设置了initial

(Edited because what you're trying does actually work)

I ran into the same problem yesterday, but it's working now – I think I was returning an object instead of a dict in get_initial.

In terms of fixing your problem, I'm a little suspicious of how much you seem to be doing in post() – could you try it with the default (non-overrided) post()?

You could also use pdb (or print statements) to check the value of self.get_form_kwargs make sure that initial is being set.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文