我希望我的帖子首先显示最新信息,但确实如此,但是当我编辑任何帖子时,它会显示在顶部,我只希望最近添加的帖子。一切正常,但我不希望编辑后的帖子排在列表顶部
views.py
def home(request):
return render(request, 'List/home.html')
def task_list(request):
context = {
'posts': Post.objects.all().order_by('-date')
}
return render(request, 'List/task.html', context)
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
form = TaskForm(instance=post)
if request.method == 'POST':
print(request.POST)
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('task')
context = {'form': form}
return render(request, 'List/add_task.html', context)
models.py
from django.db import models
from django.utils import timezone
class Post(models.Model):
Task = models.CharField(max_length=50, default='pythons')
Detail = models.TextField(max_length=100, default='python')
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.Task
答案 0 :(得分:0)
您的问题是由以下行引起的:
date = models.DateTimeField(default=timezone.now)
将其更改为auto_now_add = True
date = models.DateTimeField(auto_now_add=True)
答案 1 :(得分:-1)
您可以为日期设置'editable = False',这意味着一旦设置了日期,您以后就无法对其进行编辑,因此您还应该像这样设置'defualt = datetime.datetime.now()':
class Post(models.Model):
Task = models.CharField(max_length=50, default='pythons')
Detail = models.TextField(max_length=100, default='python')
date = models.DateTimeField(default=datetime.datetime().now, editable=False)
def __str__(self):
return self.Task