传递变量以显示django模型方法

时间:2013-10-18 01:49:30

标签: python django django-tables2

我有一个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传递给模型方法?

3 个答案:

答案 0 :(得分:1)

让我们做出以下假设

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

MyTemplate.html

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

forms.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 :) 

controller.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()方法来完成任务宾语!

答案 1 :(得分:0)

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

some_var = Task.phase(时间)

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

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