问题描述
我有以下模型:
class Article(models.Model):
title = models.CharField()
description = models.TextField()
author = models.ForeignKey(User)
class Rating(models.Model):
value = models.IntegerField(choices=RATING_CHOICES)
additional_note = models.TextField(null=True, blank=True)
from_user = models.ForeignKey(User, related_name='from_user')
to_user = models.ForeignKey(User, related_name='to_user')
rated_article = models.ForeignKey(Article, null=True, blank=True)
dtobject = models.DateTimeField(auto_now_add=True)
根据上述模型,我创建了一个模型窗体,如下所示:
Based upon the above model, i have created a model form, as follows:
模型表单:
class RatingForm(ModelForm):
class Meta:
model = Rating
exclude = ('from_user', 'dtobject')
排除 from_user
,因为 request.user
是$ code> from_user 。
Excluding from_user
because the request.user
is the from_user
.
表单呈现良好,但在下拉字段中的 to_user
中,作者也可以评价自己。所以我想要将current_user的名称填入下拉字段。我如何做?
The form renders well, but in to_user
in the dropdown field, the author can rate himself as well. So i would want the current_user's name to populate in the dropdown field. How do i do it?
推荐答案
覆盖 __ init __
删除当前用户从 to_user
选择。
Override __init__
to remove current user from the to_user
choices.
更新:更多说明
ForeignKey使用 ModelChoiceField
,其选择是查询。因此,在 __ init __
中,您必须从 to_user
的查询器中删除当前用户。
ForeignKey uses ModelChoiceField
whose choices are queryset. So in __init__
you have to remove the current user from to_user
's queryset.
更新2:示例
class RatingForm(ModelForm):
def __init__(self, current_user, *args, **kwargs):
super(RatingForm, self).__init__(*args, **kwargs)
self.fields['to_user'].queryset = self.fields['to_user'].queryset.exclude(id=current_user.id)
class Meta:
model = Rating
exclude = ('from_user', 'dtobject')
现在在您创建的视图中 RatingForm
object pass request.user
作为关键字参数 current_user
这样。
Now in the view where you create RatingForm
object pass request.user
as keyword argument current_user
like this.
form = RatingForm(current_user=request.user)
这篇关于django模型形成过滤器查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!