Home > Mobile >  Passing data from a form to a view Django
Passing data from a form to a view Django

Time:12-13

I have two functions in views.py, the first one allows you to display information from tables. The second is to get data from the form and redirect to the page with the result. How can I pass the data received from the form to the first function to display information from the tables based on this very data?

In the first function:

def SuOp(request): 
    allrooms = Rooms.objects.all()
    allfood = Food.objects.all()
    alltours = Tours.objects.all()  
    
    data = {   
    'allfood': allfood, 
    'allrooms': allrooms,
    'alltours': alltours,
    }

    return render(request, './obj.html', data)

in the second function:

def Main(request):
    error = ''
    if request.method == 'POST':
        form = SearchMain(request.POST)
        if form.is_valid():
              budget = form.cleaned_data.get("budget") 
              arrival_date = form.cleaned_data.get("arrival_date") 
              departure_date = form.cleaned_data.get("departure_date") 
              number_of_people = form.cleaned_data.get("number_of_people")
              count_days = (departure_date-arrival_date).days 
              return redirect('allobject')

        else:
              error = 'The form has been filled out incorrectly'

    form SearchMain()

    data = {
        'formS': form,
        'error': error,
    }

    return render(request, './main.html', data)

urls.py:

urlpatterns = [
    path('', views.Main, name='main'),
    path(r'allobject/$', views.SuOp, name='allobject')
]

CodePudding user response:

You can use sessions to pass values from one view to another. First set the session:

if form.is_valid():
    budget = form.cleaned_data.get("budget")
    request.session['budget'] = budget
    ...
    return redirect('allobject')

Then your other view can get the session variable:

def SuOp(request):

    budget = request.session.get('budget')
    ...

    allrooms = Rooms.objects.all()
    allfood = Food.objects.all()
    alltours = Tours.objects.all()  
    
    data = {   
    'allfood': allfood, 
    'allrooms': allrooms,
    'alltours': alltours,
    }

    return render(request, './obj.html', data)

The other option is to do all the calculations in the view that receives the budget, arrival_date, departure_date, number_of_people, save the desired results to the Rooms, Food and Tours objects.

  • Related