Home > OS >  Using Modelform with ModelChoicefield does not work for me, gives undefined error when submitting th
Using Modelform with ModelChoicefield does not work for me, gives undefined error when submitting th

Time:01-13

I am trying to use a form that adds data to the model RaportProductie using AJAX. In the form I have 2 dropdown inputs that take data from the ManoperaRaportareBloc model.

These are the attributes from ManoperaRaportareBloc : categorie_lucrare and subcategorie_lucrare

When I submit the form it shows an error with undefined. Please help. ty.

forms.py:

class RaportProductieForm(forms.ModelForm):   
    data = forms.DateField(initial=datetime.date.today)   
    categorie_lucrare = forms.ModelChoiceField(queryset=ManoperaRaportareBloc.objects.all().values_list('categorie_lucrare', flat=True))
    subcategorie_lucrare = forms.ModelChoiceField(queryset=ManoperaRaportareBloc.objects.all().values_list('subcategorie_lucrare', flat=True))

    class Meta:
        model = RaportProductie
        fields = ['lucrare', 'data', 'tip', 'subcontractor', 'obiectiv', 'categorie_lucrare', 'subcategorie_lucrare', 'um', 'cantitate', 'valoare_prod']

views.py:

def raportproductie_create_view(request):
    # request should be ajax and method should be POST.
    if request.is_ajax and request.method == "POST":
        # get the form data
        form = RaportProductieForm(request.POST)
        # save the data and after fetch the object in instance
        if form.is_valid():
            instance = form.save()
            # serialize in new friend object in json
            ser_instance = serializers.serialize('json', [ instance, ])
            # send to client side.
            return JsonResponse({"instance": ser_instance}, status=200)
        else:
            # some form errors occured.
            data = {
                'result': 'error',
                'message': 'Form invalid',
                'form': 'oops.'
            }
            return JsonResponse(data, status=400)

    # some error occured
    return JsonResponse({"error": ""}, status=400)

template.html:

$("#friend-form").submit(function (e) {
        // preventing from page reload and default actions
        e.preventDefault();
        // serialize the data for sending the form data.
        var serializedData = $(this).serialize();
        console.log(serializedData)
        // make POST ajax call
        $.ajax({
            type: 'POST',
            url: "{% url 'proiecte:raportprod-create' %}",
            data: serializedData,
            success: function (response) {             

                // display the newly friend to table.
                var instance = JSON.parse(response["instance"]);
                
                var fields = instance[0]["fields"];                
                
                $("#table-ajax tbody").prepend("<tr><td>" fields.data "</td><td>" fields.tip "</td><td>" fields.subcontractor "</td><td>" fields.obiectiv "</td><td>" fields.categorie_lucrare "</td><td>" fields.subcategorie_lucrare "</td><td>" fields.um "</td><td>" fields.cantitate "</td><td>" fields.valoare_prod "</td></tr>")
            },
            error: function (xhr, status, error) {
                  var err = JSON.parse(xhr.responseText);
                  alert(err.error);
              }
        })
    })

later edit:

i've used pdb to debug, printed the form before checking if valid and it returns this:

form.data
<QueryDict: {'csrfmiddlewaretoken': ['*********'], 'lucrare': ['1'], 'date': ['2023-01-10'], 'tip': ['1'], 'subcontractor': ['TGC Tadjiki'], 'obiectiv': ['obiectiv'], 'categorie_lucrare': ['CONFECTII_METALICE'], 'subcategorie_lucrare': ['CONSTRUCTIE ATIC - CONF METALICA'], 'um': ['km'], 'cantitate': ['2'], 'valoare_prod': ['0']}>

so...the inputs are working,

also in the ajax code, i've also gave a console.log(serializedData) and it outputs this:

csrfmiddlewaretoken=***********=1&date=2023-01-10&tip=1&subcontractor=TGC Tadjiki&obiectiv=obiectiv&categorie_lucrare=HIDRO_TERASE&subcategorie_lucrare=CONSTRUCTIE ATIC - CONF METALICA&um=mp.&cantitate=2&valoare_prod=0

later later edit:

when I am not using ModelChoiceField in the forms.py, and write the inputs by hand, the form submits...

CodePudding user response:

I found an answer to my question, in the Modelform modified the custom queryset so that they remain Charfield and have added choices:

class RaportProductieForm(forms.ModelForm):   
    date = forms.DateField(initial=datetime.date.today)
    queryset=ManoperaRaportareBloc.objects.all()
    OPTIONS1 = [(choice.pk, choice.categorie_lucrare) for choice in queryset]
    OPTIONS2 = [(choice.pk, choice.subcategorie_lucrare) for choice in queryset]
    queryset2 = Echipa.objects.all() 
    OPTIONS3 = [(choice.pk, choice.nume) for choice in queryset2]
    
    
    categorie_lucrare = forms.CharField(widget=forms.Select( choices = OPTIONS1 ))
    subcategorie_lucrare = forms.CharField(widget=forms.Select( choices = OPTIONS2 ))
    subcontractor = forms.CharField(widget=forms.Select( choices = OPTIONS3 ))   
    
    class Meta:
        model = RaportProductie
        fields = ['lucrare', 'date', 'tip', 'subcontractor', 'obiectiv', 'categorie_lucrare', 'subcategorie_lucrare', 'um', 'cantitate', 'valoare_prod']
  • Related