How can I create a field in a form without having to create it in a model?

2

I have a ModelForm in which I want to add a field without having to create it in the model, how can I do it?

If you are wondering why I want to have a field in a form if I am not going to send it to the model, it is because I am going to take the value of that field in the view and perform an operation with it.

here the forms.py

class SimpatizanteForm(forms.ModelForm):
    error_css_class = 'error'
    required_css_class = 'required'
    label_suffix = ':'

    class Meta:
        model = Simpatizante
        exclude = ['validado_por', 'fecha_validacion', 'creado_por', 'actualizado_por']

    def __init__(self, *args, **kwargs):
        super(SimpatizanteForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'POST'
        self.helper.form_class = 'form-horizontal'

        self.helper.layout = Layout(
            Fieldset(
            'Informacion Basica',
            'tipo_documento', 'num_documento','nombres','apellidos','genero','raza','edad','fecha_nacimiento',
            'grupos_poblacionales', 'ocupacion_profesion', 'nivel_academico', 'situacion_laboral',
            ),
            Div(
                FormActions(
                    Submit('save', unicode(('Guardar')), css_class="btn btn-primary"),
                    HTML("""<a role="button" class="btn btn-default" href="{0}">{1}</a>""".format(
                    'javascript:history.back()', unicode(('Cancelar')))),
                    css_class='btn-group col-sm-12',
            ),
            css_class='row'),
        )
    
asked by Mauricio Villa 25.08.2017 в 02:57
source

2 answers

3

It's very simple, As you should know, ModelForm inherits Form , so it is created in the same way you do as if it were a form without a model, here an example:

class SimpatizanteForm(forms.ModelForm):
    error_css_class = 'error'
    required_css_class = 'required'
    label_suffix = ':'

    # aquí puedes definir campos
    mi_campo_nuevo = forms.CharField(required=False)
    mi_otro_campo = forms.DateField(required=False)

    class Meta:
        model = Simpatizante
        exclude = ['validado_por', 'fecha_validacion', 'creado_por', 'actualizado_por']

And a recommendation that I leave you, is that you do not use the attribute of the class Meta, exclude , Since in the future can cause problems, better use fields

    
answered by 25.08.2017 / 17:52
source
1

You should not use ModelForm , just use forms.Form

an example that you take from the documentation :

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)
    
answered by 25.08.2017 в 17:23