首页 > 解决方案 > 如何创建一个 Django 网站来发布文章?

问题描述

我是 django 的新手,我真的不知道应该如何构建网站以发布文章(如教程)。我不是要求特定的代码,但它是如何工作的?

我应该为我要发布的每篇文章制作一个基本模板和一个 html 文件吗?如果是这样,项目中的文件夹结构应该如何?如果用户点击它,我如何显示所有这些文章的列表并重定向到它们?我应该将它们链接到数据库条目吗?我怎样才能做到这一点?

我问这些事情是因为我只做了涉及从数据库/模型中读取内容并将其显示在模板上的事情,但是文章需要图像和其他特殊结构,而博客文本字段是不够的。

如果它太令人困惑,那就这么说吧,我会试着换句话,我真的很难把我的问题变成文字。

标签: djangodjango-modelsdjango-templates

解决方案


I think you are just starting with Django, and if that is correct, I suggest you to start by making a hello world app to have a quick grasp of how django works, here is a good tutorial.

If you aren't just skip that part and start by writing down the requirements.

If you want your blog articles to have a header image, or a special text field in which you can write rich text, or even if you want to build a categories/tag system, write that in your requirements.

For each thing you would like to have django has already some ways to solve it.

For example for the image of the article you will use a django model field name ImageField.

I'll give you a really basic reference for the article model (You'll have to start a project and create an app).

# models.py
from django.db import models

class Article(models.Model):
   title = models.CharField(max_length=140)
   body = models.TextField()
   image = models.ImageField(upload_to="blog/images") 
   created_on = models.DateTimeField(auto_now_add=True)
   
   def __str__(self):
       return self.title

Remember to make use of views and template language, but if you need some help with the image in the template just use this:


{% if post.image %}
<img src="{{ post.image.url }}" title="Post image">
{% endif %}

Also you have to realize that you'll need a hosting service like heroku or amazon for your app, and a media CDN to host the images of your posts. If you decide to use heroku i recommend to use Cloudinary and here is a tutorial.

If you need some inspiration feel free to checkout my blog.


推荐阅读