如何按计划在django提交表单?

时间:2019-04-25 14:24:50

标签: python django

我有一个典型的表单,用户可以在其中输入自己的值,提交表单并在表中查看结果:

class ScanForm(form.ModelForm):
""" Creating a form for Scan results """
    value = forms.DecimalField(widget=forms.NumberInput(
        attrs={
            'class': 'form-control',
            'placeholder': 'Value',
            'max': '500',
        }
    ))
    count = forms.DecimalField(widget=forms.NumberInput(
        attrs={
            'class': 'form-control',
            'placeholder': 'Amount',
            'max': '400',
            }
    ))
    class Meta:
    """ Adding choice of interval and exclude unused fields """
        model = ScannedValue
        exclude = ('scan_date',)
        widgets = {
            'interval': forms.Select(
                attrs={
                    'class': 'form-control',
                }),
        }

我照常在我的index.html文件中渲染该表单。 当我放入所有数据并按“提交”按钮时,它正常工作。

但是我需要的是自动填写此表格,并在特定时间(例如每天01:00 pm)填写数值(假设'value'= 5,'count'= 10) 。然后,在提交表单之后,我需要在视图中解析所有接收到的具有功能的数据,然后将结果保存到数据库中。最佳和最正确的方法是什么?

这是views.py中的功能:

def scans(request): 
    form = ScanForm(request.POST or None) 
    if request.method == 'POST': 
        if form.is_valid(): 
            def fetch_scan(interval='1', amount=10, value=5): 
                # doing_some_stuff
else: 
form = ScanForm()

所以我只想每天在特定时间自动使用参数启动fetch_scan()。

1 个答案:

答案 0 :(得分:1)

您不需要为用例提交表单。您需要在视图外部定义fetch_scan,然后将其转换为芹菜任务。然后,它可以作为定期任务运行。

@app.task()  # convert to celery task
def fetch_scan(interval='1', amount=10, value=5): 
       # doing_some_stuff

def scans(request): 
    form = ScanForm(request.POST or None) 
    if request.method == 'POST': 
        if form.is_valid(): 
            fetch_scan()  # call the function
    else: 
      form = ScanForm()

然后,您每天都可以运行fetch_scan任务。

#settings.py

from celery.schedules import crontab
CELERYBEAT_SCHEDULE = {
    'daily-scan': {
        'task': 'path.to.fetch_scan',
        'schedule': crontab(hour=13),  #run daily at 1 pm
    },
}

docs