Giter VIP home page Giter VIP logo

Comments (12)

rockymeza avatar rockymeza commented on September 21, 2024 1

You can change your EventoForm to look like this. I think it should fix your problem.

class EventoForm(ModelForm):
    tipos = forms.ModelMultipleChoiceField(
        queryset=TipoEvento.objects.all(),
        widget=forms.CheckboxSelectMultiple,
    )

from django-betterforms.

gavinwahl avatar gavinwahl commented on September 21, 2024

Can you post your code, expected output, and actual output? I'm not sure if this is a bug in betterforms or if you're doing something wrong.

from django-betterforms.

dpineiden avatar dpineiden commented on September 21, 2024

Yes, no problem:

That''s the code:
<forms.py>

from django import forms
from django.forms import ModelForm
from .models import Persona, Evento, Localizacion
from django.forms.widgets import CheckboxSelectMultiple
from django.core.validators import MinLengthValidator, MaxLengthValidator,MinValueValidator,MaxValueValidator

from apps.sistema_base.models import TipoEvento

#Formulario Datos Personales


    # nombre = models.CharField(max_length=20)
    # apellido = models.CharField(max_length=20)
    # telefono = models.IntegerField()
    # email = models.EmailField()
    # edad = models.IntegerField()
    # rut_id = models.CharField( max_length = 18, blank = False, unique = True, validators=[validate_rut]) 
    # rut_palabras = models.CharField(max_length = 150, blank = True, unique=True)



class PersonaForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(PersonaForm, self).__init__(*args, **kwargs)
        self.fields["nombre"].min_length = 2
        self.fields["nombre"].validators.append(MinLengthValidator)

        self.fields["nombre"].max_length = 100
        self.fields["nombre"].validators.append(MaxLengthValidator)

        self.fields["telefono"].validators.append(MinValueValidator(100))
        self.fields["telefono"].validators.append(MaxValueValidator(999999999))

        self.fields["edad"].validators.append(MinValueValidator(10))

        self.fields["edad"].validators.append(MaxValueValidator(110))
        self.fields['nombre'].widget.attrs['class'] = 'nombre'
        self.fields['apellido'].widget.attrs['class'] = 'apellido'
        self.fields['rut_id'].widget.attrs['class'] = 'rut_id'
        self.fields['telefono'].widget.attrs['class'] = 'telefono'
        self.fields['email'].widget.attrs['class'] = 'email'
        self.fields['edad'].widget.attrs['class'] = 'edad'

    def clean(self):
        cleaned_data = super(PersonaForm, self).clean()

    class Meta:
        model = Persona
        fields = [
            'nombre',
            'apellido',
            'rut_id',
            'telefono',
            'email',
            'edad',
            ]
    # nombre = models.CharField(max_length=30)
    # date_time = models.DateTimeField(auto_now=True, auto_now_add=False)
    # prioridad = models.IntegerField()
    # estado = models.IntegerField()
    # tipo = models.ForeignKey(TipoEvento)
class EventoForm(ModelForm):

    tipos = forms.ModelMultipleChoiceField(queryset=TipoEvento.objects.all())

    def __init__(self, *args, **kwargs):
        # if 'instance' in kwargs:
        #   initial = kwargs.setdefault('initial', {})
        #   initial['tipos'] = [t.pk for t in kwargs['instance'].tipos_set.all()]

        super(EventoForm, self).__init__(*args, **kwargs)
        self.fields['tipos'].widget.attrs['class'] = 'tipos'
        self.fields['estado'].widget.attrs['class'] = 'estado'
        #self.fields['prioridad'].widget.attrs['class'] = 'prioridad'
        self.fields['estado'].widget.attrs['class'] = 'estado'


    def clean(self):
        cleaned_data = super(EventoForm, self).clean()

    class Meta:
        model = Evento
        fields = [
            'tipos',
            'estado',
            #'prioridad',
            ]
        widgets = {
            "tipos":CheckboxSelectMultiple(),
            }

class LocalizacionForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(LocalizacionForm, self).__init__(*args, **kwargs)

        self.fields["domicilio"].validators.append(MinLengthValidator(3))
        self.fields["domicilio"].validators.append(MaxLengthValidator(100))

        self.fields['domicilio'].widget.attrs['class'] = 'domicilio'
        self.fields['numero'].widget.attrs['class'] = 'numero'
        self.fields['comuna'].widget.attrs['class'] = 'comuna'

    def clean(self):
        cleaned_data = super(LocalizacionForm, self).clean()

    class Meta:
        model = Localizacion
        fields = [
            'domicilio',
            'numero',
            'comuna',
            #'latlon',
            ]

And, the betterforms:

from betterforms.forms import BetterModelForm
from betterforms.multiform import MultiModelForm
from .forms import PersonaForm, EventoForm, LocalizacionForm
from .models import Localizacion, Persona
from collections import OrderedDict
from django.forms.widgets import CheckboxSelectMultiple

from django.db.models import Q

class CallCenterMultiForm(MultiModelForm):
    form_classes = {
        'ubicacion': LocalizacionForm,
        'persona': PersonaForm,
        'incidente' : EventoForm,
    }
    tipos_evento=[]

    def clean(self):
        data = self.cleaned_data
        #incidente = data['incidente']
        print(str(data))
        #campos_1 = incidente.tipos
        #for field in campos_1:
        #   print("Campos incidente en clean(): "+field)

        if 'incidente' in data:
            if len(data['incidente']['tipos'])==0:
                raise ValidationError('Selecciona al menos un tipo de incidente')
        return data
        #print(cleaned_data.get("persona").)

    def save(self, commit=True, *args, **kwargs):

        objetos = OrderedDict(
            (key, form.save(commit=False))
            for key, form in self.forms.items()
        )

        ubicacion = objetos['ubicacion']
        persona = objetos['persona']
        incidente = objetos['incidente']

        # for tipo in self.tipos_evento:
        #   print("Eventos seleccionados en save(): "+tipo.nombre)

        # campos_1 = incidente._meta.fields
        # for field in campos_1:
        #   print(field)

        # campos_2 = ubicacion._meta.fields
        # for field in campos_2:
        #   print(field)

        # campos_3 = persona._meta.fields
        # for field in campos_3:
        #   print(field)

    #   for tipo in incidente.tipos
    #       print("Tipos seleccionados: "+tipo.nombre)


        print("Hola, hay post! "+ubicacion.domicilio)

        db_locale = Localizacion.objects.filter(Q(domicilio=ubicacion.domicilio) & Q(numero=ubicacion.numero) & Q(comuna=ubicacion.comuna))
        db_persona = Persona.objects.filter(Q(rut_id= persona.rut_id) & Q(nombre=persona.nombre) & Q(apellido=persona.apellido))


        #Si todos los datos son nuevos
        if db_locale.count() == 0 & db_persona.count()==0:
            ubicacion.save()
            persona.save()
            incidente.localizacion = ubicacion
            incidente.persona = persona
            incidente.save()
        #Si los datos de persona 

        elif db_locale.count() == 0 & db_persona.count() > 0:
            ubicacion.save()
            incidente.localizacion = ubicacion
            incidente.persona = db_persona[0]
            incidente.save()

        elif db_locale.count() > 0 & db_persona.count() == 0:
            persona.save()
            incidente.localizacion = db_locale[0]
            incidente.persona = persona
            incidente.save()

        elif db_locale.count() > 0 & db_persona.count() > 0:
            incidente.localizacion = db_locale[0]
            incidente.persona = db_persona[0]
            incidente.save()

        return objetos

(edited by @rockymeza for formatting)

from django-betterforms.

rockymeza avatar rockymeza commented on September 21, 2024

Hi @dpineiden,

Thanks for your form code, but can you also show us the code you are using to output the forms?

from django-betterforms.

dpineiden avatar dpineiden commented on September 21, 2024

Yes, it's using a ViewClass:

from django.forms import modelformset_factory
from django.shortcuts import get_object_or_404
from django.shortcuts import render

from django.views.generic import CreateView, TemplateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect

from .better_form import CallCenterMultiForm

from django.contrib import messages

from .forms import PersonaForm, EventoForm, LocalizacionForm

from .models import Localizacion, Persona, Evento
from apps.sistema_base.models import TipoEvento
from django.db.models import Q


