TAGS :Viewed: 4 - Published at: a few seconds ago

[ django model form is not displaying any errors ]

I am not getting any errors in the template. It just gives me back the form without error. Although the uploading function works fine, but if I don't give any input it doesn't give me any errors. How would I get the errors if there are in my template?

html:

{% block content %}
    <form action="/{{ user.username }}/upload_photos/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Upload"/>
    </form>
{% endblock %}

views.py:

def upload_photos(request, user_name):
    user = User.objects.get(username=unquote(user_name))
    if request.method=='POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            forum = form.save(commit=False)
            forum.user = user
            forum.save()
            return HttpResponseRedirect('/'+user.username+'/photos')
        else:
            form = PhotoForm()
            return render(request, 'upload_photos.html',{'form':form})

    else:
        form = PhotoForm()
        return render(request, 'upload_photos.html',{'form':form})

Answer 1


I've commented out the line that empties your form.

def upload_photos(request, user_name):
    user = User.objects.get(username=unquote(user_name))
    if request.method=='POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            forum = form.save(commit=False)
            forum.user = user
            forum.save()
            return HttpResponseRedirect('/'+user.username+'/photos')
        else:
            #  form = PhotoForm()  Don't overwrite the submitted form.
            return render(request, 'upload_photos.html',{'form':form})

    else:
        form = PhotoForm()
        return render(request, 'upload_photos.html',{'form':form})