2

我有一个 django 模型,其方法取决于input应以表格形式读取的变量。此方法显示为表的列使用django_tables2,列中的值取决于input用户在表单中引入的值。

class Task(model.Model):
    ...
    def time(self, input):
        ...
        return value

模板中显示的表格显示了上述模型中的一些字段:

import django_tables2 as tables

class TaskTable(tables.Table):
    class Meta:
        fields = ('time',) 

如何将input视图函数中读取的变量传递给模型方法?

4

3 回答 3

1

让我们做以下假设

  • 模板名称:MyTemplate.html
  • 网址定义:url(r'^/some/url/defn/$', 'some_app.controller.handler'),
  • 名为 InputForm 的表单

我的模板.html

<form method='POST' action='.'> <!-- posts to self -->
   {% csrf_token %}
   <table>
   {% form.as_table %}
   </table>
   <input type="submit" value="Submit" />
</form>

表格.py

class InputForm(forms.Form):
    # ... other fields
    time = forms.CharField(max_length=25)

    def clean(self):
        """
        your form validations
        """
        cleaned_data = super(InputForm, self).clean()
        time = cleaned_data.get('time')
        # validate your times format here
        if not time_valid(time):  # you need to do your own validation here
            self._errors['time'] = self.error_class(['time is invalid!'])

        return cleaned_data  # always return the cleaned data! always :) 

控制器.py

from some_app.forms import InputForm
from some_app.models import Task


@csrf_protect
def handler(request):
    template_file = 'MyTemplate.html'
    template_info = {
      'form': InputForm()
    }
    if request.method = 'POST':
        form = InputForm(request.POST)
        template_info['form'] = form
        if form.is_valid():
            # retrieve your related model here
            task = Task.objects.filter(field='lookupvalue')
            # this makes huge assumptions, 
            # namely that your form validations ensure that the form data 
            # is in the proper format to go into the database
            task.phase(form.cleaned_data.get('time'))

            # save your model data
            task.save()
        else: 
            # spit out any warnings here? 
            pass
     return render(request, template_File, template_info)

现在将您的浏览器指向您http://your_dev_server:[port]/some/url/defn/将看到一个模板,该模板在完成后将处理一些表单验证(并以错误响应),如果成功则phase()针对任务对象调用您的方法!

于 2013-10-18T04:51:12.363 回答
0

现在您的任务模型对象可以访问阶段功能,因此您可以只使用

some_var = Task.phase(时间)

在视图中导入任务后,这里的任务对象充当自我,时间是发送时间

于 2013-10-18T04:51:01.920 回答
0

__init__对该对象的表使用了以下方法,以便能够以如下形式传递读取的参数TaskTable(tasks, dt=input_datetime)

import django_tables2 as tables

class TaskTable(tables.Table):

    def __init__(self, *args, **kwargs):
        if "dt" in kwargs: self.dt = kwargs.pop("dt")
        super(TaskTable, self).__init__(*args, **kwargs)

    class Meta:
        model = Task
        fields = ('time',)

    def render_time(self, value, record):
        if hasattr(self, "dt"):
            return record.time(input=self.dt)
        else:
            return value
于 2013-10-18T16:14:04.573 回答