1

I am new to django. I have made a table cell clickable but when i click that cell, nothing happens.

template :

 {% for each in object_list %}
   <tr>                  
   <td id="{{ each.id }}"   data-href="http://127.0.0.1:8000/{{ each.region }}/{{ each.id }}"></td>
   </tr>
 {% endfor %}

needed part of view:

class MeterDetailView(DetailView):
       model = Meter
       template_name = 'meter/specificMeter.html'

       def get_context_data(self, **kwargs):
          pk = kwargs.get('pk',None)
          obj = Meter.objects.get(pk=pk)

url :

    path('<int:region>/<int:pk>/', views.MeterDetailView.as_view(), name='detail')

model :

class Meter(models.Model):
   region   = models.PositiveSmallIntegerField()
   UserId   = models.BigIntegerField(default=0,null=False)

what is wrong?Thank you all.

quqa123
  • 605
  • 6
  • 15
sonia
  • 25
  • 4

3 Answers3

0

to make the cell that redirects after it's clicked you can use onclick attribute. In your case we would have to change the code a bit:

 {% for each in object_list %}
   <tr>                  
       <td id="{{ each.id }}" onclick="window.location='http://127.0.0.1:8000/{{ each.region }}/{{ each.id}}'"></td>
   </tr>
 {% endfor %}

similar approaches can be found in this question

quqa123
  • 605
  • 6
  • 15
  • please upvote the answer if it was helpful to you so others see is as a valid solution if they have similar problem :) – quqa123 Oct 23 '20 at 09:16
0

Like it's already explained in the comments under your question, data-href is just a variant of the dataset HTML property. You can read about it more here: dataset

The easiest approach: insert all your cell data inside <a href="link"></a> tag. This question's selected answer can tell you more.

It's also possible to do with data-href by adding an onclick event to your code:

<td id="{{ each.id }}" data-href="{% url 'detail' each.region each.id %}" onclick="makeCellClickable()" class="some-class></td>

Notice that I've put an url tag instead of a direct link as a data-href.

Other that that, you need to specify makeCellClickable() function in your linked js file or in html file within <script></script> tag. Don't forget to add a class like some-class to your stylesheet that would change background, cursor or however you want to show users that cell is clickable.

function makeCellClickable() {
    window.location = this.event.target.dataset.href
}
0

if you want to specify url you should use as folows:

urls.py

urlpatterns = [ 
path('admin/', admin.site.urls),
path('',YourView, name='UseForSpecifyUrl'),]

.html

<div class="col-6 text-right">
<a href="{% url 'UseForSpecifyUrl' %}" class="text-primary"><small>Do something</small></a>
</div>
Ayse
  • 576
  • 4
  • 13