【问题标题】:Displaying the content on a different html based on the primary key根据主键在不同的 html 上显示内容
【发布时间】:2018-09-28 08:08:55
【问题描述】:

我正在使用 Django 创建一个站点。我有如下表调用通知 模型.py

class Notice(models.Model):
        Notice_No=models.AutoField(primary_key=True)
        Content=models.TextField(max_length=5000, help_text="Enter Owner Name")

我正在使用 for 循环在我的模板页面上将所有这些字段显示为 通知编号、内容、发布日期、到期日期。我已经提供了一个指向所有内容值的超链接,这些值将它带到另一个 HTML 播放中,并带有一个适当的 CHS 通知形式。现在我想做的是,如果我点击让我们说第 1 号通知的通知。我只想在下一页显示该通知的内容。如果我点击通知_no 2,它应该只显示该通知的内容。我是 python 新手,所以不知道该怎么做。我该怎么做? Notice.html 是显示表格的页面。 Noticesoc.html display 是应该显示内容的地方。

views.py

def notices(request):
    Notice_all=Notice.objects.all()[:50]
    return render(
        request,
        'notices.html',
        context={'Notice_all':Notice_all}
    )
def noticesoc(request):
    Notice_all=Notice.objects.all()
    return render(
        request,
        'noticesoc.html',
        context={'Notice_all':Notice_all}
    )

【问题讨论】:

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


    【解决方案1】:

    发送你想详细查看的数据的主键。

    <td style="color:white; font-family:helvetica; font-size:15px;">
                            <a class="nav-link" href="{% url 'noticesoc' Notice.pk %}">
                                Click here to view the contents</a>
                            </td>
    
    url( r'^noticesoc/(?P<pk>\d+)/$', 'noticesoc')
    

    然后在视图中。使用.get获取信息Notice,然后渲染。

    例如:

    def noticesoc(request, pk):
        Notice=Notice.objects.get(id=pk)
        return render(
            request,
            'noticesoc.html',
            context={'Notice_all':Notice}
        )
    

    【讨论】:

    • 这是我的 url.py 文件 urlpatterns = [ path('', views.index, name='index'), path('r^complaints',views.complaints, name='complaints '), path('r^notices',views.notices, name='notices'), path('r^maintenance',views.maintenance, name='maintenance'), path(r'^noticesoc/(? P\d+)/$',views.noticesoc, name='noticesoc'), path('r^registration',views.registration, name='registration'), ] 我在尝试你的时候遇到了这个错误方法-noticesoc() 得到了一个意外的关键字参数 'pk'
    • 更新了 sn-p。使用def noticesoc(request, pk):
    • 还是不行。错误=赋值前引用的局部变量“通知”。你能看看我的 url.py(previous comment) 是否正确
    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多