Skip to main content
 首页 » 编程设计

python之传递一个变量来显示一个django模型方法

2025年05月04日24zlslch

我有一个 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',)  

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

请您参考如下方法:

让我们做以下假设

  • 模板名称:MyTemplate.html
  • 网址定义:url(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> 

表单.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() 方法!