gpt4 book ai didi

python - Django:我的表单没有持久保存在数据库中

转载 作者:搜寻专家 更新时间:2023-10-30 23:39:37 25 4
gpt4 key购买 nike

我这里有以下结构:

模型.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

表单.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 类,因为我想个性化我的网页。为什么不保存到数据库中?

我正在使用 postgree。

非常感谢。

最佳答案

首先,你不应该覆盖 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()返回 TrueFalse .如果是 False , 什么是表单错误?

关于python - Django:我的表单没有持久保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com