获取表单中的用户名

时间:2017-12-18 23:00:53

标签: django django-forms django-users

我试图在表单中获取已记录的用户名,但我收到以下错误消息:AttributeError:' NoneType'对象没有属性'用户'

我做错了什么?

我猜

有问题
self.request = kwargs.pop('request', None)
self.user_name =self.request.user.username  

这是我的表格

class MyForm(forms.Form):

List = forms.ChoiceField(choices=())

def __init__(self, *args, **kwargs):        
    self.request = kwargs.pop('request', None)
    self.user_name =self.request.user.username  
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['List'].choices = self.list_people()

def list_people(self):      
    u = User.objects.get(username=self.user_name).accesslevel.segmentation.split(',')
    v=(('---------','---------'),)
    for l in u:
        v=v+((l.lstrip(),l.lstrip()),)
    return v

Views.py

def list_table(request):

    if request.method == 'POST':
        form = MyForm(request.POST,request=request)
    else:
        form = MyForm()

    ....

回溯

  Traceback (most recent call last):
  File "C:\Users\PC\Anaconda2\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Users\PC\Anaconda2\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\PC\Anaconda2\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\PC\folder..\views.py", line 74, in list_table
    form = MyForm()
  File "C:\Users\PC\folder..\forms.py", line 24, in __init__
    self.user = self.request.user.username
AttributeError: 'NoneType' object has no attribute 'user'

1 个答案:

答案 0 :(得分:0)

尝试在方法为GET时传递请求,而不仅仅是POST时。

def list_table(request):
    if request.method == 'POST':
        form = MyForm(request.POST, request=request)
    else:
        form = MyForm(request=request)

无论如何,如果您只想要用户,那么您已经可以访问该视图中的request.user