Передача переменной для отображения метода модели django

У меня есть модель 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 ответа

Давайте сделаем следующие предположения

  • Шаблон с именем: MyTemplate.html
  • Определение URL: 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>

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() метод против объекта задачи!

Теперь ваш объект модели Task может получить доступ к фазовой функции, поэтому вы можете использовать только

some_var = Task.phase(time)

после импорта Задачи в представлениях, здесь объект Задачи действует как сам, а время отправляется на время

Я использовал следующее __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
Другие вопросы по тегам