Search code examples
pythondjangoformsdjango-modelsimgur

form.is_valid always return false


form.is_valid in views.py always return false. I have used Django forms to create a form and html to implement it.

I will upload this photo to imgur using imgurpython later, but first this should work.

views.py

def upload_view(request):
usr = check_validation(request)

if usr:
    if request.method == "GET":
        form = PostForm()
        return render(request, 'upload.html', {'form': form})
    elif request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            pic = form.cleaned_data.get('image')
            title = form.cleaned_data.get('caption')
            post = PostForm()
            post.user = usr
            post.caption = title
            post.image = pic
            post.save()
            return redirect('feed/')
        else:
            return render(request, 'upload.html', {'error_msg' : "Invalid Inputs"})

else:
    return redirect('/login/')

models.py

class Post(models.Model):
    user = models.ForeignKey(User)
    image = models.FileField(upload_to='user_images')
    caption = models.CharField(max_length=240)
    image_url = models.CharField(max_length=255)
    created_on = models.DateTimeField(auto_now_add=True)

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['user', 'image', 'caption']

template - upload.html

<form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;">
    {% csrf_token %}
        <p class="text-16">Upload to aperture.</p>
    {{ form }}
    <p class="text-16">{{ error_msg }}</p>
    <input class="login-btn" type="submit" value="Upload"/>
  </form>

Solution

  • Your context has only one variable named form so you have to use that only to make your form work.

    <form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;">
            {% csrf_token %}
                <p class="text-16">Upload to aperture.</p>
            <input type="file" accept="image/*" value="{{ form.image }}" name="image" class="login-btn"/><br/>
            <input placeholder="Caption" class="input-default all-curve" rows="3" value="{{ form.caption }}" name="caption" />
            <p class="text-16">{{ form.error_msg }}</p>
            <input class="login-btn" type="submit" value="Upload"/>
          </form>