Search code examples
pythonflaskflask-wtformsflask-restful

Method Not Allowed - The method is not allowed for the requested URL


I'm trying to build a python flask application, but I'm facing an issue when I try to submit form data to the python method.

The issue that the server is throwing is "Method Not Allowed".

HTML CODE

<h1>Submit the Link</h1>
    <form action="/submit_article" method="POST" name="form">
        <div class="col-md-4 col-md-offset-4">
            {{ form.hidden_tag() }}
            <div class="form-group">
                <label class="control-label" for="description">Name</label>
                {{ form.description }}
            </div>
            <div class="form-group">
                <label class="control-label" for="link">Link</label>
                {{ form.link }}
            </div>
            <button class="btn btn-default" type="submit">Submit</button>
        </div>
    </form>

PYTHON METHOD (submit_article)

@app.route('/submit_article', methods=['POST'])
def submit_article():
  form = UploadForm()
  if request.method == 'POST':
    data = {
        "_id": form.link.data,
        "description": form.description.data,
        "user": current_user.username,
        "time": datetime.datetime.now()
    }

    try:
        if((app.config['NEWS_COLLECTION'].insert(data))):
            flash("Link added successfully", category="success")
            return redirect(request.args.get("new") or url_for("new"))

    except DuplicateKeyError:
        flash("Article link already exists in the Database", category="error")
        return render_template("submit_article.html")

  return render_template('submit_article.html', title='login', form=form)

Solution

  • The method is not allowed because you have only specified 'POST' in your methods list. But whenever you try to visit this URL it will send the 'GET' request. 'POST' request will be sent when you click a button but initially it will visit the page via 'GET' request.

    So replace methods=['POST'] with methods=['POST', 'GET'] and your problem will be resolve.