Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

python - Can I have a Django form without Model

Can I have a Form in my template which is not backed by a model. I do not need to store the data just need that data to generate a POST request of my own in the view.

Template - The form with text fields. View - get data from form, and generate another request.

Flow --> Form submit takes to a url which calls the view "

def form_handle(request):
    if request.method=='POST'
    form = request.POST

    #blah blah encode parameters for a url blah blah 
    #and make another post request

but this puts only the csrf token into the form variable. Is there some way I can access those text fields of the template in my form_handle view?

I know how to do it with a model but couldn't figure this out!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes. This is very much possible. You can read up on Form objects. It would be the same way you would treat a ModelForm, except that you are not bound by the model, and you have to explicitly declare all the form attributes.

def form_handle(request):
    form = MyForm()
    if request.method=='POST':
        form = MyForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            #now in the object cd, you have the form as a dictionary.
            a = cd.get('a')

    #blah blah encode parameters for a url blah blah 
    #and make another post request
    #edit : added ": "  after    if request.method=='POST'

and

class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm
    a = forms.CharField(max_length=20)
    #All my attributes here

In the template:

<form action="{% url form_handle %}" method="POST">{% csrf_token %}
    {{form.as_p}}
    <button type="submit">Submit</button>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...