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:
- Click "Create Report"
- Select the records to be included in the report.
- Hit "Submit" and the report is displayed.
To me I think:
- Load all records.
- 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()
- Return the HTML, expect it back.
- Iterate over all of the fields beginning with 'cid_' and create a list of record ids to be included in the report.
- 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 a开发者_如何学Gopparently this is illegal.
Does anybody have some suggestions?
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>
精彩评论