1

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.

3
  • Can you post the code you were using to put recipient as initial data in the form? It should work if you use something like form = MyForm(initial={'Recipient':recipient}) Commented Aug 7, 2014 at 4:46
  • It gives me the NameError: name 'recipient' not defined, even though I have "recipient" in the Message model (which is imported). Commented Aug 7, 2014 at 5:24
  • what does the compose view look like? Commented Aug 7, 2014 at 5:29

2 Answers 2

1

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}}   
Sign up to request clarification or add additional context in comments.

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.