How to provide initial form data from fk

Asked by Antonius Dali

Hi there,

I'd like to be able to provide some initial form data... but I'm not sure how to go about it with the crud views. Furthermore, the initial data is coming from the request url - see below.

As you might see below, JobRecord is the fk to Activity, which is listed in the Activity model.

...
jobrecord_activity_create = CreateObjectView(model = Activity,
                            extra_context = info_dict,
                            form_initial = { 'jobrecord': JobRecord.objects.get(pk=request.object_id)}
                            )
...
url(
        r'^jobrecord/(?P<object_id>[a-zA-Z0-9_\-]+)/activity/create/$',
        jobrecord_activity_create,
        name="jobrecord_activity_create_url"
 ),

Best thanks for the project, and help.

Daryl

Question information

Language:
English Edit question
Status:
Answered
For:
Softwarefabrica django crud Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
Marco Pantaleoni (marco-pantaleoni) said :
#1

Hi Daryl,
I would do:

def jobrecord_activity_create(request, object_id):
    jobrecord = JobRecord.objects.get(pk=request.object_id)
    create_view = CreateObjectView(mode = Activity)
    return create_view(request, extra_context = info_dict,
                                    form_initial = { 'jobrecord': jobrecord, })
...
 url(
         r'^jobrecord/(?P<object_id>[a-zA-Z0-9_\-]+)/activity/create/$',
         jobrecord_activity_create,
         name="jobrecord_activity_create_url"
  ),

(this because 'create_view' acts as a callable, invoking CreateObjectView.__call__. Since the extra_context and form_initial change between every view invocation, you have to pass them to the __call__ method, or its procedural counterpart in other words, and not when creating the view instance).
Please note that above you can also move outisde the "create_view = CreateObjectView(...)" part if you want.

Cheers,
Marco

Can you help with this problem?

Provide an answer of your own, or ask Antonius Dali for more information if necessary.

To post a message you must log in.