How to open a screen with a pre-filled HTML form?

Asked

Viewed 997 times

0

I would like to know, how to open a form whose fields are already pre-filled with the user’s data (resulting from a search in the database), being in charge of it only edit the information.

I’m using Django to program, I was able to make the form, but I can’t recover it for editing.

I can even use the function {{ form.as_p }}, however I would like to recover this data using <input>, has as?

Currently my edit view is as follows:

def editar(request, pk): # Funcao para editar um aluno
post = get_object_or_404(Aluno, pk=pk)
if request.method == "POST":
    form = PostForm(request.POST, instance=post)
    if form.is_valid():
        post = form.save(commit=False)
        post.save()
        return redirect('aluno:detalhes', pk=post.pk)
else:
    form = PostForm(instance=post)
return render(request, 'aluno/editar.html', {'form': form})

And in html it’s like this:

  <form method="POST" class="post-form">{% csrf_token %}
                        <!--Entrada do nome do aluno-->
                        <label class="campos" for="nome">Nome:</label><br>
                        <input type="text" name="nome" id="nome" required autofocus >
                        <p></p>

2 answers

1

To manually populate the value of tags input in his form you need to reference the Django form fields, pick up the .value of them and fill in value of input, as in the example below:

<input type="text" name="nome" id="nome" value="{{ form.nome.value|default:"" }}" required autofocus>
{# Tome nota para a tag "default" que é útil quando o campo está vazio pois em alguns casos ele ficaria mostrando o campo nulo "None" do Python #}

0

In your view, when instantiating the form, add the instance of the desired object.

meu_objeto = MyObject.objects.get(pk=meu_id)
form = MyForm(instance=meu_objeto)

That should solve your problem.

  • Then, doing something similar, follow an excerpt from my View: def edit(request, pk): post = get_object_or_404(Student, pk=pk) form = Postform(instance=post) Return render(request, 'student/edit.html', {'form': form'})

  • I edited my question with an excerpt from the current code

Browser other questions tagged

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