我正在尝试使用以前的stackoverflow答案和谷歌来使我的表单工作,但似乎没有什么对我有用。
我有一个模型项目和一个项目团队,我希望用户能够从他创建的一个团队中进行选择并将其链接到项目。
我正在使用名为MyUser的自定义用户
这是我的表格,以便选择一个团队:
from django import forms
from django.contrib.auth.models import User
from registration.models import MyUser
from .models import Project, Team
from django.contrib.auth import get_user_model
User = get_user_model()
class EditSelectTeam(forms.Form):
team_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None)
def __init__(self, User, request, *args, **kwargs):
super(EditSelectTeam, self).__init__(*args, **kwargs)
self.fields['team_choice'].queryset = Team.objects.all().filter(team_hr_admin = request.User)
我的观点:
def TeamSelect(request):
if request.method == "POST":
select_form = EditSelectTeam(request.user, request.POST)
if select_form.is_valid():
print('sucess')
else:
print('Fail')
else:
select_form = EditSelectTeam(request)
return render(request,'link_project.html',
{'select_form':select_form })
如果在我的表单中我放了request.User
我在我的视图中得到错误:
TypeError: __init__() missing 1 required positional argument: 'request'
如果我没有将用户放入我的__init__
我收到表单,但是当我点击POST时我收到错误
AttributeError: 'MyUser' object has no attribute 'user'
答案 0 :(得分:1)
您的__init__
方法需要User
和request
,
def __init__(self, User, request, *args, **kwargs):
但你只将其中一个传递给表格:
select_form = EditSelectTeam(request.user, request.POST)
...
select_form = EditSelectTeam(request)
我会将__init__
方法更改为user
(小写),
def __init__(self, user, *args, **kwargs):
super(EditSelectTeam, self).__init__(*args, **kwargs)
self.fields['team_choice'].queryset = Team.objects.all().filter(team_hr_admin=user)
然后将视图更改为始终通过request.user
。
select_form = EditSelectTeam(request.user, request.POST)
...
select_form = EditSelectTeam(request.user)