0

I have developed a project with Django. But I want each user IP to be able to post request for 2 minutes to prevent spam. How can I achieve this? Do you have a suggestion?

Elfo
  • 117
  • 1
  • 8
  • Maybe this [question](https://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django) is helpful in getting the IP address in Django, check it out. – Gealber Jul 11 '21 at 13:45

1 Answers1

0

Along with Gealber's link in his comment, you can probably create a model which saves a history of post requests along with IP's. Something like this in models.py-

class PostRequestLog(models.Model):
    ip = models.CharField(max_length=30)
    latestRequest = models.TimeField(auto_now=False, auto_now_add=False)

    def get_latest_request(self):
        return self.latestRequest
    def set_latest_request(self, latestRequest):
        self.latestRequest = latestRequest 

in views.py, have something like-

from models import PostRequestLog
from django.shortcuts import redirect, render
import datetime

def home_page(request):
    ip = get_client_ip(request)
    object = PostRequestLog.objects.get(ip__iexact=ip)
    time = datetime.now()
    if object:
        latestRequest = object.get_latest_request()
        if time - latestRequest < threshold:
            return redirect('home') # or whatever you want to do to direct away
        else:
            object.set_latest_request(time)
    else:
        newObject = PostRequestLog.objects.create(ip=ip, latestRequest=time)
        newObject.save()
    # process POST

There is probably a decent amount missing or wrong in the code above, but generally the idea should work. If you are trying to not allow the user to access a webpage at all (where the form is), then you can probably make the above function into a wrapper which does the same check. Use it to wrap whatever functions in views.py which renders your page with the form. If the threshold is not met, then it does not redirect to the page with the form.

sbriley
  • 36
  • 5