3

我有以下模型:

类用户配置文件(模型。模型):

user = models.OneToOneField(User, related_name="user")
people_interested = models.ManyToManyField(User, related_name="interested")

现在我想要一个表单,我想为用户提供一个可以选择 people_interested 的表单,所以我添加了以下 forms.py

class ChooseForm(forms.Form):
    q_set = User.objects.all()
    peers = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset = q_set)

然后在视图中:

form = ChooseForm(data = request.POST or None)
if request.POST and form.is_valid():
    uprofile, created = UserProfile.objects.get_or_create(user=request.user)
    uprofile.people_interested = form.cleaned_data['peers']
    uprofile.save()
    return HttpResponseRedirect("/")
else:
    return render(request, "form_polls.html", {'form':form})

但这样做的问题是,当前用户实例也会显示出来。所以我在views.py中尝试了以下内容:

form = ChooseForm(request.user.id, data = request.POST or None)

然后在 forms.py

class ChooseForm(forms.Form):

    def __init__(self, uid, *args, **kwargs):
        super(ChooseForm, self).__init__(*args, **kwargs)
        self.fields['peers'].queryset = User.objects.exclude(id=uid)
    q_set = User.objects.all() 
    peers = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset = q_set)

但是上面不是一个干净的实现,有没有更好的方法呢?

4

1 回答 1

2

是什么让你说这不是一个干净的实现?覆盖queryset__init__完全可以接受的。

为了改进你的代码,我唯一要做的就是使用一个post_save信号User来创建它UserProfile,然后user.get_profile()在你的视图上做。看到这个问题

You could also use a ModelForm for UserProfile instead of a regular form, and limit the fields to people_interested.

于 2013-02-12T15:30:04.710 回答