Reputation: 315
I have here the following structure:
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)
And the 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})
Everything works, except save on database. I need to use the Form class because I want personalize my web page. Why does it not save in the DB?
I'm using postgree.
Thanks a lot.
Upvotes: 1
Views: 66
Reputation: 308879
Firstly, you shouldn't override is_valid()
in your form. You should override either a clean_<fieldname>
method (e.g. clean_name
) or clean
instead. See the docs on form validation for more info. Your adiciona_erro
method looks unnecessary. Just raise ValidationError
, or call add_error
Secondly, if the form is valid, you should access the values from form.cleaned_data
instead of form.data
.
If you're still stuck after making those changes, you need to add more information about what isn't working. Is the post
method being called? Is form.is_valid()
returning True
or False
. If it's False
, what are the form errors?
Upvotes: 1