【问题标题】:Topics arent being added未添加主题
【发布时间】:2020-09-04 16:28:01
【问题描述】:

我对 python 和 django 都很陌生,目前正在阅读 Eric Matthes 的 Python Crash Course。我试图编写一个简单的学习日志,但我在使用 django 表单添加新主题时遇到了一些问题。代码如下:

urls.py: 从 django.urls 导入路径,re_path 从 。导入视图

urlpatterns = [
    #Home page
    
    path('', views.index, name='index'),
    path('topics/', views.topics , name='topics'),
    re_path(r'^topics/(?P<topic_id>\d+)/$' , views.topic , name = 'topic'),
    re_path(r'^new_topic/$' , views.new_topic , name = 'new_topic')
]

app_name = 'learning_logs'

view.py 的一部分:

def new_topic(request):
    if request.method != 'POST':
        form = TopicForm
    else:
        form = TopicForm(request.POST)
        if form.is_valid():
            form.save
            return HttpResponseRedirect(reverse('learning_logs:topics'))

    context = {'form' : form}
    return render(request , 'learning_logs/new_topic.html' , context)

new_topic.html: {% 扩展 'learning_logs/base.html' %}

{% block content %}

<p>Added a new topic:</p>
<form action="{% url 'learning_logs:new_topic' %}" method="post">

{% csrf_token %}
{{form.as_p}}
<button name='submit'>add topic</button>

</form>

{% endblock content %}

topics.html: {% 扩展 'learning_logs/base.html' %}

{% block content %}

<p>Topics</p>

<ul>

  {% for topic in topics %}
    <li><a href="{% url 'learning_logs:topic' topic.id %}">{{topic}}</a></li>
  {% empty %}
    <li>No topics have been added yet.</li>
  {% endfor %}

</ul>

<a href="{% url 'learning_logs:new_topic' %}">Add a new topic:</a>

{% endblock content %}

【问题讨论】:

  • 可能是因为你没有运行 form.save。试试加():form.save()
  • 就是这样。谢谢

标签: python django django-forms


【解决方案1】:

括号不见了。它应该像 bkrop 提到的那样 form.save()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2019-04-09
    • 2017-07-21
    相关资源
    最近更新 更多