class CallCenterView(CreateView):
    template_name = "callcenter/call_center.html"
    form_class = CallCenterMultiForm
    success_message = "¡Incidente Enviado!"
    #lat_o, lon_0], zoom_in
    lat_0=-33.437816
    lon_0=-70.635738
    geo = {'lat':lat_0,'lng':lon_0}
    zoom = 15

    def get_context_data(self, **kwargs):
        context = super(CallCenterView, self).get_context_data(**kwargs)
        context.update({'geo': self.geo,'zoom':self.zoom})
        return context  

    def form_valid(self, form):
        self.object = form.save(commit=False)

        persona_instance = self.object['persona']
        ubicacion_instance = self.object['ubicacion']   
        incidente_instance = self.object['incidente']

        #print("nombre de persona en model :"+str(self.form_class.form_classes['persona']._meta.fields))
        ubicacion = form['ubicacion']
        persona = form['persona']
        incidente = form['incidente']

        incidente_w= incidente.cleaned_data
        # print("Datos en m2m :"+str(incidente_w))

        persona_w = persona.cleaned_data
        ubicacion_w = ubicacion.cleaned_data


        db_locale = Localizacion.objects.filter(Q(domicilio=ubicacion_w["domicilio"]) & Q(numero=ubicacion_w["numero"]) & Q(comuna=ubicacion_w["comuna"]))
        db_persona = Persona.objects.filter(Q(rut_id= persona_w["rut_id"]) & Q(nombre=persona_w["nombre"]) & Q(apellido=persona_w["apellido"]))

        #form_bool = False
#Datos persona :{'rut_id': '10425205-2', 'email': '[email protected]', 'apellido': 'Pineda', 'edad': 54, 'nombre': 'Daniela', 'telefono': 34324}

        if db_locale.count() == 0 & db_persona.count()==0:
            print("Tipo 0")
            ubicacion_instance.save()
            persona_instance.save()
            incidente_instance.localizacion = ubicacion_instance
            incidente_instance.persona = persona_instance
            # #incidente.save_m2m()
            # for f in range(len(incidente_w_tipos['tipos'])):
            #   incidente.tipos.append(incidente_w_tipos['tipos'][f])
            form_bool = True
        #Si los datos de persona 

        elif db_locale.count() == 0 & db_persona.count() > 0:
            print("Tipo 1")
            ubicacion_instance.save()
            incidente_instance.localizacion = ubicacion_instance
            incidente_instance.persona= db_persona[0]
            # _instance_instance.persona = db_persona[0]
            form_bool = True

        elif db_locale.count() > 0 & db_persona.count() == 0:
            print("Tipo 2")
            persona_instance.save()
            incidente_instance.localizacion = db_locale[0]
            incidente_instance.persona = persona_instance

            #incidente.save_m2m()
            # for f in range(len(incidente_w_tipos['tipos'])):
            #   incidente.tipos.append(incidente_w_tipos['tipos'][f])

            form_bool = True

        elif db_locale.count() > 0 & db_persona.count() > 0:
            print("Tipo 3")
            incidente_instance.localizacion = db_locale[0]
            incidente_instance.persona = db_persona[0]
            #incidente.save_m2m()
            # for f in range(len(incidente_w_tipos['tipos'])):
            #   incidente.tipos.append(incidente_w_tipos['tipos'][f])
            form_bool = True

        for f in range(len(incidente_w['tipos'])):
            incidente_instance.tipos.add(incidente_w['tipos'][f])
            #print("Asignacion correcta: "+incidente_w['tipos'][f].nombre)

        incidente_instance.save()

        return self.get_absolute_url()

    def get_absolute_url(self):
        return redirect("/call_center/")    

from django-betterforms.

rockymeza avatar rockymeza commented on September 21, 2024

Hi @dpineiden,

I'm a little confused at the problem you are having. Weren't you saying that you are having trouble with displaying the form? The problem should be in the template no?

from django-betterforms.

dpineiden avatar dpineiden commented on September 21, 2024

No exactly in template, in template display ok the form.
I use the django shell, and call the betterform what result the forms without the widget (checkbox) configured to the manytomany dield. And the Html from the 'EventoForm' who result the correct html with the checkbox widget

from django-betterforms.

rockymeza avatar rockymeza commented on September 21, 2024

how are you outputting the form in the shell?

