我试图做一个插入和更新数据的形式。我已阅读这些:表格验证插入与更新
在我的项目,但是,我没有使用的ModelForm。
forms.py:
这是登记他/她的用户名和FIRST_NAME当用户看到的形式。这也是现有用户在尝试更改他/她的用户名和/或first_name时看到的形式。
from django import forms
from .models import User
class SettingsForm(forms.Form):
username = forms.CharField(max_length=16)
first_name = forms.CharField(max_length=32)
# ... and many more form fields
def clean_slug(self):
"""Make sure that the username entered by the user will be unique in the database"""
username = self.cleaned_data['username']
try:
product = User.objects.get(username=username)
except User.DoesNotExist:
# Good, there is no one using this username
pass
else:
# There is alreaady a user with this username
raise forms.ValidationError('This username has been used. Try another.')
return username
表格清理按预期用于插入数据。但是,更新数据时,它会抱怨用户名已被使用(自然,因为用户名已经存在于数据库中)。
如何在不使用FormForm时(而不使用ModelForm)引发ValidationError而更新数据?
(在这种情况下不使用ModelForm的原因是:我们可能会停止使用orm,SettingsForm可能包含来自不同模型的字段的混合,某些字段可能会以显示的形式重复数百次用户,我们还需要不与任何模型绑定的自定义字段......以及使用ModelForm相当具有挑战性(不可能)的其他场景。此问题的目的是找出是否有方法实现所需的结果,而无需使用ModelForm。)
你想要的形式允许更改现有用户的用户名? –
@RomanB。是。更新了问题以反映这一点。 – Flux
您可以很好地自定义ModelForms。看看我的博客文章:https://colinkingswood.github.io/Model-Form-Customisation/ –