Passes template content to view Django

Asked

Viewed 1,083 times

3

Well I know it is possible to take content from a view and move to a template.

But the doubt would be like taking the "value" of an input and passing to a view, an example of the use would be.

Taking the value of an html input:

<input type="text" name="celular" id="id_celular" value= "xx-xxx" class="form-control">

And pass this value to a Query in the example view:

teste = x.objects.all().filter(celular= "COLOCAR O VALUE AQUI")

If necessary complete code.

  • Just make an HTTP request by sending the value. O <input> is in a form? If yes, when submitting the form the request is made and the value sent to the route you set for the view.

  • Anderson <input> is in a form but initially the input has no value. only after the user enters something he would have to take value, and complete the rest of the form inputs based on this value.

  • So search for AJAX requests.

2 answers

0

The recommended way to do this is by using the forms from Django, it would look something like this.

# forms.py
from django import forms

class NameForm(forms.Form):
    celular = forms.IntegerField(label='Número de telefone', max_length=11)
# views.py
from django.shortcuts import render
from .models import Celular
from .forms import NameForm

def get_name(request):
    # se for uma requisição POST
    if request.method == 'POST':
        # cria um formulario NameForm com os campos que foram digitados
        form = NameForm(request.POST)
        # checa se é um formulário válido:
        if form.is_valid():
            # pega o número digitado
            number = form.cleaned_data['celular']
            teste = x.objects.all().filter(celular=number)
            # ...

    # se a validação der erro vai aqui
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})

Now just adapt to your case, take a look at the link I passed there have a more complete examples, a another way would be to associate a model with a form

  • I tried to accomplish this way, however it is necessary a button to validate the form, I would like it to look whenever the user typed something in the input and was doing the search.

  • Ah in this case I only know how to do using Javascript (AJAX), when it comes to a level of interactivity like this only with JS same

  • How would you use ajax and JS?

0

Using AJAX you can easily, but for this we will use a special tool, and configure it the right way.

First you need to install the Xios. It is an http client that can be added to your html by the script tag as you can see in the documentation.

What are we gonna do?

  1. Catch the moment when the value is changed.
  2. Send to Django via Axios.

You can do this either with direct functions in the element, or with Event Listener. Within this function you should take the input value, using the onInput event (either in direct functions, or with Listener). Within this function you will make the call to the view.

let data = 'valor do input'      
axios.post('url-da-view', data, config)
.then((res)=>{
   //aplique as mudanças no DOM aqui
})
.catch((erros)=>{
  //Pegue os erros aqui.
})

All right, looks like we’re done, right? NOP. You see that config variable in the Axios call? There we have to send a cookie to Django, so that the back-end is protected from CSRF attacks. According to documentation of Django we must copy the following function to get the cookie:

function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;}

const csrftoken = getCookie('csrftoken');

To send this cookie on Xios we use that config variable.

const config = {
    // O nome do header é o Django que dá, por padrão. Mas você pode mudar nas configurações.
    headers: {
        ''X-CSRFToken': csrftoken,
    }
}

Soon after adjusting the settings, you send your request.

Browser other questions tagged

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