user3916720
user3916720

Reputation: 11

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.

Upvotes: 1

Views: 1116

Answers (2)

jmark
jmark

Reputation: 1

Assuming you have a DjangoMessages Form class, you can modify the get_form(self) method. Get the form field and set its initial value to the url parameter recipient

class DjangoMessages(Form):

    def get_form(self):
        form = super().get_form()
        form.fields['recipient'].initial = self.kwargs['recipient']

Upvotes: 0

Adam W. Cooper
Adam W. Cooper

Reputation: 74

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

Upvotes: 1

Related Questions