Reputation: 1689
I have a django model for which I am writing my delete view. I get an django.urls.exceptions.NoReverseMatch
error. That is also logical since when I am trying to debug and I want to output my id with {{ model.id }}
my view shows me no id at all. When I use the pk it passes in my urls.
My model:
class UrlTrack(models.Model):
url = models.CharField(max_length=255, primary_key=True)
counter = models.BigIntegerField(default=0)
My view:
class AnalyticsDeleteUrls(SingleObjectMixin, View):
model = UrlTrack
def get(self, request, *args, **kwargs):
obj = self.get_object()
if obj is not None:
obj.delete()
return redirect('list_history')
My urls:
path('history/delete/urls/<int:id>/', AnalyticsDeleteUrls.as_view(), name="history_url"),
My template:
{% for item in url_tracks %}
<tr>
<td>{{ item.url }}</td>
<td>{{ item.counter }}</td>
<td> <a class="btn btn-danger" href="{% url 'history_url' item.id %}"> Delete </a>
</tr>
{% endfor %}
Here also my list view:
class AnalyticsIndexView(StaffRequiredMixin, ListView):
template_name = 'analytics_list.html'
model = UrlTrack
context_object_name = 'url_tracks'
queryset = UrlTrack.objects.all()
def get_context_data(self, **kwargs):
context = super(AnalyticsIndexView, self).get_context_data(**kwargs)
context['object_viewed_list'] = ObjectViewed.objects.all()
return context
Why would the id be non existent? I though django passes that in automatically....?
Any help is highly appreciated. Thanks in advance
Upvotes: 0
Views: 100
Reputation: 5793
I think you'll actually need to do it in two steps.
First, add id
to the model, then edit the makemigrations
file created. You could try modifying your migrations file to something like this:
from __future__ import unicode_literals
from django.db import migrations, models
def set_id(apps, schema_editor):
UrlTrack = apps.get_model('app_name', 'urltrack')
count = 1
for row in UrlTrack.objects.all():
row.id = count
count += 1
row.save()
class Migration(migrations.Migration):
dependencies = [
('app_name', '0001_previous_migration_name'),
]
operations = [
migrations.AddField(
model_name='urltrack',
name='id',
field=models.IntegerField(),
),
migrations.RunPython(set_id),
]
Then edit models.py again and make UrlTrack
unique and id
primary and run makemigrations
again
Upvotes: 1