I have a fully functioning Django application and I am now adding an API using Django Rest Framework. I will creating a React front end which will use the API provided via DRF. I have worked out how to use DRF to create endpoints for my models using ModelViewSets and ModelSerializers. These work fine. I now need to create an endpoint that initiates some data processing. The endpoint will need to accept a date as input and then call some code to do the processing. My standard Django application currently does this by accepting a date via a Django form and then initiating a celery task.
Here is the view:
class GenerateRosterView(LoginRequiredMixin, FormView):
"""Generate Roster View."""
template_name = "generate_roster.html"
form_class = GenerateRosterForm
def get_form_kwargs(self):
"""Pass request to form."""
kwargs = super().get_form_kwargs()
kwargs.update(request=self.request)
return kwargs
def get_success_url(self):
"""Get success URL."""
return reverse("roster_generation_status", args=(self.task_id,))
def form_valid(self, form):
"""Process generate roster form."""
start_date = form.cleaned_data["start_date"]
self.request.session["start_date"] = start_date.date().strftime(
"%d-%b-%Y"
)
result = generate_roster.delay(start_date=start_date)
self.task_id = result.task_id
return super().form_valid(form)
Here is the form:
class GenerateRosterForm(forms.Form):
"""Generate Roster Form."""
def __init__(self, request, *args, **kwargs):
"""Get default start date from session."""
super().__init__(*args, **kwargs)
if "start_date" in request.session:
start_date = datetime.datetime.strptime(
request.session["start_date"], "%d-%b-%Y"
)
else:
start_date = datetime.datetime.now()
self.fields["start_date"] = forms.DateTimeField(
widget=DateInput(), initial=start_date
)
What would be the equivalent to this using Django Rest Framework? I want my front end to be able to post a date to the endpoint which will then call the code I have written (Celery task) to process the data in the database. The result of the processing is stored in the database.