0

I need to make a process inside my django application that just after the application starts, it will randomly take one record from Products table (which contains f.e. name, price and rating) and set it into another table named SingleProduct.

The process should run inside infinite loop and replace the single product inside SingleProduct table every 15 minutes.

How can I do stuff like this? What should I looking for?

What do I need it for? I want to display some random product from the database on my home page every 15 minutes.

1 Answers1

-1

You can use Ajax for this.

Here is an Example:

In your template: Import JQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Then at the bottom you can do something like this

{% block script %}
  <script type="text/javascript">
    const interval = setInterval(function() {
    // If you wish to refresh the page after calling the function
    // uncomment the line below
    // location.reload();
      $.ajax({
        type: "GET",
        url: '{% url 'homepage' %}',
        success: function() {
          console.log('{{randomint}}')
        }
      });
    }, 1000) // this is in milisenconds, 1000 = 1sec
  </script>
{% endblock %}

This will call the url "'homepage'" every second,

url:

path('', views.homepage, name='homepage'),

view:

def homepage(request):
    template = loader.get_template('jsondata.html')
    #
    # put your code here
    #
    randomint = randint(1, 100) # this is just for example purposes
    context = {
        'randomint': randomint,
    }

    return HttpResponse(template.render(context, request))

Note: This is just an example and will not work out of the box...

Hope this somewhat answers your question.

Extra info: Django URL in Ajax

Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
Tim-Bolhoeve
  • 189
  • 7
  • Sorry, maybe I wrote it wrong. I know that I can do this on the client side and send every 15 min request to server to get a new random product, but I need to do this on server side because I want to have every user the same random product. – some nooby questions Aug 31 '22 at 14:32
  • @somenoobyquestions ahh... sorry, then i cant help you.. – Tim-Bolhoeve Sep 01 '22 at 06:44
  • @somenoobyquestions maybe [this stackoverflow link](https://stackoverflow.com/questions/57434641/how-to-loop-a-function-to-perform-a-task-every-15-minutes-on-the-0-15-30-45-min) or [this documentation](https://pypi.org/project/python-crontab/) can be of help – Tim-Bolhoeve Sep 01 '22 at 07:19