Reputation: 1
I have a typical form where users can put their values, submit the form and see the results in table:
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',
}),
}
I'm rendering that form in my index.html file as usual. And it's working normally when I put all the data and pushing "Submit" button.
But what I need is to automatically submit this form with filled values (let's say for 'value' = 5, 'count' = 10) at certain time, let's say 01:00pm every day. Then I need to parse all received data with function in my views after submitting the form and then save the results to database. What is the best and most right way to do this?
Here's function in 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()
So I only want to launch function fetch_scan() automatically at certain time with my arguments every day.
Upvotes: 0
Views: 414
Reputation: 2547
You don't need to submit forms for your use case. You need define the fetch_scan
outside the view, and then convert it into a celery task. Then, it can be run as a periodic task.
@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()
Then you can just run the fetch_scan
task everyday.
#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
},
}
Upvotes: 1