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

时间:2013-01-25 07:42:39

标签: python django python-2.7 django-generic-views django-1.4

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 :(得分: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)

有关详细信息,请参阅generic-editing in class based views

答案 1 :(得分: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

您可以将表单对象传递给上下文字典中的一个键。

可以找到更多信息here