Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use context with class in CreateView in django?

How to use context with class in CreateView in django?

Before i have:

#views.py
from django.views.generic import CreateView
from cars.models import *

def CreateCar(CreateView):
    info_sended = False
    if request.method == 'POST':
        form = FormCar(request.POST, request.FILES)
        if form.is_valid():
            info_sended = True
            form.save()
    else:
        form = FormCar()
    ctx = {'form': form, 'info_sended':info_sended}
    return render_to_response("create_car.html", ctx,
        context_instance=RequestContext(request))

Now, a have, and try:

class CreateCar(CreateView):
    info_sended = False
    template_name = 'create_car.html'
    model = Car
    success_url = 'create_car' #urls name

    def form_valid(self, form):
        info_sended = True
        ctx = {'form': form, 'info_sended':info_sended}
        return super(CreateCar, self).form_valid(form)

My html page is:

<!-- create_car.html -->
{% extends 'base.html' %}

{% block content %}

{% if info_sended %}
    <p>Data saved successfully</p>
    <p><a href="{% url 'list_cars' %}">Show List</a></p>
{% else %}
    <form class="form-horizontal" action="" method="post">
        {% csrf_token %}
        {% include "form.html" %}
        <div class="col-md-offset-1">
            <button class="btn btn-primary" type="submit">Add</button>
        </div>
    </form>
{% endif %}

{% endblock %}
like image 764
Regis Santos Avatar asked Dec 16 '22 02:12

Regis Santos


1 Answers

You should define get_context_data() method in your class view. Update your code as

from django.shortcuts import render

class CreateCar(CreateView):
    info_sended = False
    template_name = 'create_car.html'
    model = Car
    success_url = 'create_car' #urls name

    def form_valid(self, form):
        self.info_sended = True
        # Instead of return this HttpResponseRedirect, return an 
        #  new rendered page
        super(CreateCar, self).form_valid(form)
        return render(self.request, self.template_name,
                      self.get_context_data(form=form))


    def get_context_data(self, **kwargs):
        ctx = super(CreateCar, self).get_context_data(**kwargs)
        ctx['info_sended'] = self.info_sended
        return ctx
like image 158
Rohan Avatar answered Jan 31 '23 12:01

Rohan