-2

In my views.py my have a view where a user can create a post with a title, media file and caption. When i check if form.is_valid(): it always returns as false and i cannot see the issue with my form.

views.py

def your_profile(request):
    if request.method == "POST":
        form = CreatePost(request.POST)
        if form.is_valid(): 
            title = form.cleaned_data.get("title_input")
            media = form.cleaned_data.get("media_input")
            caption = form.cleaned_data.get("caption_input")

    context = {"title": "Your Profile"}
    return render(request, "myApp/your_profile.html", context)

forms.py

class CreatePost(forms.Form):
    title = forms.CharField(max_length=30)
    media = forms.FileField(max_length=350)
    caption =forms.CharField(max_length=300) 

html

<form action="" method="post">
    <input type="text" name="title_input" id="title_input">
    <label for="title_input">Title</label>

    <input type="file" name="media_input" id="media_input">
    <label for="media_input">Media</label>

    <input type="text" name="caption_input" id="caption_input">
    <label for="caption_input">Caption</label>

    <input type="submit" value="POST!">
</form>
logan_9997
  • 574
  • 2
  • 14

2 Answers2

0

Just ad the else block, like here:

if form.is_valid():
    ...
else:
    print(form.errors)

It will output the <li></li> tag with the name of the field and the error.
You also forgot to add:

{% csrf_token %}

Inside of your <form></form> tag in the .html
Also the name attributes of <input> tags must be similar with the names of the fields in the model. This always works for me.

0

Remove the "_input" from the "name" tag in HTML. The form is not able to find the field values. The name tag should have the same value as the corresponding attribute of the Form class.