在 Django 中更新自定义用户 (AbstractUser)
Updating custom user (AbstractUser) in Django
我使用 CBV 创建了一个自定义用户,我已经成功地实现了注册视图,但是我发现很难实现更新视图。我已经使用以下代码实现了更新视图:
models.py
class CustomUser(AbstractUser):
state = models.CharField(choices=States, default ='abia', max_length=50 )
city = models.CharField(max_length=50)
local_government = models.CharField(max_length=50)
phone_number = models.CharField(max_length=50, blank= True)
picture = models.ImageField(upload_to='user/photos', blank=False, null=False, validators=
[clean_image])
forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = UserCreationForm.Meta.fields + ('state', 'city', 'local_government', 'phone_number',
'picture',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserCreationForm.Meta.fields + ('state', 'city', 'local_government', 'phone_number',
'picture',)
admin.py
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['id', 'first_name', 'last_name', 'email','subscription_plan', 'state', 'city',
'local_government', 'phone_number', 'picture']
views.py(更新):
class UpdateUser( LoginRequiredMixin, UpdateView):
model = CustomUser
form_class = CustomUserChangeForm
template_name = 'profile/profile-edit.html'
login_url = 'login'
当我单击更新配置文件而不提交更新时,UpdateUser 页面只是重新加载。任何帮助将不胜感激。
由于您正在更新用户对象,因此您应该将 pk 值发送到模板中的 URL 标记
我使用 CBV 创建了一个自定义用户,我已经成功地实现了注册视图,但是我发现很难实现更新视图。我已经使用以下代码实现了更新视图:
models.py
class CustomUser(AbstractUser):
state = models.CharField(choices=States, default ='abia', max_length=50 )
city = models.CharField(max_length=50)
local_government = models.CharField(max_length=50)
phone_number = models.CharField(max_length=50, blank= True)
picture = models.ImageField(upload_to='user/photos', blank=False, null=False, validators=
[clean_image])
forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = UserCreationForm.Meta.fields + ('state', 'city', 'local_government', 'phone_number',
'picture',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserCreationForm.Meta.fields + ('state', 'city', 'local_government', 'phone_number',
'picture',)
admin.py
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['id', 'first_name', 'last_name', 'email','subscription_plan', 'state', 'city',
'local_government', 'phone_number', 'picture']
views.py(更新):
class UpdateUser( LoginRequiredMixin, UpdateView):
model = CustomUser
form_class = CustomUserChangeForm
template_name = 'profile/profile-edit.html'
login_url = 'login'
当我单击更新配置文件而不提交更新时,UpdateUser 页面只是重新加载。任何帮助将不胜感激。
由于您正在更新用户对象,因此您应该将 pk 值发送到模板中的 URL 标记