How to subclass django's generic CreateView with initial data?

a 夏天 提交于 2019-11-28 17:35:47

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!