简体   繁体   English

如何在 django 的帖子上添加图像?

[英]How can I add a image on a post in django?

I want to create an upload image button in django admin post models.我想在 django 管理帖子模型中创建一个上传图像按钮。 When an image is uploaded, will be nice to be displayed on both blog card and then on post detail on the website.上传图片后,可以很好地显示在博客卡上,然后显示在网站上的帖子详细信息上。 Here is my code until now.到目前为止,这是我的代码。 How should I do this in order to make this work?我应该如何做才能完成这项工作?

Here is my blog.html page这是我的博客。html 页面

<div class="container">
   <div class="row">
      <!-- Blog Entries Column -->
      <div class="column">
         {% for post in post_list %}
         <div class="card mb-4">
            <div class="card-body">
               <img class="card-image">{{post.header_image}}</img>
               <h2 class="card-title">{{ post.title }}</h2>
               <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p>
               <p class="card-text">{{post.content|slice:":200"}}</p>
               <a href="{% url 'post_detail' post.pk  %}" class="btn-grey">Află mai multe</a>
            </div>
         </div>
         {% endfor %}
      </div>
   </div>
</div>

Here is my post detail.html这是我的帖子详细信息。html

<div class="container">
   <div class="detail-row">
      <div class="card-detail-body">
         <h1> {{ post.title }} </h1>
         <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
         <p class="card-text ">{{ post.content | safe }}</p>
      </div>
   </div>
</div>

Here is models.py这是models.py

from django.db import models
import datetime
from django.contrib.auth.models import User

STATUS = ((0,  "Draft"), (1, "Published"))

class Post(models.Model):
    title = models.CharField(max_length=1048)
    slug = models.SlugField(max_length=1048)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    related_name=('blog_posts')
    content = models.TextField()
    status = models.IntegerField(choices=STATUS, default=0)
    created_on = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.title

And here are views.py这是views.py

def blogPage(request):
    floaterForm = FloaterForm()
    post_list = Post.objects.all().order_by('-created_on')
    context = {
        'flForm' : floaterForm,
        "post_list": post_list
    }
    return render(request, "blog.html", context)

def post_detail(request, pk):
    post= Post.objects.get(pk=pk)
    context = {
        'post' : post
    }
    return render(request, "post_detail.html", context)

You've to create one field inside your models.py file like this您必须像这样在您的models.py文件中创建一个字段

image = models.ImageField(upload_to="your_upload_dir_name")

then you've to set your media configuration now you can access your image inside your template like this然后你必须设置你的媒体配置现在你可以像这样在你的模板中访问你的图像

<img src="{{ post.image.url }}">

You firstly have to create the image field in Django.您首先必须在 Django 中创建图像字段。 For example例如

blog_image = models.ImageField(upload_to="/media/blog_images")
#This /image/blog_images is the image directory.

It will save the image URL in the model field.它将图像 URL 保存在 model 字段中。 Then you can use this image URL in the src of the image tag.然后就可以在图片标签的src中使用这张图片URL了。

The html code should be like this. html代码应该是这样的。

<form method = "post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

And in the views, your code will be like this.在视图中,您的代码将是这样的。 You can change it according to your configuration.您可以根据自己的配置进行更改。

if request.method == 'POST':
    form = BlogsForm(request.POST, request.FILES)
    if form.is_valid():
         form.save()

Then you have to set the media configuration in your server configuration and in settings.py.然后你必须在你的服务器配置和 settings.py 中设置媒体配置。 I mostly use Nginx, so I do this.我主要使用Nginx,所以我这样做。

#settings.py
MEDIA_ROOT =  BASE_DIR / 'media'
MEDIA_URL = '/media/'

#ngnix
location /media {
    autoindex on;
    alias /path to media directory of project;
}

If still you got confuse, tell me in the comments.如果您仍然感到困惑,请在评论中告诉我。 Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM