6

我正在设计一个页面,人们可以在其中查看和创建某种类型的对象(对象是模型项目的实例)。

据我了解,如果没有非常混乱的代码,我无法在一个视图中执行此操作,因此我试图了解如何使用一个模板来显示两个视图(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.

正因为如此,我猜测有一种比我正在做的更容易实现的方法。我会很感激任何帮助。

4

2 回答 2

15

使用 CreateView 可以轻松制作,完全没有任何复杂性,不要相信 CBV 仇恨者;)

class ListAndCreate(CreateView):
    model = YourModel
    template_name = "your-template.html"

    def get_context_data(self. **kwargs):
        context = super().get_context_data(**kwargs)
        context["objects"] = self.model.objects.all()
        return context

没有循环,没有条件意味着测试它没有问题。

于 2013-10-13T08:17:46.667 回答
9

一种基于函数的简洁视图,用于列出和创建对象...

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})
于 2013-10-13T03:39:22.393 回答