这是我第一次使用 mySQL 和 django,从服务器获取内容并将其显示在网页上时遇到一些问题。 这是我的代码: 这是index.html
{% extends 'test/layout.html' %}
{% block content %}
<hr>
<br>
<h1 class="container center-align">{{title}}</h1>
<br>
<h3 class="center-align blue lighten-3">Webpages</h3>
<ul class="collection">
{% for homes in homes %}
<li class="collection-item"><a href="test/details.html">{{homes.title}}</a></li>
{% endfor %}
</ul>
{% endblock %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Home
def index(request):
homes = Home.objects.all()[:10]
context = {
'title': 'All Home',
'homes': homes
}
return render(request, 'test/index.html', context)
def details(request, id):
home = Home.objects.get(id=id)
context = {
'Home': home
}
return render(request, 'test/details.html', context)
url.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'', views.index, name='index'),
url(r'details/(?P<id>\d+)/', views.details, name='details')
]
模型.py
from django.db import models
from datetime import datetime
class Home(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
created_at = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "Home"
详细信息.html
{% extends 'test/layout.html' %}
{% block content %}
<hr>
<br>
<h1 class="container center-align">{{home.title}}</h1>
<br>
<div class="card">
<div class="card-content">
{{home.body}}
</div>
<div class="card-action">
{{created_at}}
</div>
</div>
<a href="/test" class="btn">Go Back</a>
{% endblock %}
问题是,当我单击网页上的链接时,带有服务器文本的details.html 文件不显示。相反,主页显示(index.html),但现在在不同的网址下。(主页上的正常网址:localhost:8000,新网址:localhost:8000/test/details.html) 我认为问题出在 urls.py 文件中,但我不确定。 希望大家能够帮忙。
编辑: 我的文件夹
testdjango
|
|--testdjango(all the normal project files are in here)
|--test
| |--__pycache__
| |--migrations
| |--templates
| | |--test
| | |--detalils.html
| | |--index.html
| | |--layout.html
| |
| |--__init__.py
| |--admin.py
| |--apps.py
| |--models.py
| |--tests.py
| |--urls.py
| |--views.py
|
|--db.sqlite3
|-- manage.py
最佳答案
您的代码存在一些问题。
我会挑选我第一眼看到的。
将命名空间添加到您的urls.py
文件
from django.conf.urls import url
from . import views
app_name = 'something_meaningful'
urlpatterns = [
url(r'', views.index, name='index'),
url(r'details/(?P<id>\d+)/', views.details, name='details')
]
然后尝试对网址进行硬编码(您也以错误的方式进行了操作)。
<li class="collection-item">
<a href="{% url 'something_meaningful: details' id=home.id %}">{{ home.title }}</a>
</li>
对于伟大的上帝,不要对序列和迭代器实例使用相同的变量名。
{% for home in homes %}
# ul>li block above
{% endfor %}
此外,您应该更好地更改 details
函数,如下所示(pk 更通用)。
def details(request, id=None):
home = Home.objects.get(pk=id)
context = {
'Home': home
}
return render(request, 'test/details.html', context)
完成这些更改后,请提供反馈。
关于python - 通过 django 从 mySQL 服务器获取内容到网页时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50864602/