Simple form by Django

Asked

Viewed 2,048 times

7

If I have in mine model a class usuario, a phones and a class manager, who are one to one, so:

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 client, how do I? (abstracting layout)
I tried that so far:

In the Forms:

from django import forms
from app.models import Usuario

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

In view:

def teste(request):
    form = FormUsuario()

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

And in . html:

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

</form>

Can someone give me a hint of how I follow?

  • If you are learning, I recommend starting with Django 1.8 at once. In this case, the {{ form.departamento }} will not appear because it is part of the model Gerente. What you can do is add a field departamento in the FormUsuario, and after saving the form create a manager with the chosen department and user.

  • Hi. Yes I’ll give myself an update on Django 1.8, I really need it! As for Phone, in Asp.Net I would normally make a grid within the form to add dynamically. Already department I would enter normally and code Behind would assign in the related field. The hint of the field in the form seems good, but I still don’t know how to have all the insertion in one screen, so I don’t know how to apply it this way.

  • 1

    If you want to add multiple phones you will have to use manytomanyfield and not foreignkey. And this grid would in case a formset in Django, where your view would have two Foms. See Django’s documentation on formsets

1 answer

2

This question is old but I still leave my answer.

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

In this example, the form neither checks if the user or phone already exists nor does it check the passwords, but serves as an example:

py.models

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

py views.

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

html template.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.