用formset工厂更新视图不​​起作用

时间:2019-06-20 14:18:32

标签: django python-3.x django-forms django-views

我正在尝试在一个表单集上执行一个updateview,但是它找不到第二个表单中的数据。

在我的模型中。py

class OrdemServicoCoroa(models.Model):
    ordem_servico = models.ForeignKey(
        OrdemServico, related_name='coroas', on_delete=models.CASCADE, blank=True, null=True
    )
    coroa = models.ForeignKey(
        Coroas, related_name='ordens_servico', on_delete=models.CASCADE, blank=True, null=True
    )
    quantidade = models.IntegerField(default=0, blank=True, null=True)
    frase = models.CharField(max_length = 100)
    observacao = models.CharField(max_length=100, blank=True, null=True)
    foto_coroa_valida = models.ImageField(upload_to = "upload/flora",blank=True)
    inicio_flora = models.DateTimeField(blank=True, null=True)
    termino_flora = models.DateTimeField(blank=True, null=True)


    def _str_(self):
        return '{}: {}: {}'.format(self.coroa, self.quantidade, self.frase)

在我的表格中。py

class OrdemServicoForm(forms.ModelForm):
    class Meta:
        model = OrdemServico
        fields = (
        'empresa_origem','atendente','funeraria', 'falecido', 'cpf_falecido', 'abrangencia', 'tipo', 'forma_sep',
        'taxas_apagar', 'quais_taxas', 'remocao', 'codigo', 'forma_pagamento', 'urna', 'biblia', 'cristo', 'sem_adereco',
        'veu', 'preparacao', 'preparacao_opcional', 'ornamentacao', 'obs_ornamentacao', 'previsao_pronto_laboratorio',
         'cafe', 'local_velorio', 'capela',
        'local_sepultamento', 'previsao_velorio', 'data_sepultamento'
    )


class OrdemServicoCoroaForm(forms.ModelForm):
    class Meta:
        model = OrdemServicoCoroa
        fields = ('coroa', 'quantidade', 'frase', 'observacao')


OrdemServicoFormset = forms.formset_factory(
    form=OrdemServicoCoroaForm,
    extra=1,

)

在我的views.py

class OrdemServicoUpdateTeste(UpdateView):
    template_name = 'ordem_servico/ordem_servico_cadastro.html'
    model = OrdemServico
    form_class = OrdemServicoForm


    def get_success_url(self):
        self.success_url = reverse_lazy('ordem_servico:listagem')
        return self.success_url

    def get_context_data(self, **kwargs):
        context = super(OrdemServicoUpdateTeste, self).get_context_data(**kwargs)
        ppk = OrdemServicoCoroa.objects.filter(ordem_servico_id=self.kwargs['pk']).values()
        if self.request.POST:
            context['coroa_set'] = OrdemServicoFormset(self.request.POST, prefix='ordem_servico')
        else:
            context['form'] = OrdemServicoForm(instance=self.object)
            context['coroa_set'] = OrdemServicoFormset(initial=ppk)
        return context

    def post(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        ordem_servico_form = OrdemServicoFormset(self.request.POST)
        if (form.is_valid() and ordem_servico_form.is_valid()):
            return self.form_valid(form, ordem_servico_form)
        else:
            return self.form_invalid(form, ordem_servico_form)

    def form_valid(self, form, ordem_servico_form):
        self.object = form.save()
        ordem_servico_form.instance = self.object
        ordem_servico_form.save()
        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, ordem_servico_form):
        return self.render_to_response(
            self.get_context_data(form=form,
                                  ordem_servico_form=ordem_servico_form))

在我的ordem_servico_cadastro.html

{% extends '../base.html' %}
{% load static %}
{% load widget_tweaks %}

{% block content %}
  <ol class="breadcrumb">
    <li class="breadcrumb-item">
      <a href="{% url 'core:home' %}">Inicio</a>
    </li>
    <li class="breadcrumb-item">
      <a href="{% url 'ordem_servico:listagem' %}">Listagem de Ordem de Serviços</a>
    </li>
    <li class="breadcrumb-item active">{{ page_title }}</li>
  </ol>

  <div class="card mb-3">
  <div class="card-header">
    <i class="fas fa-table"></i>
    Lista Serviços
  </div>
  <div class="card-body">

    <div class="row">
      <div class="col-xs-12">
        <div class="box">
          <div class="box-header">
          </div>
          <!-- /.box-header -->
          <div class="box-body pad">
            <form class="form-horizontal" role="form" method="post" action="." enctype="multipart/form-data">
              {% csrf_token %}
              {% include "../includes/form_errors.html" with form=form %}
              {% for field in form %}
                {% include '../includes/form_field.html' with field=field %}
              {% endfor %}
              {{ coroa_set.management_form }}
              <table class="table">
                {% for form in coroa_set.forms %}
                  {% if forloop.first %}
                    <thead>
                    <tr>
                      {% for field in form.visible_fields %}

                        <th>{{ field.label|capfirst }}</th>
                      {% endfor %}
                    </tr>
                    </thead>
                  {% endif %}
                  <tr>
                  {% for field in form.visible_fields %}

                    <td>
                      {# Include the hidden fields in the form #}
                      {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                          {{ hidden }} 
                        {% endfor %}
                      {% endif %}
                      {{ field.errors.as_ul }}
                      {{ field }} 
                    </td>
                  {% endfor %}
                  </tr>
                {% endfor %}

              </table>
              <a id="add_formset" href="javascript:void(0)" class="btn btn-info"><i class="fa fa-plus" ></i></a>
              <div class="box-footer">
                <hr />
                <a href="{% url 'ordem_servico:listagem' %}" class="btn btn-danger">Cancelar</a>
                <button class="btn btn-primary pull-right" type="submit">Salvar</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>

{% endblock %}
{% block extrascripts %}
  <script type="text/javascript">
    jQuery(document).ready(function () {

      function do_add_formset(newElement, type, where) {
        total_forms_selector = '#id_' + type + '-TOTAL_FORMS';
        let total = Number($(total_forms_selector).val());

        newElement.find(':input').each(function () {
          // "attributes-0-attribute_value"
          let name = $(this).attr('name');
          let parts = name.split('-');
          let new_name = parts[0] + '-' + total + '-' + parts[2];
          let id = 'id_' + new_name;
          $(this).attr({
            'name': new_name,
            'id': id,
            'readonly': false
          }).val('').removeAttr('checked').addClass('unlocked').removeClass('locked');
        });
        total++;
        $(total_forms_selector).val(total);
        where.after(newElement);

        return newElement;
      }

      var last_tr_selector = '.table tr:last';

      $('#add_formset').on('click', function () {
        base_attributes_tr_html = '<tr>' + $(last_tr_selector).html() + '</tr>';
        do_add_formset($(base_attributes_tr_html), 'ordem_servico', $(last_tr_selector));
      });

    });
  </script>
{% endblock %}

Django从树冠加载数据,例如词组,数量等,但不加载树冠fk,而queryset则提供此信息。如果我在queryset中进行打印,将显示表冠的fk,但django不会在模板中呈现。

在此先感谢您的帮助。我花了几个小时在Google上进行研究,但没有解决方案。

0 个答案:

没有答案