我尝试制作更新现有类别的表单,然后重定向回“类别”页面。这是我的代码:
forms.py
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter the category name.")
description = forms.CharField(max_length=256, required=False, help_text="Please enter the description of the category.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
status = forms.BooleanField(label='Status',
required=False,
help_text="Is this category still active?")
# An inline class to provide additional information on the form.
class Meta:
# Provide an association between the ModelForm and a model
model = Category
fields = ('name', 'description', )
views.py
def update_category(request, category_name_slug):
obj = get_object_or_404(Category, slug=category_name_slug)
form = CategoryForm(request.POST or None, instance=obj)
if form.is_valid():
form.save()
return HttpResponseRedirect(
reverse('obj', kwargs={'category_name_slug':category_name_slug}) )
return render(request, "courses/update_category.html", {'form': form})
update_category.html
{% block main_content %}
<h1>Add a Category</h1>
<form id="update_category_form" method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<br/>
<input type="submit" name="submit" value="Update Category" />
</form>
{% endblock %}
当我尝试使用此表单进行更新时,出现NoReverseMatch错误。我觉得它与views.py有关。我怎么写第一次回报?我设法得到另一个更新表格没有slug工作正常,所以它是导致问题的slu ??我需要pk / id吗?感谢。
编辑:这是网址模块:
urls.py
urlpatterns = [
url(r'^$', views.courses, name='courses'),
url(r'^about/', views.about, name='about'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/add_course/$', views.add_course, name='add_course'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/delete_category/$', views.delete_category, name='delete_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/update_category/$', views.update_category, name='delete_category'),
答案 0 :(得分:0)
您应该将类别页面的网址模式名称提供给reverse
:
def update_category(request, category_name_slug):
...
if form.is_valid():
form.save()
return HttpResponseRedirect(
reverse('category', kwargs={'category_name_slug':category_name_slug}) )
答案 1 :(得分:0)
错误在于:
body{ overflow: hidden }
您传递的是reverse
方法,字符串document.body.style.overflow = "auto";
实际上是return HttpResponseRedirect(reverse('obj', ...)
个对象。
一种优雅的方法是在'obj'
模型中添加get_absolute_url
方法,如下所示:
Category
然后,在Category
视图中,只需执行以下操作:
class Category(models.Model):
# model fields here
def get_absolute_url(self):
return reverse('category', kwargs={'category_name_slug': self.slug})