我正在设计一个页面,人们可以在其中查看和创建某种类型的对象(对象是模型项目的实例)。
据我了解,如果没有非常混乱的代码,我无法在一个视图中执行此操作,因此我试图了解如何使用一个模板来显示两个视图(ProjectCreateView 和 ProjectListView)。
现在,这就是我正在使用的:
视图.py:
class ProjectCreateView(CreateView):
model = Project
template_name = "fileupload/project_list.html"
fields = ["name"]
def get_context_data(self, **kwargs):
context = super(ProjectCreateView, self).get_context_data(**kwargs)
return context
class ProjectListView(ListView):
model = Project
def get_context_data(self, **kwargs):
context = super(ProjectListView, self).get_context_data(**kwargs)
return context
class ProjectView(View):
model = Project
def get(self, request, *args, **kwargs):
view = ProjectListView.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = ProjectCreateView.as_view()
return view(request, *args, **kwargs)
网址.py
urlpatterns = patterns('',
url(r'^projects/$', ProjectView.as_view(), name="projects"),
)
模型.py
class Project(models.Model):
name = models.CharField(max_length=200)
def get_absolute_url(self):
return reverse("projects")
表格代码
<form id="fileupload" method="post" action="." enctype="multipart/form-data">
<div class="row fileupload-buttonbar">
<div class="span7">
<span class="btn btn-primary fileinput-button">
<i class="icon-plus icon-white"></i>
<span>New Project</span>
<input type="submit" name="Create">
</span>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete Project</span>
</button>
<input type="checkbox" class="toggle">
</div>
{{ form.as_p }}
</div>
<table class="table table-striped"><tbody class="files"></tbody></table>
</form>
但是,使用此配置,表单仅在按下按钮后显示“名称”字段,输入名称后,我得到以下信息:
NoReverseMatch at /upload/projects/
Reverse for 'projects' with arguments '()' and keyword arguments '{}' not found.
正因为如此,我猜测有一种比我正在做的更容易实现的方法。我会很感激任何帮助。