'Python(Django): form write an ERROR befor submit

I want to check the Form after submit, but I have ERROR MASSAGE befor it. I thing there is a mistake at VIEW-file

this is my views.py:

    @login_required
    def post_create(request):
        form = PostForm(request.POST)
        template = 'posts/create_post.html'
        if request.method == 'POST':
            if form.is_valid():
                form.instance.author = request.user
                form.save()
                return redirect('posts:profile', username=request.user.username)
        return render(request, template, {'form': form})

this is my HTML template:

            {% if form.errors %}
                  {% for field in form %} 
                    {% for error in field.errors %}            
                      <div class="alert alert-danger">
                        {{ field.label }}: {{ error|escape }}
                      </div>
                    {% endfor %}
                  {% endfor %}
                  {% for error in form.non_field_errors %}
                    <div class="alert alert-danger">
                      {{ error|escape }}
                    </div>
                  {% endfor %}
              {% endif %}


Solution 1:[1]

your form is trying to submit when the page load. I usually prevent this using javascript.

try this:

<script>
    form = document.getElementById('paymentform')
    form.addEventListener('submit', function(e){
        e.preventDefault(); // prevents the form from submitting on pageload 
    form.submit();
               
    })
</script>

first give your form an id, I gave mine paymentform and then paste the above code snippet at the bottom of your html file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bruno