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

后端 未结 3 1742
故里飘歌
故里飘歌 2020-12-13 05:11

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 av

相关标签:
3条回答
  • 2020-12-13 05:26

    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
    
    0 讨论(0)
  • 2020-12-13 05:36

    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

    0 讨论(0)
  • 2020-12-13 05:39

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

    0 讨论(0)
提交回复
热议问题