我有两个应用程序为posts和home。如何在我的home应用程序中调用我的posts应用程序中的功能之一。这样,所有信息都将显示在我的home.html页面上。
我想要一种发布帖子的方法,请在home.html页面上查看发布列表。我不想去另一个网址,我想将网址保留在/ home /
home / views.py
from posts import views
from posts.models import Post
from posts.views import posts_list
# TODO: Found a hacky way to display all posts on home page
def home(request):
# TODO: If the user is not authenticated then don't show the home page,
# but instead show soe other page reporting the error. (Maybe just the login page).
posts_list(request)
return render(request, 'home.html')
posts / views.py
def posts_list(request):
# return HttpResponse("<h1> List a posts. </h1>")
# TODO: Privacy stuff
queryset = Post.objects.all()
context = {
"object_list": queryset,
"user": "username"
}
return render(request, "home.html", context)
答案 0 :(得分:0)
也许您不需要调用其他应用程序的视图。只需使用url重定向到帖子视图即可。
例如,您可以使用:
from posts.views import posts_list
url('home/', posts_list, name="home"),
您可以将视图导入为:
from posts.views import posts_list
在主视图中:
posts_list(request)
也:
return render(request, 'home.html')
从主视图中删除此部分。
如果这不起作用,则可以使用:
return redirect('posts:posts_list')
然后,您无需调用帖子视图。然后您的主视图将是:
def home(request):
return redirect('posts:posts_list')
如果您不想更改url,则可以将home函数更改为:
def home(request):
# TODO: If the user is not authenticated then don't show the home page,
# but instead show soe other page reporting the error. (Maybe just the login page).
if request.method == "POST":
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.publish = datetime.now()
instance.save()
queryset = Post.objects.all()
context = {
"object_list": queryset,
"user": "username",
"form":form
}
else:
form = PostForm()
queryset = Post.objects.all()
context = {
"object_list": queryset,
"user": "username",
"form":form
}
return render(request, "home.html", context)
然后,您不需要在posts_list
应用中使用posts_create
和posts
函数。