我正在学习django大约一个月,我正在尝试在博客应用中为我的帖子应用激活/停用功能。这是我的模特。我的愿望是能够激活帖子以在模板中显示它但是如何通过view.py更改(设置)is_activate
字段的值?以下是我做模特的方法:
class Post(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
body = models.TextField()
is_activate = models.BooleanField(default=False)
总结:我需要点击一个按钮并激活一个帖子,然后在另一个激活帖子的模板中显示它
答案 0 :(得分:1)
您可以按主键访问帖子
post = Post.objects.get(id=id)
post.is_activate = True
post.save()
通过此代码,您的is_activate标志将设置为此帖子
答案 1 :(得分:0)
试试这个: 这是您的 model.py
class Post(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
body = models.TextField()
is_activate = models.BooleanField(default=False)
和view.py
from foldername import Post //if there are subfolders use'.' between them.
//import the other packages which u need
form=form_name //your form name
template=template_name //your template name
def post( self, request, *args, **kwargs ):
try:
form = self.form_class( request.POST)
if form.is_valid():
new_formfile = form.save(commit=False)
new_formfile.is_activate = true
new_formfile.save()
except Exception as e:
return render(request, 'exception.html', {'exception': str(e), 'message': e.message})
或强>
//在try块
中写入另一个方法id = request.GET.get('id')
id_instance = Post.objects.get( pk = id )
form = self.form_class(request.POST, instance = id_instance)
if form.is_valid():
new_formfile = form.save(commit=False)
new_formfile.is_activate = true
new_formfile.save()
form.save()