0

How can I pass value from django templates to views.py?? I have written Index.html having view function index() now I have created another view function places() in which I need to pass the value of p tag from Index.html file. It doesn't include any POST or GET method.

Index.html

{% block content %}
<div >
        {% for key,values in image_data.items  %} 
                <div class="divtag">
                <!-- {{key}} -->
                    <a href="Places" class="tag" >
                        <img src="{{values}}"/>
                        <div class="middle">
                            <p class="center" data={{key}}>{{key}}</p>
                        </div>
                    </a>
                </div>
        {% endfor %}
</div>
{% endblock %}

Views.py

#main index view
def index(request):
img = MyModel.objects.all()
template = loader.get_template('Index.html')
image_data = {}
for obj in img:

    image_data[obj.image_name] = obj.image

print("-----------------------------------------------------------------")
return render(request,'Index.html',{"image_data" : image_data})

 # where i need to return value from template
def places(request):
name = 'Paris'  #i want name value from p tag in html file
if(name == 'Paris'):

    img = Paris.objects.all()
    template = loader.get_template('Index.html')
    image_data = {
        'images' : [obj.image for obj in img],
        'name' : [obj.image_name for obj in img],
        'description' : [obj.image_description for obj in img]
    }
    image_data_zip = zip([obj.image for obj in img],[obj.image_name for obj in img],[obj.image_description for obj in img])   
    print("-----------------------------------------------------------------")
    return render(request,'Paris.html',{"image_data_zip" : image_data_zip})
else:

    img = Germany.objects.all()
    template = loader.get_template('Index.html')
    image_data = {
        'images' : [obj.image for obj in img],
        'name' : [obj.image_name for obj in img],
        'description' : [obj.image_description for obj in img]
    }
    image_data_zip = zip([obj.image for obj in img],[obj.image_name for obj in img],[obj.image_description for obj in img])   
    print("-----------------------------------------------------------------")
    return render(request,'Germany.html',{"image_data_zip" : image_data_zip})

1 Answers1

0

Sending data from Back-End to Front-End is context in django.

Sending data from Front-End to Back-End is Ajax and it's not a django concept.

Here's a reference to use ajax with jQuery. Without jQuery, Search for axios

e.g

$.ajax({
    url: 'myserver/getID', // no domain needed. careful with CORS (search about it)
    type: 'GET',
    data: // don't specify this, we're not posting any data,
    success: function (response) {console.log(response.data)}, 
    // response will be what returned from python
    error: function (error){console.log(error)}
})
Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30