在django

时间:2015-11-13 01:54:34

标签: python django

我关注了Django Girls tuorial http://tutorial.djangogirls.org/en/index.html并成功创建了一个博客。但是我想在我的块中添加一个图像字段, 目前我的models.py看起来像:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


class Post(models.Model):
    author = models.ForeignKey(User)
    title = models.CharField(max_length = 200)
    text = models.TextField()
    model_pic= models.ImageField(upload_to = 'blog/images', default='blog/images/already.png')
    created_date = models.DateTimeField(default = timezone.now)
    published_date = models.DateTimeField(blank = True, null =True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

    def approved_comment(self):
        return self.comments.filter(approved_comment=True)

class Comment(models.Model):

    post = models.ForeignKey('blog.Post', related_name='comments')
    author = models.CharField(max_length=200)
    text =  models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

    def approve(self):
        self.approved_comment = True
        self.save()
    def __str__(self):
        return self.text

和我的views.py看起来像:

from django.shortcuts import render, get_object_or_404 ,redirect

from .models import Post, Comment

from django.utils import timezone
from .forms import PostForm, CommentForm 
from django.contrib.auth.decorators import login_required


def post_list(request):
    posts = Post.objects.filter(published_date__lte = timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html',{'posts' : posts})

def post_detail(request, pk):
    post = get_object_or_404(Post, pk = pk)
    return render(request, 'blog/post_detail.html',{'post':post})

@login_required
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)

        if form.is_valid():
            post = form.save(commit = False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('blog.views.post_detail', pk=post.pk)

    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

@login_required
def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('blog.views.post_detail', pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'blog/post_edit.html', {'form': form})

@login_required
def post_draft_list(request):
    posts = Post.objects.filter(published_date__isnull=True).order_by('created_date')
    return render(request, 'blog/post_draft_list.html',{'posts':posts})

@login_required
def post_publish(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.publish()
    return redirect('blog.views.post_detail', pk=pk)

@login_required
def post_remove(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.delete()
    return redirect('blog.views.post_list')

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit = False)
            comment.post = post
            comment.save()
            return redirect('blog.views.post_detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request,'blog/add_comment_to_post.html', {'form': form})

@login_required
def comment_approve(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.approve()
    return redirect('blog.views.post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    post_pk = comment.post.pk
    comment.delete()
    return redirect('blog.views.post_detail', pk=post_pk)

我的forms.py看起来像是:

from django import forms

from .models import Post, Comment

class PostForm(forms.ModelForm):


    class Meta:
        model = Post
        fields = ('title', 'text')

class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ('author', 'text',)

现在请指导我应该在模型Post中进行哪些更改以及如何修改视图以获取我的图像以及如何为相同的模板制作

我试过https://coderwall.com/p/bz0sng/simple-django-image-upload-to-model-imagefield,但它对我不起作用。

任何帮助都将受到高度赞赏。 谢谢。

如果您需要更多信息,请发表评论。

1 个答案:

答案 0 :(得分:2)

所以,让我们走吧。

设置ImageField()时,您拥有upload_to属性。来自documentation

  

将附加到MEDIA_ROOT设置的本地文件系统路径,以确定url属性的值。

因此,您将拥有一个函数来确定存储图像的动态路径(请阅读上面的链接以获取更多信息)。

E.g。

class Post(models.Model):
    author = models.ForeignKey(User)
    title = models.CharField(max_length = 200)
    text = models.TextField()
    model_pic= models.ImageField(upload_to=upload_image, default='blog/images/already.png')
    created_date = models.DateTimeField(default = timezone.now)
    published_date = models.DateTimeField(blank = True, null =True)


    def upload_image(self, filename):
        return 'post/{}/{}'.format(self.title, filename)

请注意,您不会在{Postner model_pic中包含fields。所以它不会出现在模板上。

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'text', 'model_pic',)

您的观点会有所改变:

@login_required
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)

一旦您使用了上传,您将使用request.FILES read more here,但让我引用此信息:

  

请注意,如果请求方法是POST,则FILES将仅包含数据,并且发布到请求的文件包含enctype =" multipart / form-data"。否则,FILES将是一个空白的字典对象。

因此,在您的模板上,您的代码<form>将具有属性enctype="multipart/form-data"

<form enctype="multipart/form-data" method="POST" action="">
    {{ form.as_p }}
</form>

毕竟,您可以检索此图像以在页面中显示。假设您已通过上下文将post实例传递给模板:

<img src="{{ post.model_pic.url }}" alt="{{ post.title }}" />