如何自动以特定形式填充字段

时间:2019-10-26 10:33:51

标签: django django-forms django-views

我正在开发django应用程序,以跟踪实验室中的订单和产品。我有一个Order模型,可以通过填充其中某些字段(但不是全部)的表单并创建对象的形式来创建实例。 我还创建了一个UpdateForm,以便在订单到达实验室后更新空白字段。此更新表单只有一个字段(存储位置),但是我希望此表单将订单状态自动设置为“已接收”,并在表单输入时将日期用户填充为“ received_by”字段,并使用dateTime填充“ received_date”已发送。

在撰写本文时,我只是想我可以为Receive创建一个不同的模型,并通过OnetoOne将其与Order模型相关联,

我的代码如下:

#models.py-------------------------------------------------------------
class Pedido(models.Model):
    nombre = models.CharField(max_length=40, help_text=_('Nombre del producto.'))
    referencia = models.CharField(max_length=20, help_text=_('Referencia del fabricante.'))
    cpm = models.CharField(max_length=20, default ='A la espera.',help_text=_('Código del CPM asignado a este pedido.'), null = True, blank = True, verbose_name = _('CPM'))
    fecha = models.DateTimeField(auto_now_add=True)
    unidades = models.IntegerField(default = 1)
    usuario = models.ForeignKey(User, on_delete=models.CASCADE, blank = True)
    autogestion = models.BooleanField(default = False, verbose_name='Autogestión', help_text = _("Marca esta casilla si vas a procesar tu mismo el pedido."))
    usuario_recepcion = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='recepcion')
    fecha_recepcion = models.DateTimeField(blank=True, null=True)

    ESTADO_PEDIDO = (
        ('n', _('Pendiente')),
        ('p', _('Proforma solicitada')),
        ('c', _('CPM solicitado')),
        ('v', _('Para validar')),
        ('r', _('Recibido'))
    )

    estado = models.CharField(
        max_length=1,
        choices=ESTADO_PEDIDO,
        blank=False,
        default='n',
        help_text=_('Estado del pedido'),
    )

    fabricante = models.ForeignKey('Fabricante', null = True, on_delete=models.SET_NULL)
    centro_gasto = models.ForeignKey('CentroGasto', null = True, on_delete=models.SET_NULL, verbose_name = _('Centro de Gasto'))
    almacen = models.ForeignKey('Almacen', null = True, on_delete=models.SET_NULL, blank = True)
    direccion = models.ForeignKey('Direccion', default = 'CIBM', null = True, on_delete=models.SET_NULL, verbose_name = _('Dirección de entrega'))
    codigo = models.CharField(max_length=20, blank=True, default=keygen())

#views.py----------------------------------------------------------
class PedidoListView(LoginRequiredMixin, generic.ListView):
    model = Pedido
    ordering = ['-fecha']

class PedidoDetailView(LoginRequiredMixin, generic.DetailView):
    model = Pedido

@login_required
def Guia(request):
    return render(request, 'guia.html')

@login_required
def add_pedido(request):
    if request.method == "POST":
        form = PedidoForm(request.POST)
        if form.is_valid():
            model_instance = form.save(commit=False)
            model_instance.usuario = request.user
            model_instance.save()
            return redirect('/')

    else:
        form = PedidoForm()
        return render(request, "nuevo_pedido.html", {'form': form})

class RecepcionUpdate(LoginRequiredMixin, UpdateView):
    model = Pedido
    fields = ['almacen']
    template_name_suffix = '_recepcionar'

#forms.py-----------------------------------------------------------------
class PedidoForm(ModelForm):
    def clean_usuario(self):
        if not self.cleaned_data['usuario']:
            return User()
        return self.cleaned_data['user']

    class Meta:
        model = Pedido
        exclude = ['codigo', 'fecha', 'cpm', 'almacen', 'estado', 'usuario']

1 个答案:

答案 0 :(得分:0)

如果您尝试在Django中更改预定义的类,则始终可以覆盖它。例如,您可以扩展form_valid方法:

class RecepcionUpdate(LoginRequiredMixin, generic.UpdateView):
    model = Pedido
    fields = ['almacen']
    template_name_suffix = '_recepcionar'

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.user = self.request.user
        super(RecepcionUpdate, self).save(form)

注意:我尚未对此进行测试,很可能应该调用super().save(form)而不是调用return super().form_valid(form)。无论如何,我相信通过这个示例,您将能够找到许多与Django版本匹配的代码段。