我正在设计一个页面,人们可以在其中查看和创建某种类型的对象(这些对象是模型Project的实例)。
据我了解,没有可怕的凌乱代码,我无法在一个视图中做到这一点,所以我试图了解如何使用一个模板来显示两个视图(ProjectCreateView和ProjectListView)。
现在,这就是我正在处理的内容:
views.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)
urls.py
urlpatterns = patterns('',
url(r'^projects/$', ProjectView.as_view(), name="projects"),
)
models.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.
因此,我猜想比我正在做的事情要容易得多。我将不胜感激。
最佳答案
一种基于混乱函数的视图,用于列出和创建对象...
from django.shortcuts import render
# model and form imports
def list_and_create(request):
form = YourModelForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
form.save()
# notice this comes after saving the form to pick up new objects
objects = YourModel.objects.all()
return render(request, 'your-template.html', {'objects': objects, 'form': form})
关于django - Django模板中的ListView和CreateView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19341568/