简体   繁体   中英

Django 1.9.4 Get input data from form to show into a different template

Here is my code that I believe pertains to this situation. I'm sorry, I'm new to django.

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import SearchForm

def result_one(request):
        return render(request, "testresult.html", {})

def get_results(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
           return HttpResponseRedirect('/result/')
    else:
        form = SearchForm()
    return render(request, 'index.html', {'form': form})

urls.py

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^search/$', "search.views.get_results"),
    url(r'^result/$', "search.views.result_one"),
]

forms.py

from django import forms

class SearchForm(forms.Form):
    client_group_number=forms.IntegerField(label='Group Number', widget=forms.TextInput(attrs={'placeholder': 'Group Number'}))

From my understanding, what I believe should happen is that an input will be put into a html page. When the user hits submit, the input gets saved into forms.py as data. This data gets manipulated in views.py which gets displayed in a different html page. (I hope this is correct)

What I want it to do is take in an input for client_group_number(in forms.py) from index.html(for example: 123), that can be accessed in views.py and displayed in another html template that I have called testresult.html, which would display Group Number = 123 (the 123 coming from either the forms.py or views.py).

This might be a very simple thing to accomplish and I apologize if it is, but I can't seem to find what I need on the internet.

Django validate the form input data in the cleaned_data dictionary. You would need to pass this to the new template either as arguments in the redirect or using session. Here is one simple example to give you an idea, there are probably better ways.

if form.is_valid():
  group_number = form.cleaned_data["client_group_number"]
  HttpResponseRedirect("/result/?group_number=" + group_number)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM