简体   繁体   中英

how to get values from views.py and use it in html template?

I'm making a Map where users can log in and assign default start and end points. I am very new to Django and html, now I am stuck on not knowing how to pass variable values into html.

this is my views.py

def maps(request):
    username = password = ''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username = username, password = password)

        if user is not None:
            if user.is_active:

                login(request, user)

                traffic_start = Auth.objects.get(user = user).traffic_start
                traffic_end = Auth.objects.get(user = user).traffic_end

    return render_to_response('maps.html')

and i'm trying to use the values in the html file here

function calcRoute(){
    var start = document.getElementById('start').value;
    var end = document.getElementById('end').value;
    var request = {
      origin: start,
      destination: end,
      travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(response, status){
      if(status == google.maps.DirectionsStatus.OK){
        directionsDisplay.setDirections(response);
      }
    });
  }
  google.maps.event.addDomListener(window, 'load', initialize);

I tried looking for similar threads but I am still unable to figure it out, please help me, much appreciated!!

render_to_response has an optional argument that you can use just for that, it's called context. It has to be a dictionary.

render_to_response('maps.html', {'name': username})

You can use the value of username in your template with {{ name }} .
Check the Django Tutorial for a sophisticated example project.

You can also pass objects this way:

Models.py

class Profiles(models.Model):
    id = models.IntegerField()
    first_name = models.CharField(max_length=45, blank=False)
    surname = models.CharField(max_length=45, blank=False)

Then reference this object in views.py and pass it to your template as @Tim Zimmermann mentioned

Views.py

profiles = Profiles.objects.all;
render_to_response('template.html', {'profiles': profiles })

You can then loop through them in your template:

template.html

{% for profile in profiles %}
      <p>{{ profile.first_name }}</p>
      <p>{{ profile.surname }}</p>
{% endfor %}

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