How do I post a form of an extended model in Django

0

Create an app in django called employee

class Empleado(models.Model):
    usuario = models.OneToOneField(User, on_delete = 'cascade', blank = False)
    cedula = models.CharField(max_length = 10)
    sueldo = models.FloatField()
    fecha_nacimiento = models.DateField()
    direccion = models.CharField(max_length = 80)
    telefono = models.CharField(max_length = 14)

def __str__(self):
    return self.user.first_name

and I want to put together the form of the EMPLOYEE model with the django User model by default in the same template, what would the view look like, how do I do this, If you can give me an example of a complete app with something similar, It would be very much appreciated, or if you know how to solve the problem, it is also very helpful.

    
asked by Jonnathan Carrasco 25.02.2018 в 23:07
source

2 answers

0

What you are doing is not extending, you are relating two tables (models) so you can do what you want you have to use inheritance (extend) the User model in Employee, your models would be the following:

class Empleado(User):
    cedula = models.CharField(max_length = 10)
    sueldo = models.FloatField()
    fecha_nacimiento = models.DateField()
    direccion = models.CharField(max_length = 80)
    telefono = models.CharField(max_length = 14)

   def __str__(self):
      return self.user.first_name

with this the model used inherits all the user fields, in the Form you would use the model used to access the user fields as well,

class EmpleadoUserForm(forms.ModelForm):

     class Meta:
         model = Empleado 
         # tienes que usar un fields para especificar que campos se van a mostrar o un exclude para indicar que campos no se van a mostrar
         fields = ['firts_name', 'celula', 'sueldo'] # y demás campos que necesites
    
answered by 02.03.2018 / 08:37
source
0

If you want to join two forms, you can use a personalized form. example:

from django import forms

class EmpleadoUserForm(forms.Form):
    cedula = forms.CharField(max_length=10, required=True, error_messages={'required':'El campo célula es obligatorio', 'max_length':'Máximo 11 caracteres'})
    sueldo = forms.FloatField()
    fecha_nacimiento = forms.DateField()
    direccion = forms.CharField(max_length = 80)
    telefono = forms.CharField(max_length = 14)
    ..... y sigue con los datos del usuario

This creates a form class with the Employee and User data together. If you look closely I have omitted the user field since if you want 2 forms in 1 it is in order to create an Employee and a User at the same time, so it would be a mistake to put the field to select a user that does not exist in that moment. With this class you can validate in the function that you have defined in your views, py but you will not be able to save since there is no real object with those fields. As I explained to you, the objective of this class is only to validate the data, once validated, you initialize the classes you want and fill in the data with the ones collected in your form. example

from .forms import *
from .models import *

def empleado_create(request):
  if request.method == 'POST':
    form = EmpleadoUserForm(request.POST)
    if form.is_valid():
      usuario = Usuario(nombre=form.cleaned_data['nombre'],
          .....)
      usuario.save()

      empleado = Empleado( usuario_id = usuario.id,
                           cedula = form.cleaned_data['cedula'],
                           sueldo = form.cleaned_data['sueldo'],
                           fecha_nacimiento = form.cleaned_data['fecha_nacimiento'],
                           direccion = form.cleaned_data['direccion'],
                           telefono = form.cleaned_data['telefono'])
      empleado.save()
      return redirect("Pagina que desees")
  else:
    form = EmpleadoUserForm()
  return render(request, 'pagina del form.html', {'form': form})

As you see first I have created the user since the class used must have a user id, (that detail must be taken into account whenever you do this kind of thing) and when creating the employee I passed him as userid the id recently created user I hope it helps you

    
answered by 27.02.2018 в 14:48