在 Django 上使用 CreateView 时出现 KeyError

问题描述 投票:0回答:1

当我尝试创建一个对象“Comprobante”时,会抛出错误:




KeyError at /caja_chica/comprobantes/crear/

'comprobante'

Request Method:     POST
Request URL:    http://127.0.0.1:8000/caja_chica/comprobantes/crear/
Django Version:     3.2.5
Exception Type:     KeyError
Exception Value:    

'comprobante'



这是我的模型 Comprobante:





class Comprobante(models.Model):
    TIPO_A = 1
    TIPO_B = 2
    TIPO_C = 3
    TIPO_T = 4
    TIPO_X = 5

    TIPO_CHOICES = (
        (TIPO_A, 'A'),
        (TIPO_B, 'B'),
        (TIPO_C, 'C'),
        (TIPO_T, 'T'),
        (TIPO_X, 'X'),
    )

    caja_chica = models.ForeignKey(CajaChica, on_delete=models.PROTECT)
    lote = models.ForeignKey(Lote, on_delete=models.DO_NOTHING, null=True, blank=True,         related_name='lote_comprobantes')
    numero = models.CharField(max_length=13)
    tipo = models.PositiveSmallIntegerField(choices=TIPO_CHOICES, default=TIPO_T)
    ente = models.ForeignKey(Ente, on_delete=models.PROTECT)
    fecha = models.DateField()
    partida_presupuestaria = models.ForeignKey(PartidaPresupuestaria, on_delete=models.PROTECT)
    detalle = models.CharField(max_length=100)
    importe = models.DecimalField(max_digits=7, decimal_places=2)
    history = HistoricalRecords()

    def __str__(self):
        return self.numero

    #def save(self, *args, **kwargs):
    #    super(Comprobante, self).save(*args, **kwargs)
    #    self.caja_chica.disponible -= self.importe
    #    self.caja_chica.save()

    def get_absolute_url(self):
        """
        Devuelve la url para acceder a una instancia particular de Comprobante.
        """
        return reverse('caja_chica:comprobante_update', args=[str(self.id)])

这是我的表格:

class ComprobanteForm(forms.ModelForm):
    class Meta:
        model = Comprobante
        fields = ('__all__')

我使用 CreateView 的视图:

class ComprobanteCreate(SuccessMessageMixin, CreateView):
    model = Comprobante
    fields = '__all__'
    success_url = reverse_lazy('caja_chica:comprobante_list')
    success_message = "%(comprobante)s fue creado exitosamente"

和我的 comprobante_form 模板:

{% extends "caja_chica/base.html" %}

{% block breadcrumbs %}
<div class="breadcrumbs">
    <a href="{% url 'caja_chica:inicio' %}">Inicio</a> >
    <a href="{% url 'caja_chica:comprobante_list' %}">Comprobantes</a> >
    {% if comprobante.id %} {{ comprobante }} {% else %} Agregar {% endif %}
</div>
{% endblock %}

{% block content %}

<h1>{% if comprobante.id %} Modificar {% else %} Agregar {% endif %} Comprobante </h1>

<form action="" method="post">
    {% csrf_token %}
    <table>
    {{ form.as_table }}
    </table>
    <input type="submit" value="Guardar" />
</form>
{% endblock %}

我认为是视图问题,但我不明白问题所在,也不知道问题在哪里

我尝试通过视图中的函数传递上下文,如下所示:

    def get_context_data(self, **kwargs):
        context = super().get_context_data( **kwargs)
        context['comprobante'] = None
        print(context)
        return context
python-3.x django django-views
1个回答
0
投票

success_message
不是 插入上下文,而是表单的
cleaned_data
,因此在本例中是模型的所有字段。

因此您可以使用:

class ComprobanteCreate(SuccessMessageMixin, CreateView):
    model = Comprobante
    fields = '__all__'
    success_url = reverse_lazy('caja_chica:comprobante_list')
    success_message = '%(numero)s fue creado exitosamente'
© www.soinside.com 2019 - 2024. All rights reserved.