[ACCEPTED]-How to subclass django's generic CreateView with initial data?-django-class-based-views

Accepted answer
Score: 30

get_initial() should just return a dictionary, not be 2 bothered with setting self.initial.

Your method should 1 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
Score: 1

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

Score: 0

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

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

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

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

More Related questions