-rocky

On Fri, Feb 12, 2016 at 10:26 PM, David Pineda [email protected]
wrote:

No exactly in template, in template display ok the form.
I use the django shell, and call the betterform what result the forms
without the widget (checkbox) configured to the manytomany dield. And the
Html from the 'EventoForm' who result the correct html with the checkbox
widget


Reply to this email directly or view it on GitHub
#39 (comment)
.

from django-betterforms.

dpineiden avatar dpineiden commented on September 21, 2024

First, only Incidente Form:

<tr><th><label for="id_tipos">Tipos:</label></th><td><select multiple="multiple" class="tipos" id="id_tipos" name="tipos">
<option value="1">Asalto</option>
<option value="2">Incendio</option>
</select></td></tr>
<tr><th><label for="id_estado">Estado:</label></th><td><input class="estado" id="id_estado" min="0" name="estado" type="number" value="1" /></td></tr>

Second, BetterForm, with IncidenteForm inside:

<tr><th><label for="id_persona-nombre">Nombre:</label></th><td><input class="nombre" id="id_persona-nombre" maxlength="20" name="persona-nombre" type="text" /></td></tr>
<tr><th><label for="id_persona-apellido">Apellido:</label></th><td><input class="apellido" id="id_persona-apellido" maxlength="20" name="persona-apellido" type="text" /></td></tr>
<tr><th><label for="id_persona-rut_id">Rut id:</label></th><td><input class="rut_id" id="id_persona-rut_id" maxlength="18" name="persona-rut_id" type="text" /></td></tr>
<tr><th><label for="id_persona-telefono">Telefono:</label></th><td><input class="telefono" id="id_persona-telefono" min="0" name="persona-telefono" type="number" /></td></tr>
<tr><th><label for="id_persona-email">Email:</label></th><td><input class="email" id="id_persona-email" maxlength="254" name="persona-email" type="email" /></td></tr>
<tr><th><label for="id_persona-edad">Edad:</label></th><td><input class="edad" id="id_persona-edad" name="persona-edad" type="number" /></td></tr><tr><th><label for="id_ubicacion-domicilio">Domicilio:</label></th><td><input class="domicilio" id="id_ubicacion-domicilio" maxlength="150" name="ubicacion-domicilio" type="text" /></td></tr>
<tr><th><label for="id_ubicacion-numero">Número:</label></th><td><input class="numero" id="id_ubicacion-numero" min="0" name="ubicacion-numero" type="number" value="0" /></td></tr>
<tr><th><label for="id_ubicacion-comuna">Comuna:</label></th><td><select class="comuna" id="id_ubicacion-comuna" name="ubicacion-comuna">
<option value="" selected="selected">---------</option>
<option value="1">Santiago</option>
<option value="2">Ñuñoa</option>
<option value="3">La Florida</option>
</select></td></tr><tr><th><label for="id_incidente-tipos">Tipos:</label></th><td><select multiple="multiple" class="tipos" id="id_incidente-tipos" name="incidente-tipos">
<option value="1">Asalto</option>
<option value="2">Incendio</option>
</select></td></tr>
<tr><th><label for="id_incidente-estado">Estado:</label></th><td><input class="estado" id="id_incidente-estado" min="0" name="incidente-estado" type="number" value="1" /></td></tr>

(edited for formatting by @rockymeza)

from django-betterforms.

rockymeza avatar rockymeza commented on September 21, 2024

@dpineiden first, in the future, can you use the special code block Markdown syntax that GitHub provides, it helps a lot with readability.

You mention IncidenteForm, but above you didn't have an IncidenteForm, I'm assuming it is the EventoForm. I don't see a checkbox on the EventoForm, it only has two fields, tipos which is the select multiple and estado which appears to be an IntegerField.

Where are you expecting the checkbox to come from? What do you expect the output to be?

from django-betterforms.

dpineiden avatar dpineiden commented on September 21, 2024

Thanks, i was searrch a correct way to put code (in the standat "" don't work well)

The field on 'EventoForm' is tipos, i want be checkboxes, but the betterform clean it and put the selector for that field

from django-betterforms.

dpineiden avatar dpineiden commented on September 21, 2024

It's works!
Thanks Rockymeza ;)

from django-betterforms.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.