2016-07-07 59 views
0

所以我有一个基本的Django网站设置,显示来自数据库的动态信息。如何在将数据库信息显示在Django模板中之前处理数据库信息?

我希望能够处理来自数据库的文本,所以我可以创建BBCode解析器或任何我想要的东西。我对Django来说很新,所以我有点困惑,应该在哪里完成。

这些都是我的文件至今...

Models.py

from django.db import models 

class Post(models.Model): 
    title = models.CharField(max_length=140) 
    body = models.TextField() 
    date = models.DateTimeField() 

    def __str__(self): 
     return self.title 

Urls.py

from django.conf.urls import url, include 
from django.views.generic import ListView, DetailView 
from forum.models import Post 

urlpatterns = [ 
    url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="forum/forum.html")), 
    url(r'^(?P<pk>\d+)$', DetailView.as_view(model = Post, template_name = 'forum/post.html')), 
] 

Forum.html

{% extends "layout.html" %} 

{% block body %} 
    {% for post in object_list %} 
     <p>{{ post.date|date:"Y-m-d" }}<a href="/forum/{{post.id}}"> {{ post.title }}</a></p> 
    {% endfor %} 
{% endblock %} 

Functions.py

def bbcode(data): 
    data2 = data + "some random text" 

    return data2 

所有这些文件都位于根目录项目文件夹“coolsite”中的“论坛”目录内。

所以我的理解是,我需要在某处导入functions.py,并使用bbcode()方法来处理从数据库中拉出的文本。这样一旦在“forum.html”模板上显示,它就被解析了。

对不起,如果这是一个重复的问题。我四处搜寻,无法完全找到我正在寻找的东西。

我应该怎么做呢?

+0

类型的一个广泛的问题,但它应该在视图中完成。 – Sayse

回答

2

您需要覆盖ListView方法。您将需要做在你的代码的一些变化:

  • 设置自定义视图,以您的网址配置

urls.py

from django.conf.urls import url, include 
from django.views.generic import ListView, DetailView 
from forum.models import Post 
from forum.views import PostList 

urlpatterns = [ 
    url(r'^$', PostList.as_view(), name='post_list'), 
    url(r'^(?P<pk>\d+)$', DetailView.as_view(model = Post, template_name = 'forum/post.html')), 
] 
  • 创建自定义视图您基于ListView的应用(forum.views)

    # views.py 
    
    from django.views.generic import ListView 
    from forum.models import Post 
    
    
    class PostList(ListView): 
    
    model = Post 
    template_name = "forum/forum.html" 
    
    # here is where magic happens 
    def get_context_data(self, *args, **kwargs): 
        context = super(PostList, self).get_context_data(*args, **kwargs) 
        # context has the same context that you get in your template before 
        # so you can take data and work with it before return it to template 
        return context 
    

你可以找到文档Class-Based Views here

+0

你救了我的一天,队友! – oskarko