[Django]-Is there a better way to check if the values of an AJAX request are valid?

0👍

If you’re not opposed to using a framework Marshmallow will handle serialization and deserialization for you, it is super easy to define custom validation beyond simple type checking, and it’s gorgeous. Tom Christie has even wrapped it up for use with Django.

Edit:
If you choose to use it your code would look more like this:

from rest_marshmallow import Schema, fields

class FeedSchema(Schema):
    last_id = fields.Integer()
    feed_type = fields.String()

@ajax_required
def poll(request):
    try:
        # Validate request
        serializer = FeedSchema(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        # Return posts
        if data['feed_type'] == 'following' and request.user.is_authenticated():
            posts = Post.get_posts(user=request.user, after_id=data['last_id'])
            return JsonResponse({
                'html': render_to_string('posts/raw_posts.html', {'posts': posts}),
                'count': posts.count()
            })
        # The user isn't authenticated or they requested a feed type they don't have access to.
        return HttpResponseForbidden()
    except ValidationError as err:
        return HttpResponseBadRequest(err.messages)

Leave a comment