所以我想知道如何在django中锁定帖子。当我单击check并单击CreatePost时,它应该将文章固定到顶部。而较新的帖子只会显示在底部,而不会干扰固定的帖子。pin系统还应能够锁定多个柱。因此,如果我固定另一个帖子,两个帖子都应该位于顶部。其他非钉住的立柱应仅显示在下方
models.py
class AskSection(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
is_pin = models.BooleanField()
likes = models.ManyToManyField(User, related_name='likes', blank=True)
is_marked = models.BooleanField(default=False)
date_posted = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['-date_posted']
verbose_name_plural = "Ask Section"
def __str__(self):
return str(self.title)
forms.py
class AskSectionCreateForm(forms.ModelForm):
is_pin = forms.BooleanField(label="pin ask post", required=False)
class Meta:
model = AskSection
fields = ('title', 'description', 'is_pin')
widgets = {
'title': forms.TextInput(attrs={
'class': 'form-control'
}),
'description': forms.Textarea(attrs={
'class': 'form-control'
}),
}
views.py
@login_required
def create_ask_post(request):
if request.method == "POST":
form = AskSectionCreateForm(request.POST or None)
if form.is_valid():
title = form.cleaned_data.get('title')
description = form.cleaned_data.get('description')
is_pin = form.cleaned_data.get('is_pin')
obj = form.save(commit=False)
obj.title = title
obj.description = description
obj.is_pin = is_pin
obj.user = request.user
obj.save()
messages.success(request, f'You have posted {title} successfully')
return redirect('/details_ask/' + str(title) + '/')
else:
form = AskSectionCreateForm()
else:
form = AskSectionCreateForm()
context = {
'form': form
}
return render(request, "editor/create_ask_post.html", context)
html file
{% for question in all_questions %}
<!-- random HTML not important code --> <!-- code is related to just the styling of posts and just model fields -->
{% endfor %}
所以请让我知道怎么做。HTML文件不是很重要。它只包含卡和模型字段
谢谢
因此,您实际上不需要模型中的另一个字段,您可以使用DateTime字段,但正如前面所述,我将向
AskSection
模型添加一个rank = models.Integerfield(default=0)
。(别忘了迁移)您有一个views.py文件,其中包含一个函数,您可以在其中设置html的上下文(不是您在答案中显示的上下文,而是定义
all_questions
的另一个上下文)。在这里,您可以为所有问题设置顺序,如soall_questions = AskSection.objects.filter(user=request.user).order_by("rank", "-is_pin")
。你的代码可能看起来有点不同,现在我不知道你是否按用户过滤我只是假设当用户添加一个新问题时,你会增加你在新问题上的排名,因此你总是有一个干净的顺序。每当用户“锁定”一个问题时,您将采用最高排名并添加一个数字+将
Boolean
设置为True
另一种方法是使用Datefield
date_posted
,如下所示all_questions = AskSection.objects.filter(user=request.user).order_by("date_posted", "-is_pin")
。在这种情况下,日期将作为“等级”。为您保存迁移,但其灵活性不如Integerfield相关问题 更多 >
编程相关推荐