0

网址.py

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

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

视图.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)

如何??

添加

表格.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>
4

2 回答 2

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)

有关更多信息,请阅读基于类的视图中的通用编辑

于 2013-01-25T08:47:08.657 回答
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

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

可以在这里找到更多信息 。

于 2021-02-18T13:25:57.223 回答