如何将模板中的输入发送到django中的视图

时间:2016-09-24 13:21:42

标签: django templates views

我需要一些帮助。我是django的新人。我想得到输入并将其打印在第二个textarea中。我试过但真的不知道我该怎么做。 我知道我错了,但不知道如何解决它并做到这一点。帮助!

这是我的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>

这是我的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})

这是我的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), ]

1 个答案:

答案 0 :(得分:1)

您应该创建不在模板中的表单,但您必须在视图中创建它并将其传递给模板。

阅读Forms

forms.py中的示例表单:

from django import forms

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

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})

示例模板文件:

<!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>