带有图片Django3的博客文章

时间:2020-05-07 18:08:55

标签: django django-models django-views

嗨,我想在我的博客文章应用中添加一些功能,我想将图像粘贴到文章内容中,所以我想这是我为图像创建新模型并将其设置为OneToOne的原因。模型 我想知道是否有什么方法可以将此图像设置为帖子模型中的内容字段

models.py

class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post-detail', kwargs={'pk': self.pk})

class PostImage(models.Model):
    post = models.OneToOneField(Post, on_delete=models.CASCADE)
    image = models.ImageField(default=None, upload_to='post_pics', blank=True)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

    img = Image.open(self.image.path)

    if img.height > 500 or img.width > 500:
        output_size = (500, 500)
        img.thumbnail(output_size)
        img.save(self.image.path)

vievs.py

def home(request):
context = {
    'posts': Post.objects.all(),
    'user_posts': "active",
}

return render(request, 'blog/home.html', context)


class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 5

post_template.html

{% extends "blog/base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
   <div class="content-section">
       <form method="POST">
           {% csrf_token %}
           <fieldset class="form-group">
               <legend class="border-bottom mb-4">Blog Post</legend>
            {{form|crispy }}
           </fieldset>
           <div class="form-group">
               <button class="btn btn-outline-info" type="submit">Post</button>
           </div>
       </form>
   </div>
{% endblock content %}

2 个答案:

答案 0 :(得分:0)

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

in this picture you can see image that i've browsed from my desktop ans it's exactly there where i want it to be saved

答案 1 :(得分:0)

好吧,我找到了另一个使用CKEditor的解决方案,现在一切正常

相关问题