Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

templates - Django: How to link a client-side component with a server-side information

I know the title is maybe confusing, but let me clarify my problem.

I have an Animal model with simply a name field in it. In my HTML template, I list each instance of Animal in an a element (display order may vary).

view.py:

def index(request):
    animals = Animal.objects.all()
    return render(request, 'index.html', {'animals': animals})

index.html:

{% for animal in animals %}
  <a>animal.name</a>
{% endfor %}

Output is something like this:

  • Cow
  • Duck
  • Horse
  • Cat
  • Bee

My question is, when the user clicks on an animal, I have to perform certain actions in the database. But how can I know which animal did he click ? I don't want to get the client-side text with javascript, because this is not secure and the user can change it by inspecting the element.

I simplified my problem with animals, but in reality it is more complicated than this and I really need to find a secure way to get the correct clicked animal, even if the user changed the text or the HTML class or ID or something like this.

Edit: I don't want either to use any other method that allows the user to change html from his browser

question from:https://stackoverflow.com/questions/65672120/django-how-to-link-a-client-side-component-with-a-server-side-information

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you are already using anchor links, you can for example do something like this:

{% for animal in animals %}
  <a href="{% url 'animal:detail' animal.pk %}">{{ animal.name }}</a>
{% endfor %}

or with a hard coded url like this (not best practice, use the above if you can):

{% for animal in animals %}
  <a href="/animals/detail/{{ animal.pk }}/">{{ animal.name }}</a>
{% endfor %}

Then you can have a url pattern like /animals/detail/<int:pk>/ that maps to the href target linked above. Now, when a user clicks that link, they call the view behind that url. In this resulting view, you have the pk of the animal available and can now retrieve it from the database.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...