我的问题是关于再次重定向到/ topics / [id_number_for_topic]页面,其中所有主题条目均位于该页面。当我在/ edit_entry / [id_number_for_entry]中结束条目编辑并单击按钮时,将发生以下错误:
Reverse for 'topics' with arguments '(3,)' not found. 1 pattern(s) tried: ['topics/$']
此数字3表示主题ID。
我想问题在于在views.py> edit_entry()或正则表达式中的返回指令
我的代码:
views.py
def edit_entry(request, entry_id):
"""Edycja wpisu"""
entry = Entry.objects.get(id=entry_id)
topic = entry.topic
if request.method != 'POST':
form = EntryForm(instance=entry)
else:
form = EntryForm(instance=entry, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_logs:topics',
args=[topic.id]))
context = {'entry': entry, 'topic': topic, 'form': form}
return render(request, 'edit_entry.html', context)
urls.py
url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'),
url(r'^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry, name='edit_entry'),
models.py
class Topic(models.Model):
"""Temat poznawany przez usera"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Zwraca reprezentacje modelu w postaci ciagu text."""
return self.text
class Entry(models.Model):
"""Konkret informacje o postepie w nauce"""
topic = models.ForeignKey(Topic)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
return self.text[:50] + "..."
edit_entry.html
{% block content %}
<p><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p>
<h3>Edycja wpisu:</h3>
<form action="{% url 'learning_logs:edit_entry' entry.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Zapisz zmiany</button>
</form>
{% endblock content %}
答案 0 :(得分:0)
此代码中有一个错字。在这里:
return HttpResponseRedirect(reverse('learning_logs:topics',
args=[topic.id]))
应该是:
return HttpResponseRedirect(reverse('learning_logs:topic',
args=[topic.id]))
答案 1 :(得分:0)
我建议您使用reverse
中的django
。
from django.urls import reverse
...
return HttpResponseRedirect(reverse('learning_logs:topics', kwargs=dict(topic_id=topic.id)))