views:

40

answers:

1

Hello,

I have a system which keeps lots of "records" and need to integrate a component which will produce reports of any selected records.

To the user, it looks like this:

  1. Click "Create Report"
  2. Select the records to be included in the report.
  3. Hit "Submit" and the report is displayed.

To me I think:

  1. Load all records.
  2. Create a ReportForm which produces a "BooleanField" by iterating over all of the records from part 1 and using code like: self.fields['cid_' + str(record.id)] = BooleanField()
  3. Return the HTML, expect it back.
  4. Iterate over all of the fields beginning with 'cid_' and create a list of record ids to be included in the report.
  5. Pass the numbers to the report generator.

But from within the view I cannot access the form data the only way I can imagine doing it. Since I don't know which Record IDs will be available (since some may have been deleted, etc) I need to access it like this:

{{form.fields['cid_'+str(record.id)']}}

But apparently this is illegal.

Does anybody have some suggestions?

+1  A: 

If I understand your question correctly, your answer lies in using the proper Django form widgets. I will give you an example. Let's say you have a Django model: -

class Record(models.Model):
    name = models.CharField()

Let's say you create a custom Form for your needs: -

class MyCustomForm(forms.Form):
    records= forms.ModelMultipleChoiceField(queryset=Record.objects.all, widget=forms.CheckboxSelectMultiple)

Let's say you have the following view: -

def myview(request):
    if request.method == 'POST':
        form = MyCustomForm(data=request.POST)
        if form.is_valid():
            #do what you want with your data
            print form.cleaned_data['records']
            #do what you want with your data
    else:
        form = MyCustomForm()
    return render_to_response('mytemplate.html', {'form': form}, context_instance=RequestContext(request))

Your mytemplate.html might look like this: -

<div>
    {{ form.records.label_tag }}
    {{ form.records }}
</div>
chefsmart