def get_form(request, form_class, field_order, bound=False): """ Generic function. Used for all submission types. Specify the ``form_class`` that's given in ``forms.py``. The ``field_order`` is a list of strings that indicates the linear order of the fields in the form. A ``bound`` form is a function of the object assigned to ``bound`` (see below). An unbound form is simply an empty form. """ if bound: if isinstance(bound, models.Revision): tags = ','.join([str(tag) for tag in bound.tags.all()]) fields = {'item_url': bound.item_url, 'title': bound.title, 'description': bound.description, 'sub_tags': tags, 'snippet_code': bound.item_code, 'sub_type': 'snippet', 'sub_license': bound.sub_license_id, } if bound.entry.sub_type == 'link': fields['sub_type'] = 'link' elif bound.entry.sub_type == 'package': fields['sub_type'] = 'package' elif bound.entry.sub_type == 'code': fields['sub_type'] = 'snippet' form_output = form_class(fields) else: if request.POST['sub_type'] == 'package': # Create a fake "UploadedFile" object, so the user can resume # editing or finish their submission, without being told # they have to reenter this field. zip_hash = request.POST.get('package_hash', '') zip_file = models.ZipFile.objects.filter(zip_hash=zip_hash) if zip_file: zip_name = zip_file[0].raw_zip_file.name uploaded_file = UploadedFile(zip_name, name=zip_name, content_type='application/zip', size=zip_file[0].raw_zip_file.size) uploaded_file.skip_validation = True # see ``forms.py`` request.FILES['package_file'] = uploaded_file form_output = form_class(request.POST, request.FILES) if request.POST['sub_type'] == 'package' and zip_file: form_output.fields['package_file'].initial = uploaded_file else: form_output = form_class() # Rearrange the form order form_output.fields.keyOrder = field_order index = 1 for field_name, field in form_output.fields.iteritems(): field.widget.attrs['tabindex'] = str(index) index += 1 if request.user.is_authenticated(): # Email field not required for signed-in users form_output.fields.pop('email') return form_output