theProCoder
theProCoder

Reputation: 435

Form variable for django CreateView

Heads-Up: I don't know if this is a duplicate, but all the questions that StackOverflow said to be similar are not mine.

Hi, I have a django model called Post (I am doing the usual 'blog' website, since I am still learning). I am creating a CreateView for it (django.views.generic) to create more posts.

My problem is that I want to pass in string as a context variable. This can be done with context_object_name or the function get_context_data. But, to create the form that CreateView automatically generates, it passes a context variable called form. Since I am passing my own context data, the CreateView's form context variable gets overwritten.

So, what I am asking is, what is the name of that form variable (if there is) that I can pass into the context data dictionary like {'string': my_string, form: createView_form_variable}.

CreateView:

class CreateBlogView(LoginRequiredMixin, CreateView):
    model = Post
    template_name = 'blogs/create_update_blogs.html'
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def get_context_data(self):
        return {'string': 'Create', 'form': This is the thing I need}

Any help on this would be appreciated - Thanks in advance.

P.S. Please comment if I have not made things clear

Upvotes: 1

Views: 905

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21807

The default implementation of get_context_data will return a dictionary to be passed as a context. The problem with your implementation is that you aren't calling the super method and using it's returned value. super is used to call the same method of the parent class, hence you can write:

class CreateBlogView(LoginRequiredMixin, CreateView):
    model = Post
    template_name = 'blogs/create_update_blogs.html'
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)  # call super
        context['string'] = 'Create'  # add to the returned dictionary
        return context

Upvotes: 2

Related Questions