Search code examples
pythondjangodjango-filter

Returning a filter result in a different page - Django


I've searched up but nothing seams to do the trick or be on point.

Let's say i have two websites on page A.html I have a filter (djnago_filter) and B.html is empty. If the user submits the search form he is redirected from page A.html to page B.html where the results are displayed with for loop.

How do I to that?

I was thinking about passing the data from query set to another view but there must be better solution to this.


Solution

  • There are several ways to store and display information on the different views(pages):

    1. You could use the Sessions:
        #views.py
    
        #set the session key in the view A:
        request.session['info'] = {'key', 'value'}
        
        #get the session key in the view B:
        info = request.session['info']
        del request.session['info']
    
    1. You could use Models with JSONField:
        #app/models.py
    
        #model to store information from page A
        from django.contrib.auth.models import User
        class MyModel(models.Model):
            user = models.ForeignKey(User,
                on_delete=models.DELETE,
                related_name="info")
            info = models.JSONField()
    
        #views.py
        #store data in the view A:
        from app.models import MyModel
        MyModel.objects.create(user=request.user, info={'key', 'value'})
        
        #retrieve data in the view B:
        info = MyModel.objects.get(user=request.user)
    

    But actually, all depends on the logic that you intent to achieve. There are actually other methods like using async Ajax, React, WebSockets...