Eric Cano
Eric Cano

Reputation: 21

Passing variable with POST in django

Hi im trying to pass a name from a form to a view in django using POST. There are no errors in the execution but its passing nothing from the template and dont know if i doing something wrong here. Im starting with django so i can have newbie errors. If u need more information tell me pls.

Views.py

def crear_pdf(request):
    empresa_selec = ""
    form = EmpModelForm()
    if request.method == 'POST':
        form = EmpModelForm(data=request.POST)
        if form.is_valid():
            empresa_selec = form.cleaned_data['nombre']

   #"empresa_selec" that's the empty variable

Models.py

class Empresa_modelo(models.Model):
    nombre = models.CharField(max_length=100,blank=True,null=True)

Forms.py

    class EmpModelForm(forms.ModelForm):
        class Meta:
            model = Empresa_modelo
            fields = ["nombre"]

template.html

 <div class="container-fluid">
            <form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %}
                <p>Empresa</p>
                <input type="text" name="empresa">
                <br>
                <button type="submit">Subir</button>
            </form>
            <br>
            <a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a>
        </div>

Upvotes: 0

Views: 1885

Answers (3)

AR7
AR7

Reputation: 376

Had a look at your code,there are a couple of issues.First you are not using the model form defined in your forms.py file in your template. Second you have defined an input text box with the name that you are not referring in your views. Either use the model form or use the same name of your input text box in your views.

def crear_pdf(request):
empresa_selec = ""
form = EmpModelForm()
if request.method == 'POST':
    form = EmpModelForm(data=request.POST)
    if form.is_valid():
        empresa_selec = form.cleaned_data['nombre']
else:
    return render(request,"template.html",{"form":form})

And in your template you can edit as such:

<div class="container-fluid">
        <form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %}
            {{ form.as_p }}
            <br>
            <button type="submit">Subir</button>
        </form>
        <br>
        <a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a>
    </div>

Hope this helps.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599490

You haven't got a field called nombre in your template; you only have empresa.

That's presumably because you don't ouput your EmpModelForm in the template. You don't show your render call in the view, but assuming you pass it as form, you should just do {{ form.as_p }} in the template.

Upvotes: 2

Manpreet Ahluwalia
Manpreet Ahluwalia

Reputation: 331

Try using:

<input type="text" name="nombre">

There is no field named empresa.

Upvotes: 0

Related Questions