无法获取django表单的初始数据

时间:2016-05-16 10:51:58

标签: python django python-2.7 django-forms

这里是django形式,这是django用户更改表格

class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """

    class Meta:
        model = MyUser
        fields = ('first_name', 'last_name', 'mobile' , 'gender')
        widgets = {
        'gender': forms.RadioSelect(),
        }

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)
        if self.request.user.is_authenticated():
            user = User.objects.get(email=self.request.user.email)
            first_name = user.first_name
            last_name = user.last_name
            mobile = user.mobile
            gender = user.gender

        self.fields['first_name'].initial = first_name
        self.fields['last_name'].initial = last_name
        self.fields['mobile'].initial = mobile
        self.fields['gender'].initial = gender

这是我得到的错误

'UserChangeForm' object has no attribute 'request'

这是视图

class UserProfileEditView(DetailView):
    template_name = "edit_profile.html"

    def get(self , request , *args , **kwargs):
        context = {}
        edit_form = UserChangeForm()

        context['edit_form'] =  edit_form

        return render(request , self.template_name , context)

这里是追溯

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "C:\Users\lenovo\Desktop\Grooved2\grooved\src\accounts\views.py" in get
  54.         edit_form = UserChangeForm()
File "C:\Users\lenovo\Desktop\Grooved2\grooved\src\accounts\forms.py" in __init__
  58.         if self.request.user.is_authenticated():

如何获取django表单中字段的初始数据? 谢谢

MHassan的响应后

已修改

这是表格

def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)
        intial_data = self.kwargs.get('initial')
        request = intial_data.get('request')

        if self.request.user.is_authenticated():
            user = User.objects.get(email=request.user.email)
            first_name = user.first_name
            last_name = user.last_name
            mobile = user.mobile
            gender = user.gender

        self.fields['first_name'].initial = first_name
        self.fields['last_name'].initial = last_name
        self.fields['mobile'].initial = mobile
        self.fields['gender'].initial = gender
        del self.fields['gender'].widget.choices[0]

这是视图

def get(self , request , *args , **kwargs):
        context = {}
        edit_form = UserChangeForm(initial={'request': request})

        context['edit_form'] =  edit_form

        return render(request , self.template_name , context)

这里是追溯

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "C:\Users\lenovo\Desktop\Grooved2\grooved\src\accounts\views.py" in get
  54.         edit_form = UserChangeForm(initial={'request': request})
File "C:\Users\lenovo\Desktop\Grooved2\grooved\src\accounts\forms.py" in __init__
  58.         intial_data = self.kwargs.get('initial')

1 个答案:

答案 0 :(得分:1)

Django请求对象默认情况下在Form类中不可用,因此您必须自己传递它:

class UserChangeForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        # Call super() after deleting the extra kwargs.
        super(UserChangeForm, self).__init__(*args, **kwargs)
        # Other code

在视图中创建表单时传递它:

def update(request):
    form = UserChangeForm(request=request)