Simple Django form

6
If I have in my model a class usuario , a phones and a class manager, which are one to one, like this:

class Usuario(models.Model):
    login = models.CharField(max_length=50, unique=True)
    senha = models.CharField(max_length=50)
    telefone = models.ForeignKey(TelefonesUsuario)

class TelefonesUsuario(models.Model):
    telefone = models.CharField(max_length=11)

class Gerente(models.Model):
    departamento = models.CharField(max_length=10)
    usuario = models.OneToOneField(Usuario)

If I want to register a new customer, how do I? (abstracting layout)
I have tried this so far:

No forms:

from django import forms
from app.models import Usuario

class FormUsuario(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = Usuario

Na view:

def teste(request):
    form = FormUsuario()

    return render_to_response("teste.html", {'form': form}, context_instance=RequestContext(request))

And no .html:

<form action="" method="post">
{% csrf_token %}
    {{ form.login }}
    {{ form.senha }}
{#    {{ form.telefone }} -> exception #}
    {{ form.departamento }} {# -> não aparece na página #}

</form>

Can anyone give me a hint of how I'm following?

    
asked by anonymous 03.05.2015 / 21:48

1 answer

1

This question is old but I still leave my answer.

In this case you can create a form only to add the clients and not the extender of "Model.Form". Instead you can create a "save" function that checks out and saves the objects.

In this example, the form does not even check if the user or phone already exists, nor does it give the passwords, but it is an example:

models.py

class Usuario(models.Model):
    login = models.CharField(max_length=50, unique=True)
    senha = models.CharField(max_length=50)
    telefone = models.ForeignKey(TelefonesUsuario)

class TelefonesUsuario(models.Model):
    telefone = models.CharField(max_length=11)

class Gerente(models.Model):
    departamento = models.CharField(max_length=10)
    usuario = models.OneToOneField(Usuario) 

forms.py

from django import forms
from django.contrib.auth.hashers import make_password
from django.db import transaction
from .models import Usuario, TelefonesUsuario

class FormUsuario(forms.Form):

    login = forms.CharField(max_length=50, label='login')
    senha = forms.CharField(widget=forms.PasswordInput(), label='senha')
    conf_senha = forms.CharField(widget=forms.PasswordInput(), label='conf_senha')
    telefone = forms.CharField(max_length=20, label='telefone')

    def save(self):
        # usuario existe ?
        # telefone existe ?
        # password correcto
        # password_identico?
        # etc
        ...

        try:
            telefone = TelefonesUsuario(
                telefone=self.cleaned_data['telefone']
            ).save()

            usuario = Usuario(
                login=self.cleaned_data['login'],
                senha=make_password(self.cleaned_data['senha']),
                telefone=telefone.id
            ).save()

            return True, usuario.id

        except:
            transaction.rollback()
            return False, "Erro ao salvar cliente."


    def edit(self,id_usuario):
        # Edite o usuário

views.py

def criar_usuario(request):
    ...
    if request.method == "GET":
         # render form etc ...
         ...
    elif request.method == "POST":
         # get form etc ...
         ...
         form_status = form.save()

         if not form_status[0]:
            params['error'] = brand_form_status[1]
            return render_to_response('template.html', params)

         ...
         # continua para output

template.html

<form action="{% url 'criar-cliente' %}" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>
    
08.08.2015 / 04:53