如何从基于类的通用表单视图将数据传递到模板

时间:2018-12-10 09:07:19

标签: django

views.py

 class CompanyUpdateView(UpdateView):
        model = Company
        fields = ['company_name', 'company_description','company_email',
        'company_phone', 'company_address', 'company_website'
        , 'company_status', 'company_monthly_payment']

company_form.html

{% extends "super_admin/base.html" %}
    {% load crispy_forms_tags %}
    {% block content %}
        <div class="content-section">

            {{ object.update }}
            <form action="" method="POST">
                {% csrf_token %}
                <fieldset class="from-group">
                    <legend class="border-bottom mb-4">Enter New Company</legend>
                    {{ form | crispy}}
                </fieldset>
                <div class="form-group">
                    <button class="btn btn-outline-info" type="submit">Submit</button>
                </div>
            </form>

        </div>
    {% endblock content %}

我在company_form.html中获取表单值 但是我想要静态值,该值将存储在CompanyUpdateView中,并将显示在company_form.html模板中。

之所以这样做,是因为我使用相同的模板进行更新删除并创建公司,当我单击编辑按钮时,它将显示删除按钮而不是保存按钮

{% extends "super_admin/base.html" %}
{% block content %}
<a class="btn btn-primary" href="{% url 'super-company-create' %}" role="button">Add a Company</a>
    <table class="table">
        <thead class="thead-dark">
            <tr>
            <th scope="col">#</th>
            <th scope="col">Company Name</th>
            <th scope="col">Company Email</th>
            <th scope="col">Company Website</th>
            <th scope="col">Company Status</th>
            <th scope="col">Company Monthly Payment</th>
            <th scope="col">Edit</th>
            </tr>
        </thead>
        <tbody>
    {% for company in companies %}
        <tr>
            <th scope="row">{{ company.id }}</th>
            <td>{{ company.company_name }}</td>
            <td>{{ company.company_email }}</td>
            <td>{{ company.company_website }}</td>
            <td>{{ company.company_status }}</td>
            <td>{{ company.company_monthly_payment }}</td>
            <td><a href="{{ company.id }}/update?update=update" name="editButton123">Edit</a></td>
        </tr>
    {% endfor %}
        </tbody>
    </table>

{% endblock content %}

1 个答案:

答案 0 :(得分:0)

如果要向模板传递一些额外的上下文,则需要使用如下所示的get_context_data函数。

class YourGenericView(SomeView):
    def get_context_data(self, *args, **kwargs):
        # calling super is required to get all the context this generic view is going to inject like form data etc.
        context = super(YourGenericView, self).get_context_data(*args, **kwargs)
        context.update(your_data_dict)
        return context