如何在models.py中为(状态)检查编写views.py

时间:2017-06-10 11:32:24

标签: python django

如何选择选择参数"已发布"来自views.py的models?在models.py中,我给choices选项[draft,published]

我使用表单来收集输入并将其存储到数据库中。除了这个之外,所有内容都运行良好。

  

/ blog / post / new /

中的NameError      

名称'已发布'未定义

models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,self).get_queryset().filter(status='published')  

class Post(models.Model):
    STATUS_CHOICES=(
        ('draft','Draft'),
        ('published','Published'),
    )
    title=models.CharField(max_length=250)
    slug=models.SlugField(max_length=250,unique_for_date='publish')
    author=models.ForeignKey(User,related_name='blog_posts')
    body=models.TextField()
    publish=models.DateTimeField(default=timezone.now)
    created=models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(auto_now=True)
    status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
    objects=models.Manager()
    published=PublishedManager()

views.py

from django.shortcuts import render, get_object_or_404
from django.utils import timezone 
import datetime
from .models import Post
from .forms import PostForm


def post_list(request):
    posts = Post.published.all()
    return render(request,'blog/post/list.html', {'posts':posts})

def post_detail(request,year,month,day,post):
    post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day )
    return render(request,
                  'blog/post/detail.html',
                  {'post':post})

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 = timezone.now()
            post.slug=post.title
            post.status=Published
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/post/post_edit.html', {'form': form})

1 个答案:

答案 0 :(得分:0)

更改行

post.status = 'published'

将其括在引号中。