简体   繁体   中英

How can I get values from a view in Django every time I access the home page

I currently have the following view created in Django:

@login_required
def retrieve_from_db(request):
  some_ids = get_some_data()
  context = {'some_ids': some_ids}
  return render(request, 'index.html', context)

This is my urls.py:

from django.urls import path
from . import views

app_name = 'blabla'

urlpatterns = [
   path('', views.another_view, name='index'),
   path('', views.retrieve_from_db, name='index'),
   ...
   ...
   ...
]

And this is part of my index.html

<div>
  <select name="myIdList" id="myIdList">
  {% for some_id in some_ids %}
      <option value="{{ some_id }}">{{ some_id }}</option>
  {% endfor %}
  </select>
</div>

I would like to know how can I get the results from the function retrieve_from_db() . What I want is that every time I access the home page, by default the selects are populated with the result of the view.

All I have found so far on StackOverflow have been answers using forms in which the user somehow has to perform some action to trigger the POST, is there any way to do all of this without the user having to press any buttons or perform an action? simply every time the page loads, get the results of the retrieve_from_db() function defined in the view.

You can use "GET" method which is not safe for passing sensitive data! GET should send data while rendering page.

Your views.py function to retrieve data would look like this:

 @login_required
  def retrieve_from_db(request, some_id):
  if request.method == "GET":
      some_ids = request.GET.get('some_id')
      context = {'some_ids': some_ids}
      return render(request, 'index.html', context)

Your HTML would look like this:

  <div>
  <form action="/retrieve_from_db/{{some_id}}" method="GET">
  <select name="myIdList" id="myIdList">
  {% for some_id in some_ids %}
      <option value="{{ some_id }}">{{ some_id }}</option>
  {% endfor %}
  </select>
</div>

Interesting part here is, how it will pass many 'some_id' objects as you generate them from for loop.

This solution maybe is not one of the most elegant ones, but should pass data without user interference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM