简体   繁体   中英

How to pre-populate Django form with part of URL?

I'm completely new to programming (Django), and I'm trying to pre-populate a django_messages form with a snippet of the URL.

For example, for a compose form at www.mywebsite.com/compose_root/Chris88 , I want the "Recipient" field to be pre-populated with "Chris88".

Is there any way to do this? In urls.py, I have:

url(r'^compose_root/(<recipient>[\w.@+-]+)/$', compose, name='messages_compose_to'),

I already tried plugging in recipient as an initial in the "Recipient" form field, but it didn't work, so it might be easier just to pre-populate with an excerpt of the URL.

Help is much appreciated.

Assuming you have a form that looks something like:

class New_form(Form.form):
    ... FormStuff
    recipient = Some Field

Add a view that looks like:

def compose_root(request,recipient):
     ...# View Stuff
     form = New_form(initial={"recipient": recipient})
     return render_to_response('form-template.html', {'form':form})

And in your form-template

{{form}}   

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