Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

forms - Django Method Not Allowed (POST)

In views:

def article_add(request):
    print request.user, " is adding an article"
    if request.method == "POST":
        web_url = request.POST['web_url']
        Uploadarticle(web_url)
        return redirect('myapp:index')

In html:

<form class="navbar-form navbar-right" role="form" method="post" action="{% url 'myapp:article_add' %}" enctype="multipart/form-data">
{% csrf_token %}
    <div class="form-group">
        <div class="col-sm-10">
        <input id="article_url" name="web_url" type="text">
        </div>
   </div>
   <button type="submit" class="btn btn-default"> + </button>
</form>

In url.py:

app_name = 'myapp'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^$', views.article_add, name='article_add'),
]

What i'm trying to do here is to pass the url value through html to view, call the function to upload the database, redirect the user to the same home page as refresh then the newly added item will show up.

Somehow everytime I submit I got a blank page, in terminal I got an errors says:

Method Not Allowed (POST): /
"POST / HTTP/1.1" 405 0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As I can see in the code, you are using same URL for both view, so, whenever you hit URL /, the request goes to first view(IndexView) which probably does not have any post method. Change the URL for article_add view. Do like this:

app_name = 'myapp'
urlpatterns = [
    url(r'^article-add/$', views.article_add, name='article_add'),
    url(r'^$', views.IndexView.as_view(), name='index'),

]

You will be able to access view from URL {host_address}/article-add/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...