Initial Form Django is not working properly

Asked

Viewed 30 times

1

Well I am developing an application in Django and I am trying to use jquery with Django to make a request to Viacep to consult the cep that the person typed and left the focus of the field that was typing.

This is my view.py

@login_required(login_url="/login/")
def cadastro_empresa(request):
    
    cep = request.GET.get('cep')

    try:
        resposta = cep_consulta(cep)
        logradouro = resposta['logradouro']
        bairro = resposta['bairro']
        print(resposta)
    except:
        resposta = ''
    
    
    if request.method == 'POST':

        form = EmpresaForm(request.POST)

        if form.is_valid():
            
            form.save()
            messages.success(request, 'Formulario enviado com sucesso!')
            return HttpResponseRedirect('/cadastro-empresa/')
    else:
        if resposta != '':
            form = EmpresaForm(initial={
                'endereco': logradouro,
                'bairro': bairro
            })
            print(form)
        else:
            form = EmpresaForm()
        
    
    return render(request, 'cadastros/cadastro_empresa.html', locals())

this is my block I’m putting the form.

{% block content %}
<div class="content-wrapper">
    <div class="content">
        <div class="col-lg-9">
            <div class="card card-default">
                <div class="card-header card-header-border-bottom">
                    <h2>Cadastro de Empresa</h2>
                </div>
                <div class="card-body">
                    <form action="" method="post">
                        {% csrf_token %}
                        {% if form %}
                            <div class="form-row">
                                <div class="form-group col-md-6 mb-0">
                                    {{ form.cnpj|as_crispy_field }}
                                </div>
                                <div class="form-group col-md-6 mb-0">
                                    {{ form.nome|as_crispy_field }}
                                </div>
                                
                                </div>
                                <div class="form-row">
                                    <div class="form-group col-md-6 mb-0">
                                        {{ form.ie|as_crispy_field }}
                                    </div>
                                    <div class="form-group col-md-6 mb-0">
                                        {{ form.razao_social|as_crispy_field }}
                                    </div>
                                </div>
                                <div class='form-row'>
                                    <div class='form-group col-md-6 mb-0'>
                                        {{ form.email|as_crispy_field }}
                                    </div>
                                    <div class='form-group col-md-6 mb-0'>
                                        {{ form.fone|as_crispy_field }}
                                    </div>
                                </div>
            
                                <div class='form-row'>
                                    <div class="form-group col-md-4 mb-0">
                                        {{ form.cep|as_crispy_field }}
                                    </div>
                                    <div class='form-group col-md-4 mb-0'>
                                        {{ form.cidade|as_crispy_field }}
                                    </div>
                                    <div class='form-group col-md-4 mb-0'>
                                        {{ form.uf|as_crispy_field }}
                                    </div>
                                </div>
                                <div class="form-row">
                                <div class="form-group col-md-6 mb-0">
                                    {{ form.endereco|as_crispy_field }}
                                </div>
                                <div class="form-group col-md-6 mb-0">
                                    {{ form.bairro|as_crispy_field }}
                                </div>
                                
                                </div>
                                <div class="form-row">
                                <div class="form-group col-md-6 mb-0">
                                    {{ form.ativo|as_crispy_field }}
                                </div>
                                <div class="form-group col-md-6 mb-0">
                                    {% for message in messages %}
                                    <div class="alert alert-success" role="alert">
                                        {{ message }}
                                    </div>
                                    {% endfor %}
                                </div>
                                </div>
                                
                                <button type="submit" class="btn btn-primary">Adicionar</button>
                        {% endif %}
                    </form>
                </div>
            </div>
            
        </div>
    </div>
</div>
{% endblock  %}

this is the jquery to call the url that calls the view up there.

{% block script %}
    <script>
    $("#id_cep").blur(function(){
        $.ajax({
            url: "{% url 'cadastro_empresa' %}",
            method: 'GET',
            data:{cep: $('#id_cep').val()},
            beforeSend: function(){
                $('#id_nome').val();
            },  
            success: function(response){
                
            }
        })
    });
    </script>
{% endblock  %}

and finally this is the return of when I print my form after the "if answer != ''"

<tr><th><label for="id_endereco">Endereco:</label></th><td><input type="text" name="endereco" value="Rua Nelson Cordeiro" maxlength="400" required id="id_endereco"></td></tr>
<tr><th><label for="id_bairro">Bairro:</label></th><td><input type="text" name="bairro" value="Loteamento Marinoni" maxlength="200" required id="id_bairro"></td></tr>
<tr><th><label for="id_cep">Cep:</label></th><td><input type="text" name="cep" maxlength="9" required id="id_cep"></td></tr>

as you can see it is sending along with the form the values with the values of the api I am consulting but unfortunately these values are not rendered on the screen someone can help me ?

1 answer

0

You will have to render this your form in HTML. First, you will have to return this variable form as a json. That piece of code goes in place of the print(form). Thus:

from django.http import JsonResponse
data = {}
data["form"] = form
return JsonResponse(data)

Then in javascript, inside the function success, you will get the return that comes in the variable response and render in any div empty in html. Like this:

// coloquei o id div-vazia, mas você altera de acordo com a sua necessidade
$('#div-vazia').html(response.form);

There is also another way, that would be throwing the values directly into the inputs.

That piece of code goes in place of the print(form).

from django.http import JsonResponse
data = {}
data["endereco"] = logradouro
data["bairro"] = bairro
return JsonResponse(data)

That chunk of code goes inside the success.

const endereco = response.endereco
const bairro = response.bairro
$("#id_endereco").val(endereco);
$("#id_bairro").val(bairro);

In short, here we return json of view, we receive this information in the function AJAX and manipulate the DOM to display this information. Vlw!

Browser other questions tagged

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