Mehdi
Mehdi

Reputation: 21

How to send input from template to a view in django

I need some help. I'm a new in django. I want to get the input and print it in the second textarea. I tried but really don't know how can I do it. I know that I'm wrong but don't know how to fix it and do it. help!

This is my index.html

 <form method='POST' action=''> 
   <tr><td align="left"> question: </td>
   <td colspan="5">
   <input name="quest" type="text" value= "{{quest}}" size="40"  
 maxlength="200" value=""><font color="DimGray" size="2"> ask yr question:</font> </td>
   </tr><tr><td></td><td></td></tr>
   <tr><td height="23"></td></tr>
   <tr><td></td>
   <br><button type="submit">Search</button> {% csrf_token %}   
 </form>

 <td align="left"> le passage </td>

 <FORM>
   <TEXTAREA name="nom" rows=4 cols=40>{{res}}</TEXTAREA>
 </FORM>
<td align="left"> les textes </td>

 <FORM>
   <TEXTAREA name="nom" rows=4 cols=40>{{aff}}</TEXTAREA>
 </FORM>

This is my views.py

from django.shortcuts import render

def affich(request):
if request.method == 'POST':
    question = request.POST['quest']
    var = question.POST.get('value')
    aff = var.get_value()
return render(request,"index.html",{'aff': aff})

This is my urls.py

from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^index/','journal.views.affich',name='index'),
url(r'^admin/', admin.site.urls), ]

Upvotes: 0

Views: 2126

Answers (1)

Cagatay Barin
Cagatay Barin

Reputation: 3496

You should create the form not in your template, but you have to create it in your view and pass it to the template.

Read Forms

Example form in forms.py:

from django import forms

class ExampleForm(forms.Form):
    field = forms.CharField(label='Message', max_length=80)

Example view in views.py:

from django.shortcuts import render
from django.http import HttpResponse
from .forms import ExampleForm

def example_view(request):
    if request.method == 'POST':
        form = ExampleForm(request.POST)
        if form.is_valid():
            field1 = form.cleaned_data['field1']
            # Do what you gotta do.
            return HttpResponse("")
    else:
        form = ExampleForm()
        return render(request, 'template.html', {'form': form})

Example template file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Your Example Form</title>
</head>
<body>
    <form class="ExampleForm" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>
</body>
</html>

Upvotes: 1

Related Questions