gpt4 book ai didi

python - 如何排除 ModelMultipleChoiceField 中的值?

转载 作者:行者123 更新时间:2023-11-28 17:34:23 25 4
gpt4 key购买 nike

我不希望登录用户出现在这个 ModelMultipleChoiceField 上,以限制他们自己与自己建立关注关系?那么我如何从查询集中排除已登录的用户,这可能是一个简单的解决方法,但我是 Django 的新手,现在已经有几个小时没有解决这个问题了。

表单.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',
)

View .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'

最佳答案

您绝对可以使用 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

关于python - 如何排除 ModelMultipleChoiceField 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31973414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com