Post方法无法发送

时间:2018-05-15 04:50:29

标签: python django

我决定更改学习日志的主题。

enter image description here

当我按下提交按钮时,它无法重定向并报告479错误。

[15/May/2018 12:46:32] "POST /edit_topic/5 HTTP/1.1" 200 479

edit_topic.html

{% extends "learning_logs/base.html" %}

    {% block content %}
        <p>
            <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a>
        </p>
        <p>Edit The Entry:</p>
        <form  action="{% url "learning_logs:edit_topic" topic.id %}" method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <button name="button">save changes</button>

        </form>

    {% endblock content %}

forms.py

from django import forms
from .models import Topic, Entry

class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic
        fields = ['text']
        labels = {'text':''}

views.py

def edit_topic(request, topic_id):
    topic = Topic.objects.get(id=topic_id)

    if request != "POST":
        form = TopicForm(instance=topic)
        print(request) # test point
    else:
        form = TopicForm(instance=topic, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("learning_logs:topic", args=[topic_id]))

    context = {'topic':topic, 'form':form}
    print(form) # test form 
    return render(request, "learning_logs/edit_topic.html", context)

urls.py

urlpatterns = [
    #Home Page
    url(r'^$', views.index, name='index'),
    # Show all the topics
    url(r'^topics/$', views.topics, name='topics'),
    # Detail pate for a single topics
    url(r'^topic/(?P<topic_id>\d+)/$', views.topic, name='topic'),
    # Page for adding a new topic
    url(r'^new_topic/$', views.new_topic, name='new_topic'),
    # Page for editing the topic
    url(r'^edit_topic/(?P<topic_id>\d+)$', views.edit_topic, name='edit_topic'),
    # page for adding a new Entry
    url(r"^new_entry/(?P<topic_id>\d+)$", views.new_entry, name='new_entry'),
    # page for adding a edit  Entry
    url(r"^edit_entry/(?P<entry_id>\d+)$", views.edit_entry, name="edit_entry"),
]

models.py

class Topic(models.Model):
    """A topic the user is learning about."""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """Return a string representation of the model."""
        return self.text

我的代码有什么问题?

当我尝试提交时,没有错误,但未提交更改。

System check identified no issues (0 silenced).
May 15, 2018 - 13:01:44
Django version 1.11.13, using settings 'learning_log.settings'
Starting development server at http://127.0.0.1:8001/
Quit the server with CONTROL-C.
[15/May/2018 13:01:48] "POST /edit_topic/4 HTTP/1.1" 200 475

1 个答案:

答案 0 :(得分:1)

您认为情况不正确

if request != "POST" # this will be always true

应该是

if request.method != "POST"