在Django DetailView中获取表单

时间:2016-06-22 16:35:54

标签: python django forms django-generic-views detailview

我目前正在尝试显示自定义表单,我在相应视图中更改表单

.html中的

<form action="{% url 'systems_system_update' system.id %}" id="system_update_form" method="post" class="form">
        {% csrf_token %}
        {% buttons %}
          <button type="submit" class="btn btn-primary">Update {{ system.name }}</button>
        {% endbuttons %}
        {% bootstrap_form system_update_form %}
        {% buttons %}
          <button type="submit" class="btn btn-primary">Update {{ system.name }}</button>
        {% endbuttons %}
      </form>

所以我试图在视图中定义system_update_form 在SystemDetailView

class SystemDetailView(DetailView):
"""Detail view for Systems"""

form_class = SystemForm
model = System
template_name = 'systems/system_detail.html'

def get_form(self, form_class):
    form = super(SystemDetailView, self).get_form(form_class)
    form.fields['primary_purpose_business_use'].label = "Primary purpose/business use"
    form.fields['secondary_purpose_business_uses'].label = "Secondary purpose/business uses"

    return form

def get_context_data(self, **kwargs):
    context = super(SystemDetailView, self).get_context_data(**kwargs)
    context.update({
        'system_update_form': self.form_class(instance=self.get_object()),
        'object_name': self.object.name,
        'user_can_edit': self.request.user.has_perm(
            'services.change_system'),
        'user_can_delete': self.request.user.has_perm(
            'services.delete_system'),
        'object_events': self.object.events.all(),
    })

    return context

所以,我正在更新上下文并将'system_update_form'设置为表单,我正在尝试使用get_form更新表单,但我不认为DetailView具有覆盖的get_form方法。 在表单中更新它不是一个选项,因为SystemForm在许多不同的地方使用,需要特别为此视图进行更改

1 个答案:

答案 0 :(得分:4)

DetailView 没有get_form()方法,因为未使用表单,因此未调用get_form()方法。< / strong>

您可以在get_form()方法中手动实例化表单,并在生成context时调用此方法,而不是这样。

此外,在您的代码中,您通过调用instanceself.get_object()传递给表单。这将导致另一个获取object的查询,因为Django之前已经获取了object。您可以使用object直接传递self.object

,而不是这样做
class SystemDetailView(DetailView):

    def get_form(self):
        form = self.form_class(instance=self.object) # instantiate the form

        # modify the form fields
        form.fields['primary_purpose_business_use'].label = "Primary purpose/business use"
        form.fields['secondary_purpose_business_uses'].label = "Secondary purpose/business uses"

        return form

    def get_context_data(self, **kwargs):
        context = super(SystemDetailView, self).get_context_data(**kwargs)
        context.update({
            'system_update_form': self.get_form(), # get the form instance
            'object_name': self.object.name,
            'user_can_edit': self.request.user.has_perm(
                'services.change_system'),
            'user_can_delete': self.request.user.has_perm(
                'services.delete_system'),
            'object_events': self.object.events.all(),
        })

        return context