【问题标题】:Data not saved when using CreateView and ListView on same url在同一网址上使用 CreateView 和 ListView 时未保存数据
【发布时间】:2018-06-08 22:40:17
【问题描述】:

我有以下view.py。目标是在同一 url 上的每个 ListView 项目上显示 CreateView 表单。现在 textarea 正在显示,但提交表单不会保存数据。我真的很感激任何帮助。

view.py:

class CreatePost(CreateView):
    class PostForm(ModelForm):
        class Meta:
            model = Post
            fields = ['post'] 
            widgets = {
            'post': forms.Textarea()
            }

class TheList(ListView):
    model = Item
    template_name='item/items.html'

    def get_context_data(self, **kwargs):
        context = super(TheList, self).get_context_data(**kwargs)
        context['form'] = CreatePost.PostForm
        return context

【问题讨论】:

  • 在同一个 URL 上是什么意思?任何 URL 只能调用一个视图。

标签: django django-models django-forms django-views


【解决方案1】:

数据无法自动保存,因为ListView 不是为此而设计的。您只需使用其context_data 发送表单。 但是ListView有post()和get()方法,你可以根据请求方法取回post或者get中提交的数据。

def post(self, request, *args, **kwargs):
    form  = CreatePost.PostForm(request.POST)
    if form.is_valid():
        form.save()
    return render(request, self.template_name, {'form': form})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    相关资源
    最近更新 更多