django 无法添加< Image>示例位于数据库“default”上,值位于数据库“None”上

vhmi4jdf  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(114)

我在Django中开发和应用程序,当我提交表单y时,我得到了这个错误,当它试图在ManyToMany关系上添加图像时,就会出现这个问题。

Internal Server Error: /publish_offer/
Traceback (most recent call last):
  File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view
    return view_func(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Projects\revenue\management\views.py", line 49, in publish_offer
    oferta.imagenes.add(*imgs)
  File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1137, in add
    self._add_items(
  File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1397, in _add_items
    target_ids = self._get_target_ids(target_field_name, objs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1313, in _get_target_ids
    raise ValueError(
ValueError: Cannot add "<ImagenesOferta: ImagenesOferta object (None)>": instance is on database "default", value is on database "None"
[29/Jun/2023 16:10:20] "POST /publish_offer/ HTTP/1.1" 500 87580

这是我的模型:

class ImagenesOferta(models.Model):
    imagen = models.ImageField(verbose_name='Imagen Oferta', blank=False, null=False, upload_to='img_ofertas/')

    class Meta:
        verbose_name = 'Imagen de Oferta'
        verbose_name_plural = 'Imagenes de Ofertas'
        ordering = ['-id']

class Oferta(models.Model):
    titulo = models.CharField(verbose_name='Título', max_length=100, null=False, blank=False)
    descripcion = models.TextField(verbose_name='Descripción', null=True, blank=True)
    cantidad = models.PositiveSmallIntegerField(verbose_name='Cantidad', null=False, blank=False, default=1)
    valor = models.DecimalField(verbose_name='Valor', max_digits=4, decimal_places=2, null=False, blank=False)
    material = models.CharField(verbose_name='Material', max_length=20, null=False, blank=False, choices=MATERIAL_CHOICES)
    imagenes = models.ManyToManyField(ImagenesOferta, verbose_name='Imagenes de la Oferta', blank=True)
    usuario = models.ForeignKey(Usuario, verbose_name='Usuario', null=False, blank=False, on_delete=models.CASCADE)
    is_active = models.BooleanField(verbose_name='Activo/Inactivo', default=True)
    vendido = models.BooleanField(verbose_name='Vendido', default=False)
    fecha_creacion = models.DateTimeField(verbose_name='Fecha de Creación', auto_now_add=True)

    def __str__(self):
        return self.titulo

    class Meta:
        verbose_name = 'Oferta'
        verbose_name_plural = 'Ofertas',
        ordering = ['-fecha_creacion']

这是我的看法

@login_required(login_url='login')
def publish_offer(request):

    form = formOferta()

    if request.method == 'POST':
        form = formOferta(request.POST, request.FILES)
        if form.is_valid():
            form.instance.usuario = request.user
            oferta = form.save()
            imgs = [
                ImagenesOferta(imagen=image)
                for image in request.FILES.getlist('imagenes')
            ]
            ImagenesOferta.objects.bulk_create(imgs)
            oferta.imagenes.add(*imgs)
            return redirect('home')
        else:
            messages.error(request, form.errors)
            return render(request, 'publicar_oferta.html', {
                'form': form
            })
        
    return render(request, 'publicar_oferta.html', {
        'form': form
    })

这是我的模型表

class formOferta(forms.ModelForm):

    class Meta:
        model = Oferta
        fields = ('titulo', 'descripcion', 'cantidad', 'valor', 'material')
        widgets = {
            'titulo': forms.TextInput(
                attrs={
                    'class': 'form-control w-100',
                    'id': 'titulo',
                    'placeholder': 'Coloca el título aquí'
                }
            ),
            'descripcion': forms.Textarea(
                attrs={
                    'class': 'form-control w-100',
                    'id': 'descripcion',
                    'placeholder': 'Añade la descripción aquí'
                }
            ),
            'cantidad': forms.NumberInput(
                attrs={
                    'type': 'range',
                    'class': 'form-range w-100',
                    'id': 'cantidad',
                    'min': '1',
                    'max': '100',
                    'steps': '1',
                    'value': '0'
                }
            ),
            'valor': forms.NumberInput(
                attrs={
                    'class': 'form-control',
                    'id': 'valor',
                    'steps': '0.01',
                    'placeholder': '0.00$'
                }
            ),
            'material': forms.Select(
                attrs={
                    'class': 'custom-select'
                },
                choices=MATERIAL_CHOICES
            )
        }

我真的卡住了,昨天的应用程序没有这种行为,如果有人能给予我一个手,我会非常感激!!

1zmg4dgp

1zmg4dgp1#

我认为问题在于ImagenesOferta(imagen=image)。这是一个尚未保存到数据库的查询,因此无法添加到oferta.imagenes。我也很困惑,imagen=image。我把imagen看作是ImagenesOferta的一个字段,但是image是从哪里来的呢?也许你想要的是这个:

if form.is_valid():
    form.instance.usuario = request.user
    oferta = form.save()
    imgs = [
        for image in request.FILES.getlist('imagenes'):
            ImagenesOferta(imagen=image).save()   
    ]
    # ImagenesOferta.objects.bulk_create(imgs)
    oferta.imagenes.add(*imgs)
    return redirect('home')

相关问题