所以我有一个基本的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 :(得分:2)
您需要覆盖ListView
方法。您需要对代码进行一些更改:
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