How to limit form submit request in Django app

Viewed 27

I want to limit submitting request for visitors(anonymous) in my django app.

Suppose 10 or 50 limits per day/month. If they try to search more than my given limit I want to show a message "you have reached your daily or monthly limit!"

How can I do this?

Here is views:

def homeview(request):
    if request.method == "POST" and 'text1' in request.POST:
        text1 = request.POST.get('text1')
        text2 = request.POST.get('text2')
        data = my_custom_function(text1, text2)
        context = {'data': data}
    else:
        context = {}
    return render(request, 'home.html', context)

here is form in template:

<form action="" method="POST">
    {% csrf_token %}
    <input class="form-control m-3 w-50 mx-auto" type="text" name="text1" id="text1" placeholder="">
    <input class="form-control m-3 w-50 mx-auto" type="text" name="text2" id="text2" placeholder="">
    <input class="btn btn-primary btn-lg my-3" type="submit" value="Submit">
</form>
1 Answers

You can use throttling from the Django REST framework. But there is no throttle rate for a month out of the box. Maybe you can use https://stackoverflow.com/a/50371440/4151233 to create a specific class.

Otherwise, I recommend writing your own implementation. This should be adapted to the requirements with questions such as:

  • Are my users authenticated when making the requests?
  • How fast should it be and how much load is expected?
  • Is a standard DB query acceptable or does it need to be implemented with the cache framework?
Related