Django | add:在PK URL标记上

时间:2018-10-17 20:44:56

标签: django python-3.x django-models django-templates django-views

我正在尝试使用HTML模板中的| add:“ 1”获得下一个PK值。 我的问题是如何使它工作?例如,如果PK为1,则单击链接后应为2。查看代码。

模板

 <h3>
    <a href="{% url 'step' task_pk=step.task.pk step_pk=step_id|add:"1" %}">Next Step</a>
</h3>

模型

class Task(models.Model):
CATEGORIES = (
    ('tr', 'Traffic'),
    ('cr', 'Conversion Rate'),
    ('br', 'Bounce Rate'),
    ('ma', 'Marketing'),
    ('sc', 'Sales Channels'),
    ('cur', 'Customer Relations'),
)
title = models.CharField(max_length=100)
description = models.CharField(max_length=300)
category = models.CharField(max_length=100, choices=CATEGORIES)
created_at = models.DateTimeField(auto_now_add=True)
order = models.IntegerField(default=0)
id = models.AutoField(primary_key=True)

def __str__(self):
    return self.title


class Step(models.Model):
task = models.ForeignKey(Task, on_delete=models.CASCADE)
order = models.PositiveIntegerField(default=1)
title = models.CharField(max_length=100)
is_complete = models.BooleanField(default=False)
description = models.TextField()
id = models.AutoField(primary_key=True)

class Meta:
    ordering = ['order']
    unique_together = ("task", "order")

def __str__(self):
    return self.title

观看次数

def task_step(request, task_pk, step_pk):
step = get_object_or_404(Step, task_id=task_pk, pk=step_pk)
return render(request, 'totd/task_step.html', {'step': step})

网址

urlpatterns = [
re_path(r'(?P<task_pk>\d+)/(?P<step_pk>\d+)/$', views.task_step, name='step'),
]

1 个答案:

答案 0 :(得分:1)

将next_step ID作为上下文的一部分传递可能会更容易。这样,您可以先检查该值是否存在于数据库中,并且在渲染模板时不会出现ReverseMatch错误。

def task_step(request, task_pk, step_pk):
    step = get_object_or_404(Step, task_id=task_pk, pk=step_pk)
    next_step_pk = step_pk + 1

    # Use a filter operation so if there is no item with this pk it won't fail but will return an empty queryset
    next_step = Step.objects.filter(pk=next_step_pk)
    # Check the next step pk has a DB entry and set it to None if it doesn't exist
    if next_step.count() == 0:
        next_step_pk = None
    return render(request, 'totd/task_step.html', {'step': step,
                                                   'next_step_pk': next_step_pk})

然后,您将可以在模板中访问此上下文,并且仅当链接存在时才可以呈现该链接。

{% if next_step_pk %}
     <h3>
        <a href="{% url 'step' task_pk=step.task.pk step_pk=next_step_pk %}">Next Step</a>
    </h3>
{% endif %}