如何排除ModelMultipleChoiceField中的值?

时间:2015-08-12 19:04:15

标签: python django forms

我不希望登录用户出现在这个ModelMultipleChoiceField上,以限制自己与自己创建以下关系?那么如何从查询集中排除登录用户,可能是一个简单的修复方法,但我是Django的新手,现在已经躲过了几个小时。

forms.py

class Add_Profile(forms.ModelForm):

def __init__(self,*args, **kwargs): # initializing your form in other words loading it
    super(Add_Profile, self).__init__(*args, **kwargs)
    user_id = kwargs.pop('user_id') # taking user_id out of the querylist
    self.fields['follows'] = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=UserProfile.objects.filter(~Q(id=user_id)))

  class Meta:
     model = UserProfile
     fields = (
        'bio',
        'follows',
        'theme',
        'profile_picture',
     )

Views.py

@login_required   
def edit_profile(request, user_id):
userprofile = UserProfile.objects.get(pk=user_id)
if request.method == 'POST':
    edit_profile = Add_Profile(request.POST, request.FILES, instance=userprofile, user_id=request.user.id)
    if edit_profile.is_valid():
        edit_profile.save()
        return redirect('/home/user/{0}/'.format(request.user.username))
    else:
        print edit_profile.errors
else:
    edit_profile = Add_Profile(instance=userprofile, user_id=request.user.id)
return render (request, 'edit.html', {'form': edit_profile,})

错误: init ()得到了一个意外的关键字参数'user_id'

2 个答案:

答案 0 :(得分:2)

您绝对可以使用forms.Form而不是forms.ModelForm来执行此操作this example in the docs

from django import forms
from django.contrib.auth import get_user_model

class Add_Profile(forms.Form):
    follows = forms.ModelMultipleChoiceField(queryset=None)

    def __init__(self, user=None, *args, **kwargs):
        super(Add_Profile, self).__init__(*args, **kwargs)
        if user is not None:
            self.fields['follows'].queryset = get_user_model().objects.exclude(pk=user.pk)
        else:
            self.fields['follows'].queryset = get_user_model.objects.all()

在实例化表单时,只需传入要排除的用户:

form = Add_Profile()  # all users will be present in the dropdown
some_guy = User.objects.get(pk=4)
form = Add_Profile(user=some_guy)  # all users except some_guy will be present

答案 1 :(得分:0)

为表单类定义__init__方法。在初始化时将登录的用户标识传递给表单,这将使用模型表单。

def __init__(self, *args, **kwargs):
    user_id = kwargs.pop('user_id')
    super(Add_Profile, self).__init__(*args, **kwargs)
    self.fields['follows'] = forms.ModelMultipleChoiceField(queryset=UserProfile.objects.filter(~Q(user_id=user_id)))

在初始化表单时,您可以传递user_id

address_form = Add_Profile(request.POST, user_id=request.user.id)