1

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.

1 Answer 1

2

I seem to have found a solution though perhaps not ideal.

Here is the view:

class GenerateRosterViewSet(viewsets.ViewSet):
    """GenerateRosterView."""

    def list(self, request):
        """Get page."""
        data = {"date": "required"}
        return Response(data, status=status.HTTP_200_OK)

    def create(self, request):
        """Generate roster with given start date."""
        serializer = DateTimeSerializer(data=request.data)
        if serializer.is_valid():
            date = serializer.validated_data["date"]
            result = generate_roster.delay(start_date=date)
            data = {"task": result.task_id}
            return Response(data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def retrieve(self, request, pk=None):
        """Not used."""
        pass

    def update(self, request, pk=None):
        """Not used."""
        pass

    def partial_update(self, request, pk=None):
        """Not used."""
        pass

    def destroy(self, request, pk=None):
        """Not used."""
        pass

Here is the serializer:

class DateTimeSerializer(serializers.Serializer):
    """DateTime Serializer."""

    date = serializers.DateTimeField()

    def create(self, validated_data):
        """Create date."""
        return datetime(**validated_data)

    def update(self, instance, validated_data):
        """Update date."""
        instance.date = validated_data.get("date", instance.date)
        return instance
Sign up to request clarification or add additional context in comments.

1 Comment

I had a similiar question if you can please help stackoverflow.com/questions/69931199/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.