1

I have been trying to work with the uploading features of Django but I just can't seem to get it to work. My form already contains enctype="multipart/form-data" so that can't be the issue. Anyways here's what im working with:

This is my model

class Photo(models.Model):
    """ This represents a Photo
    """
    caption = models.CharField(_("caption"), max_length=100, null=True,
        blank=True, unique=True)
    image = ValidateImageField(
    upload_to='uploaded_photos/Published/%Y/%B/%d/',
    content_types=['image/jpeg', 'image/gif', 'image/png'],
    max_upload_size= settings.FILE_UPLOAD_MAX_MEMORY_SIZE
    )
    source = models.URLField(_("source"), null=True, blank=True)
    status = models.CharField(_("status"), max_length=1, choices=STATUS_CHOICES,    default='H')
    date_added = models.DateTimeField(_("date_added"), auto_now_add=True)
    date_modified = models.DateTimeField(_("date_modified"), auto_now=True)
    slug = models.SlugField(_("slug"), max_length=50, unique=True)
    extra_info = models.TextField(_("extra_info"), null=True, blank=True)

This is my form:

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = Photo
        field = ('image', 'caption', 'source', 'extra_info',)
        exclude = ('status','slug',)

This is my view:

def submit_image(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid:
            form.save()
        return redirect('photos.views.upload_success')

    form = UploadImageForm()
    return render(request,'photos/upload.html', {
        'form': form
    })

I have already tried using the chunks method as shown in the djangodocs and that too doesn't work. Could there be a problem with my code, if so I would be grateful if someone can point it out. Thanks in Advance.

cclerv
  • 2,921
  • 8
  • 35
  • 43

1 Answers1

2

I'm sure that your form is just invalid (for example there is no required slug provided). But you don't handle this, redirecting to success page anyway. Also you've forgotten parentheses after is_valid, so it will be always True. Correct view will be something like this:

def submit_image(request):
    form = UploadImageForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        return redirect('photos.views.upload_success')

    return render(request,'photos/upload.html', {
        'form': form
    })
DrTyrsa
  • 31,014
  • 7
  • 86
  • 86