我试图对我的超链接进行打点。我创建了Django面板(home.html):
目前,我有:
http://127.0.0.1:8000/request/2/
但是我想要:http://127.0.0.1:8000/request/hallo-das-ist-ein-test-9/
{% for topic in topics %}
<tr>
<td>{{ topic.slug }}</td>
<td><a href="{% url 'topic_posts' topic.pk %}">{{ topic.subject }}</a></td>
<td>{{ topic.starter.username }}</td>
<td>0</td>
<td>0</td>
<td>{{ topic.last_updated }}</td>
</tr>
{% endfor %}
和
class Topic(models.Model):
subject = models.CharField(max_length=255)
category = models.CharField(max_length=255, null=True)
last_updated = models.DateTimeField(auto_now_add=True)
starter = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='topics')
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.subject)
super(Topic, self).save(*args, **kwargs)
您可以看到,子弹已创建。 (第一列= {{topic.slug}})
如何创建条形链接并将其链接到我的线程超链接? (例如“ hallo das ist ein test:9”)
我当前在views.py中的代码:
def home(request):
topics = Topic.objects.all()
return render(request, 'home.html', {'topics': topics})
def topic_posts(request, topic_pk):
topic = get_object_or_404(Topic, pk=topic_pk)
return render(request, 'topic_posts.html', {'topic': topic})
我当前的url.py:
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
url(r'^new/$', views.new_topic, name='new_topic'),
url(r'^request/(?P<topic_pk>\d+)/$', views.topic_posts,
name='topic_posts'),
url(r'^request/(?P<topic_pk>\d+)/reply/$', views.reply_topic,
name='reply_topic'),
]
我已经尝试过不同的方法,例如:
def home(request):
topics = Topic.objects.all()
slug = Topic.slug
return render(request, 'home.html', {'topics': topics, 'slug': slug})
def topic_posts(request, slug):
slug = get_object_or_404(Topic, pk=slug)
return render(request, 'topic_posts.html', {'slug': slug})
home.html:
<td><a href="{% url 'topic_posts' topic.slug %}">{{ topic.subject }}</a></td>
url.py:
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
url(r'^new/$', views.new_topic, name='new_topic'),
url(r'^request/(?P<slug>[-\w\d]+)/$', views.topic_posts,
name='topic_posts'),
url(r'^request/(?P<topic_pk>\d+)/reply/$', views.reply_topic,
name='reply_topic'),
]
我在这里做错了什么...?
答案 0 :(得分:0)
您的预期行为需要进行一些更改。
在表更改中:
<a href="{% url 'topic_posts' topic.pk %}">
到
<a href="{% url 'topic_posts' slug=topic.slug %}">
在视图中,像这样更新代码:
def topic_posts(request, slug):
topic = get_object_or_404(Topic, slug=slug)
...