3

私は次のモデルを持っています:

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)

上記のモデルに基づいて、次のようなモデルフォームを作成しました。

モデルフォーム:

class RatingForm(ModelForm):

     class Meta:
          model = Rating
          exclude = ('from_user', 'dtobject')

from_userであるため除外request.userfrom_userます。

フォームはうまくレンダリングされますがto_user、ドロップダウンフィールドで、作成者は自分自身を評価することもできます。したがって、current_userの名前をドロップダウンフィールドに入力する必要があります。どうすればいいのですか?

4

1 に答える 1

9

オーバーライドして、現在のユーザーを選択肢__init__から削除します。to_user

更新: 詳細説明

ModelChoiceField選択肢が queryset であるForeignKey を使用します。そのため、のクエリセット__init__から現在のユーザーを削除する必要がありますto_user

更新 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オブジェクトパスを作成するビューで、このようrequest.userにキーワード引数として渡しますcurrent_user

form = RatingForm(current_user=request.user)
于 2012-11-24T08:06:55.367 に答える