Problems uploading images using django formsets

1

Good day the reason why I make this entry is because I am struggling to load images using django forms, when creating a new product two forms appear to load two more images, the problem is that when loading all the forms if they create these records in the Database, but without the images that must be uploaded. Thanks in advance!

models.py

class Etiqueta(models.Model):
    nombre = models.CharField(max_length = 20)
    def __str__(self):
        return self.nombre
    class Meta:
        verbose_name = 'Etiqueta'
        verbose_name_plural = 'Etiquetas'
class Producto(models.Model):
    nombre = models.CharField(max_length = 70)
    descripcionCorta = models.CharField(max_length = 150)
    descripcionDetallada = models.TextField()
    imagenPrincipal = models.ImageField(upload_to = 'imagenesProductos/', null=True, blank=True)
    precioOriginal = models.PositiveIntegerField()
    precioDescuento = models.PositiveIntegerField(null=True, default= None, blank=True)
    cantidad = models.PositiveSmallIntegerField(null=True, blank=True)
    especificaciones = models.TextField(null=True, blank=True)
    calificacion = models.PositiveSmallIntegerField(null=True, blank=True)
    categoria = models.CharField(max_length = 30)
    fechaCreacion = models.DateField(auto_now_add=True)
    etiqueta = models.ManyToManyField(Etiqueta)
    def __str__(self):
        return self.nombre
    class Meta:
        verbose_name = 'Producto'
        verbose_name_plural = 'Productos'
class FotografiaProducto(models.Model):
    producto = models.ForeignKey(Producto, null=True, blank=True, on_delete=models.CASCADE)
    fotografia = models.ImageField(upload_to = 'imagenesProductos/', null=True, blank=True)
    def __str__(self):
        return str(self.id)

views.py

@login_required()
def addProducto(request):
    data = {
        'form-TOTAL_FORMS': '2',
        'form-INITIAL_FORMS': '0',
        'form-MAX_NUM_FORMS': '',
    }
    FotoProductoFormSet = formset_factory(FotoProductoForm, extra=2)
    if request.method == 'POST':
        formaFoto = FotoProductoForm(request.POST, request.FILES, prefix='fotografia')  
        productoForm = ProductoForm(request.POST, request.FILES)
        formset = FotoProductoFormSet(data, request.POST, request.FILES)
        if productoForm.is_valid() and formset.is_valid():
            nuevoProducto = productoForm.save(commit=False)
            nuevoProducto.imagenPrincipal = request.FILES['imagenPrincipal']
            nuevoProducto.save()
            post = get_object_or_404(Producto, pk=nuevoProducto.id)
            for form in formset:
                nuevaImagen = form.save(commit=False)
                nuevaImagen.producto = post
                nuevaImagen.save()
            return redirect('productoList')
    else:
        productoForm = ProductoForm()
        formset = FotoProductoFormSet(prefix='fotografia')
    return render(request, 'producto/formularioProducto.html', {'form':productoForm, 'formset':formset})

forms.py

class ProductoForm(forms.ModelForm):
    class Meta:
        model = Producto
        fields = [
            'nombre',
            'descripcionCorta', 
            'descripcionDetallada',
            'imagenPrincipal',
            'precioOriginal',
            'precioDescuento',
            'cantidad',
            'especificaciones',
            'categoria',
            'etiqueta'
        ]
        labels = {
            'nombre': 'Nombre',
            'descripcionCorta': 'Descripcion corta', 
            'descripcionDetallada': 'Descripcion detallada',
            'imagenPrincipal': 'Imagen principal',
            'precioOriginal' : 'Precio original',
            'precioDescuento': 'Precio con descuento',
            'cantidad': 'Numero de articulos disponibles',
            'especificaciones': 'Especificaciones',
            'categoria': 'Categoria',
        }
        widgets = {
            'nombre': forms.TextInput(),
            'descripcionCorta': forms.TextInput(), 
            'descripcionDetallada': forms.TextInput(),
            'precioOriginal': forms.NumberInput(),
            'precioDescuento': forms.NumberInput(),
            'cantidad': forms.NumberInput(),
            'especificaciones': forms.TextInput(),
            'categoria': forms.TextInput(),
        }

    #etiqueta = forms.ModelMultipleChoiceField(queryset=Etiqueta.objects.all())
    def __init__(self, *args, **kwargs):
        super(ProductoForm, self).__init__(*args, **kwargs)
        self.fields["etiqueta"].widget = CheckboxSelectMultiple()
        self.fields["etiqueta"].queryset = Etiqueta.objects.all()
class FotoProductoForm(forms.ModelForm):
    def __name__(self):
        return self.__class__.__name__
    class Meta:
        model = FotografiaProducto
        fields = [
            'fotografia',
        ]
        labels = {
            'fotografia' : 'Fotografia Secundaria',
        }

productoProduct.html form

{% extends 'usuarios/base.html' %}
{% block content %}
    <h1>Registro Reventeando</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        {{form2.as_p}}
        {% for forma in formset %}
            {{forma.as_p}}
        {% endfor %}
        <button>Guardar</button>
    </form>
{% endblock %}
    
asked by Luis Avila Gurrola 30.03.2017 в 22:54
source

0 answers