因此,我正在构建这个学习日志应用程序,用户可以在其中创建多个主题。我正在尝试创建一个页面,用户可以在其中编辑/保存更改/删除他们的主题名称。我在edit_topic
视图函数中的逻辑是用save
和delete
按钮、下面的代码或随意检查GitHub Repo的形式显示原始主题:
你知道吗视图.py你知道吗
def edit_topics(request, topic_pk=None):
'''edit existing topics mainly the names'''
# modify the model data according to the request method and name
if request.method == 'POST' and topic_pk != None:
if 'save' in request.POST:
topic_to_change = get_object_or_404(Topic, pk=topic_pk)
form = TopicForm(instance=topic_to_change, data=request.POST)
if form.is_valid():
form.save()
elif 'delete' in request.POST:
topic_to_delete = get_object_or_404(Topic, pk=topic_pk)
topic_to_delete.delete()
return redirect('learning_logs:edit_topics')
# get the original/modified data passing to render
topics = Topic.objects.all()
topic_lst = []
for topic in topics:
form = TopicForm(instance=topic)
topic_lst.append(form)
context = {'topics': topics, 'topic_lst': topic_lst}
return render(request, 'learning_logs/edit_topics.html', context)
编辑_主题.html你知道吗
{% extends 'learning_logs/base.html' %}
{% block content %}
<section class="container">
<h3>Topics you have created</h3>
<ul class="">
{% for form in topic_lst %}
<li class="mb-5">
<form class="d-flex align-items-center"
action="{% url 'learning_logs:edit_topics' form.instance.pk %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-primary" name="submit">save</button>
<button class="btn btn-danger" name="delete">delete</button>
</form>
</li>
{% endfor %}
</ul>
<a class="btn btn-info" href="{% url 'learning_logs:topics' %}">Done</a>
</section>
{% endblock content %}
你知道吗网址.py你知道吗
from django.urls import path
from . import views
app_name="learning_logs"
urlpatterns = [
path('', views.index, name='index'),
path('topics/', views.topics, name='topics'),
path('topics/edit/', views.edit_topics, name='edit_topics'),
path('new_topic/', views.new_topic, name='new_topic'),
path('topic_<int:topic_pk>/', views.topic, name='topic'),
path('topic_<int:topic_pk>/new_entry/', views.new_entry, name='new_entry'),
path('topic_<int:topic_pk>/entry_<int:entry_pk>/', views.entry, name='entry'),
path('topic_<int:topic_pk>/entry_<int:entry_pk>/edit_entry/', views.edit_entry, name='edit_entry'),
]
但是,我认为可能有一些逻辑错误,它不断地引起NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'edit_topics' with arguments '(1,)' not found. 1 pattern(s) tried: ['topics/edit$']
如果删除edit_topics.html
文件中的form.instance.pk
,则不会引发错误。但是结果是,view函数中的if
逻辑将不起作用。。。我对编程相当陌生,我肯定也有一些逻辑错误——
我正在视图函数中处理topic_pk
可选参数,因为我不确定如何正确地传递它。你知道吗
理想情况下,我希望用户可以逐个编辑、保存或删除此页面上的主题,单击save
或delete
后,页面将重定向回此视图并呈现更新的主题文本。最后,完成后,他们可以单击末尾的Done
按钮。。。你知道吗
请帮帮我!谢谢!!你知道吗
按以下方式更新您的url:
在html中,更改以下行:
在这里,我做的是,有两个url指向同一个视图,一个有
topic_pk
,另一个没有。你知道吗相关问题 更多 >
编程相关推荐