我这里有以下结构:
models.py:
class MyUser (models.Model):
name = models.CharField(max_lenght=255, required=True)
password = models.CharField(max_lenght=255, required=True)
phone = models.CharField(max_lenght=255, required=True)
company = models.CharField(max_lenght=255,required=True)
user = models.OneToOneField(User, related_name="client")
@property
def email(self):
return self.user.email
forms.py:
from django import forms
from django.contrib.auth.models import User
class MyUserForm(forms.Form):
name= forms.CharField(required=True)
email = forms.EmailField(required=True)
pass = forms.CharField(required=True)
phone = forms.CharField(required=True)
company = forms.CharField(required=True)
def is_valid(self):
valid = True
if not super(MyUserForm, self).is_valid():
self.adiciona_erro('Error. Pleas correct the form.')
valid = False
user_exists = User.objects.filter(username=self.data['name']).exists()
if user_exists:
self.adiciona_erro('User already exists.')
valid = False
return valid
def adiciona_erro(self, message):
errors = self._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.utils.ErrorList())
errors.append(message)
views.py
:
class MyUserView(View):
def get(self, request):
return render(request, self.template_name)
def post(self, request):
form = MyUserForm(request.POST)
if form.is_valid():
dados_form = form.data
user = User.objects.create_user(dados_form['name'], dados_form['email'], dados_form['pass'])
client = Client(name=dados_form['name'],
email=dados_form['email'],
phone=dados_form['phone'],
nome_empresa=dados_form['company'],
user=user)
###########################################
#SHOULD SAVE ON DATABASE, NO?
client.save()
###########################################
return redirect('index')
return render(request, self.template_name, {'form' : form})
一切正常,除了保存数据库。我需要使用Form类,因为我想个性化我的网页。 为什么不保存在DB中?
我正在使用postgree。
非常感谢。
答案 0 :(得分:1)
首先,您不应该覆盖表单中的is_valid()
。您应该覆盖clean_<fieldname>
方法(例如clean_name
)或clean
。有关详细信息,请参阅docs on form validation。您的adiciona_erro
方法看起来没必要。只需举起ValidationError
,或致电add_error
其次,如果表单有效,您应该访问form.cleaned_data
而非form.data
的值。
如果您在进行这些更改后仍然卡住,则需要添加有关哪些内容无效的更多信息。是否调用了post
方法? form.is_valid()
返回True
或False
。如果是False
,那么表单错误是什么?