首页 > 解决方案 > How do I manipulate text submitted in a Django form?

问题描述

I want the user to be able to input a word, click "submit", and then see their word in all caps on the next page. (This is not my final intention, just a useful way to progress).

views.py:

from django.http import HttpResponse
from django.template import loader
from .models import Word
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import WordForm

def wordinput(request):

    if request.method == 'POST':
        form = WordForm(request.POST)
        if form.is_valid():            
            return HttpResponseRedirect('/thanks/')    
    else:
        form = WordForm()

    return render(request, 'word.html', {'form': form})

def your_word(request):
    form = WordForm()

    if request.method == 'POST': # and form.is_valid():        
        word = WordForm(request.POST)
        word = str(word)
        word = word.upper()
        return HttpResponse(word)   

    else:        
        return HttpResponse("that didn't work")     

forms.py:

from django import forms

class WordForm(forms.Form):
    your_word = forms.CharField(label='Type your word here', max_length=100, required = True)


word.html:

<form action="/wordsearch/your-word/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Search">
</form>

urls.py:

from django.contrib import admin
from django.urls import include, path

from . import views

urlpatterns = [
    path('wordinput/', views.wordinput, name='wordinput'),    
    path('your-word/', views.your_word, name='your_word')
]

Result: TYPE YOUR WORD HERE: ASDF

((In this result, "ASDF" is in a box and manipulable))

Desired result: ASDF

((The desired result is simply on the screen))

标签: pythondjango

解决方案


而不是word = str(word),使用word = str(word.cleaned_data["your_word"]).


推荐阅读