如何将表单传递给基于类的通用视图(TodayArchiveView)?

0 投票
2 回答
1162 浏览
提问于 2025-04-17 13:37

url.py

from django.conf.urls import patterns, include, url
import os.path
from crm.views import *

urlpatterns += patterns('',
    (r'^test/$', tView.as_view()),
)

views.py

from django.views.generic import TodayArchiveView
from crm.forms import *
from crm.models import *

class tView(TodayArchiveView):
    model = WorkDailyRecord
    context_object_name = 'workDailyRecord'
    date_field = 'date'
    month_format = '%m'
    template_name = "onlyWorkDailyRecord.html"
    form_class = WorkDailyRecordForm ################## ADD

tView 是一个通用视图……

WorkDailyRecord 是在 models.py 中定义的模型

我想把表单(在 forms.py 中的 'WorkDailyRecordForm' 类)传递给模板(onlyWorkDailyRecord.html)

该怎么做呢?

添加

forms.py

from django import forms

class WorkDailyRecordForm(forms.Form):
    contents = forms.CharField(label='',
            widget=forms.Textarea(attrs={'placeholder': 'contents', 'style':'width:764px; height:35px;'}),
            required=False,
        )
    target_user = forms.CharField(label='',
            widget=forms.TextInput(attrs={'placeholder': 'target', 'style':'width:724px'}),
            required=False,
        )

onlyWorkDailyRecord.html

<form method="post" action="." class="form-inline" id="save-form">
    {{ form.as_table }}
    <button type="submit" class="btn btn-mini" id="workDailyRecord-add">작성</button>
</form>

2 个回答

0

我在把表单类传递给一个通用视图时遇到了麻烦,不过我通过重写 get_context_data() 这个函数解决了这个问题。如果有人也在找这个方法,可以参考一下。

这是来自 Mozilla 文档的一个例子:

class BookListView(generic.ListView):
    model = Book

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get the context
        context = super(BookListView, self).get_context_data(**kwargs)
        # Create any data and add it to the context
        context['some_data'] = 'This is just some data'
        return context

你需要把表单对象放入上下文字典中的一个键里。

想了解更多信息,可以点击 这里

0

在基于类的视图中,你需要指定一个 form_class

form_class = WorkDailyRecordForm

这是一个简单的例子:

class tView(TodayArchiveView):
    form_class = WorkDailyRecordForm
    template_name = 'onlyWorkDailyRecord.html'
    model = WorkDailyRecord

    def form_valid(self, form, **kwargs):
        instance = form.save(commit=True)
        return HttpResponse('Done')

    def dispatch(self, request, *args, **kwargs):
        return super(tView, self).dispatch(request, *args, **kwargs)

想了解更多信息,可以查看 基于类的视图中的通用编辑

撰写回答