Django form posting does nothing

2019-08-23 22:51发布

问题:

I'm making an Image posting form with thes fields: Title, Description, Image file, and a public or not boolean. The issue I have is that it does nothing. It seems to post as I can see it in the dev server console, but then nothing, no image in media/photos, nothing in the database either... Weird thing is that when I create an Image object from the django admin page, It works perfectly fine. So it must be in the view or template, but I may be wrong. Here's the code:

<!--The template-->
{% if user.is_authenticated %}

    <h1>Ajouter une image</h1>
    <h2>Deconnexion:</h2><a href="/Gallery/Disconnect/">Ici</a>
    <p>
    <form method="post" enctype="multipart/form-data" action=".">
    {% csrf_token %}
    <p><label for="id_titre">Titre:</label>
    <input id="id_titre" type="text" name="Titre" maxlength="100" /></p>
    <p><label for="id_description">Description:</label>
    <textarea name="Description" id="id_description" ></textarea></p>
    <p><label for="id_i">Image:</label>
    <input type="file" name="Image" id="id_i" /></p>
    <p><label for="id_public"><input type="checkbox" name="public" id="id_public"/>Public <!-- Attention, Internet est un lieu public, meme si cette case n'est pas cochée, votre image devient publique une fois postée. elle ne sera cependant pas affichée dans la gallerie aleatoire ou dernieres images. -->
    </label></p>
     <input type="submit"/>
    </form>
    </p>
    {% if sauvegarde %}
    <p>Image saved.</p>
    {% endif %}
{% else %}
    <h1>Connect</h1>
        {% if error %}
        <p><strong>wrong password, or user does not exist, sorry</strong></p>
        {% endif %}
    <form method="post" action=".">
    {% csrf_token %}
    <p><label for="id_username">Username:</label>
    <input id="id_username" type="text" name="username" maxlength="30" /></p>
    <p><label for="id_password">Password:</label>
    <input id="id_password" type="password" name="password" maxlength="30" /></p>
    <input type="submit"/>
    </form><h1>Or Register <a href="/Gallery/Register/">here</a></h1>
{% endif %}

The View:

#The view
def Publish(request):
    reg = False
    sauvegarde = False
    if request.user.is_authenticated():
        if request.method == "POST":
            form = ImagePublish(request.POST, request.FILES)
            if form.is_valid():
                pic = Image()
                pic.titre = form.cleaned_data["titre"]
                pic.description = form.cleaned_data["description"]
                pic.i = form.cleaned_data["i"]
                pic.public = form.cleaned_data["public"]
                pic.save()

                sauvegarde = True
            else:
                form = ImagePublish(request.POST, request.FILES)
    else :
        if request.method == "POST":
            form = ConnexionForm(request.POST)
            if form.is_valid():
                username = form.cleaned_data["username"]  # Nous récupérons le nom d'utilisateur
                password = form.cleaned_data["password"]  # … et le mot de passe
                user = authenticate(username=username, password=password)  #Nous vérifions si les données sont correctes
                if user:  # Si l'objet renvoyé n'est pas None
                    login(request, user)  # nous connectons l'utilisateur
                else: #sinon une erreur sera affichée
                        error = True
        else:
            form = ConnexionForm()

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

The form:

#The form
class ImagePublish(forms.Form):
    titre = forms.CharField(max_length=100)
    description = forms.CharField(widget=forms.Textarea)

    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
    public = forms.BooleanField(required=False)

That's it, I can add any other part of the code you need and everything is imported, also I would like to point the fact that I got no error, and the message I set to say like "cool, Image uploaded" doesn't show up, If that can show anyone the good direction...

回答1:

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


回答2:

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).



回答3:

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



标签: django forms