[Answer]-Django form posting does nothing

0đź‘Ť

âś…

I just solved my issue, actually it was the auteur field that didn’t fill itself with connected user, so it didn’t validate cause it was empty and the Image wasn’t posting. I just added “pic.auteur = request.user” in my view and it did it. If you need it just ask and I’ll post the new code! bye

👤ClementLebre

1đź‘Ť

If you’re adding stuff from admin, then you must have a model. In that case, you need to use ModelForm for the form and use @dhana’s approach, not doing it manually (admin interface does it via ModelForm afaik.

You may want to use the {{form}} and render the errors like {{ form.non_field_errors }}. This way you can see what’s wrong.

You may want to start from a simple form (without all the validation code).

👤Laur Ivan

0đź‘Ť

You are not rendering the empty form to html using django forms at GET request. Like this,

GET Request:

form = ImagePublish()

return render(request, 'Publier.html',locals())

django template Publier.html

<form method="post" enctype="multipart/form-data" action=".">
    {% csrf_token %}
    {{ form }}
</form>

Then submitting form is post request,

 if request.method == "POST":
    form = ImagePublish(request.POST, request.FILES)
    if form.is_valid():
        form.save()

forms.py:

from .models import Image
    class ImagePublish(forms.ModelForm): # This is my change
        class Meta:
           model = Image
        def clean_content(self):
            if content != None:
                content = self.cleaned_data['content']
                content_type = content.content_type.split('/')[0]
                if content_type in settings.CONTENT_TYPES:
                    if content._size > int(settings.MAX_UPLOAD_SIZE):
                        raise forms.ValidationError(_(u'Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size)))
                else:
                    raise forms.ValidationError(_(u'File type is not supported'))
                return content
👤dhana

Leave a comment