Search

Travel Tips

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lifestyle

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Hotel Review

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Django框架——出现的问题

Django Crispy Forms TypeError: __init__() got an unexpected keyword argument 'instance'

# Django Crispy Forms TypeError: __init__() got an unexpected keyword argument 'instance'


## 环境 Python3.6 + django2.2


# 错误原因是要使用instance参数 UserChangeInfoForm继承forms.ModelForm 而不是forms.Form



## 原代码


```
class UserChangeInfoForm(forms.Form):
    class Meta:
        model = UserProfile
        fields = ['nick_name', 'sex', 'address', 'phone', 'brithday']
```


```
def user_change_info(request):
    user_change_info_form = UserChangeInfoForm(request.POST, instance=request.user)
    if user_change_info_form.is_valid():
        user_change_info_form.save(commit=True)
        return JsonResponse({"status": 'ok', 'msg': '修改成功'})
    else:
        return JsonResponse({"status": 'fail', 'msg': '修改失败'})
```


## 修改之后

```
class UserChangeInfoForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['nick_name', 'sex', 'address', 'phone', 'brithday']
```


```
def user_change_info(request):
    user_change_info_form = UserChangeInfoForm(request.POST, instance=request.user)
    if user_change_info_form.is_valid():
        user_change_info_form.save(commit=True)
        return JsonResponse({"status": 'ok', 'msg': '修改成功'})
    else:
        return JsonResponse({"status": 'fail', 'msg': '修改失败'})
```


这是一个简介
    互联网冲浪金牌选手。赖床世锦赛纪录保持者,拖延俱乐部顶级VIP,夜宵外卖一级鉴赏师,国家脱单脱贫重点扶持对象,中央戏精学院优秀学生,亚洲酸柠檬推广大使,国家一级退堂鼓表演艺术家。
评论 (125)
评论

我是 s enim interduante quis metus. Duis porta ornare nulla ut bibendum

Rosie

6 minutes ago

Sed ac lorem felis. Ut in odio lorem. Quisque magna dui, maximus ut commodo sed, vestibulum ac nibh. Aenean a tortor in sem tempus auctor

Agatha Christie

December 4, 2020 at 3:12 pm

Sed ac lorem felis. Ut in odio lorem. Quisque magna dui, maximus ut commodo sed, vestibulum ac nibh. Aenean a tortor in sem tempus auctor

Steven

December 4, 2020 at 3:12 pm

Donec in ullamcorper quam. Aenean vel nibh eu magna gravida fermentum. Praesent eget nisi pulvinar, sollicitudin eros vitae, tristique odio.

Danielle Steel

December 4, 2020 at 3:12 pm