我有一个Django模型,正在为其编写删除视图。我收到django.urls.exceptions.NoReverseMatch
错误。这也是合乎逻辑的,因为当我尝试调试并且想使用{{ model.id }}
输出我的ID时,我的视图完全没有显示ID。当我使用pk时,它将传入我的网址。
我的模特:
class UrlTrack(models.Model):
url = models.CharField(max_length=255, primary_key=True)
counter = models.BigIntegerField(default=0)
我的观点:
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')
我的网址:
path('history/delete/urls/<int:id>/', AnalyticsDeleteUrls.as_view(), name="history_url"),
我的模板:
{% 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 %}
这也是我的列表视图:
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
为什么ID不存在?我虽然django自动将它传递给了...?
我们非常感谢您的帮助。预先感谢
答案 0 :(得分:1)
我认为您实际上需要分两步进行。
首先,将id
添加到模型中,然后编辑创建的makemigrations
文件。您可以尝试将迁移文件修改为以下内容:
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),
]
然后再次编辑models.py,将UrlTrack
设为唯一,将id
设为主要,然后再次运行makemigrations