【问题标题】:How can I create a new url in a Django app?如何在 Django 应用程序中创建新的 url?
【发布时间】:2016-09-24 13:29:05
【问题描述】:

我已经在 Django 应用程序中实现了一个模型,我想添加一个 url 来处理这个模型的视图。

class Post(models.Model):
     author = models.ForeignKey('auth.User')
     title = models.CharField(max_length=200)
     text = models.TextField()
     created_date = models.DateTimeField(default=timezone.now)
     published_date = models.DateTimeField(blank=True, null=True)

你能帮帮我吗?

【问题讨论】:

  • 我建议您在做任何其他事情之前至少阅读本教程:docs.djangoproject.com/en/1.10/intro/tutorial01。在这一点上,向您展示如何编写 url 模式对您没有任何好处。
  • @Fabi G 您的问题含糊不清。请更新它以提出更具体的问题,而不仅仅是“你能帮我吗?”。

标签: python django url view


【解决方案1】:

我也会推荐 Django 教程:https://docs.djangoproject.com/en/1.10/intro/tutorial01/

但是,要回答您的问题,您可以进行如下设置:

views.py:

from django.shortcuts import render
from .models import Post

def my_view(request):
    posts = Post.objects.all()
    return render(request, 'template.html', {'posts': posts})

urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.my_view, name='my_view')
]

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 2018-12-11
    • 2010-09-09
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多