def create_invitation(request): if request.method == 'POST': # If the form has been submitted... form = BaseFormSet(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass nombre = form.cleaned_data['NbreInvite'] return HttpResponseRedirect('/admin/') # Redirect after POST else: form = CreateInvitationForm # An unbound form return render_to_response('createinvitation.html', { 'form': form, })# Create your views here.
def add_fields(self, form, index): # We're adding the id field, so we can just call the # BaseFormSet.add_fields if index < self.initial_form_count(): initial = self.queryset[index] else: initial = None self._pk_field = form.fields['id'] = SourceChoiceField(required=False, initial=initial) if initial: form.fields['BULK'] = forms.BooleanField(required=False) BaseFormSet.add_fields(self, form, index)
def __init__(self, data=None, prefix=None, *args, **kwargs): self.prefix = prefix or self.get_default_prefix() if data: self.data = {} # Add management field info # This is hard coded given that none of these keys or info is exportable # This could be a problem point if the management form changes in later releases self.data['%s-TOTAL_FORMS' % self.prefix] = len(data) self.data['%s-INITIAL_FORMS' % self.prefix] = len(data) self.data['%s-MAX_NUM_FORMS' % self.prefix] = 0 # Add correct data for i in range(0, len(data)): prefix = self.add_prefix(i) for field in data[i]: self.data['%s-%s' % (prefix, field)] = data[i][field] BaseFormSet.__init__(self, self.data, self.prefix, *args, **kwargs)
def add_fields(self, form, index): self._pk_field = self.model._meta.pk if form.is_bound: pk_value = form.instance.pk else: try: pk_value = self.get_queryset()[index].pk except IndexError: pk_value = None attrs = dict(app_label=self.model._meta.app_label, modelname=self.model.__name__.lower(), label=unicode(form.instance)) form.fields[self._pk_field.name] = IntegerField( initial=pk_value, required=False, widget=RenderLink(attrs=attrs), label=_("Navigate to:")) BaseFormSet.add_fields(self, form, index)
def total_form_count(self): if self.data or self.files: if hasattr(self.management_form, 'cleaned_data'): return self.management_form.cleaned_data[TOTAL_FORM_COUNT] else: return 0 else: return DjangoBaseFormSet.total_form_count(self)
def __init__(self, data=None, prefix=None, *args, **kwargs): self.prefix = prefix or self.get_default_prefix() if data: self.data = {} # Add management field info # This is hard coded given that none of these keys or info is exportable # This could be a problem point if the management form changes in later releases self.data["%s-TOTAL_FORMS" % self.prefix] = len(data) self.data["%s-INITIAL_FORMS" % self.prefix] = len(data) self.data["%s-MAX_NUM_FORMS" % self.prefix] = 0 # Add correct data for i in range(0, len(data)): prefix = self.add_prefix(i) for field in data[i]: self.data["%s-%s" % (prefix, field)] = data[i][field] BaseFormSet.__init__(self, self.data, self.prefix, *args, **kwargs)
def add_fields(self, form, index): """ over ridden add_field to include uuid in form """ self._pk_field = pk = self.model._meta.pk if form.is_bound: pk_value = form.instance.pk else: try: pk_value = self.get_queryset()[index].pk except IndexError: pk_value = None form.fields[self._pk_field.name] = Field(initial=pk_value, required=False, widget=HiddenInput) if (form.fields).has_key('invoice_terms'): form.fields['invoice_terms'] = forms.ModelChoiceField( InvoiceTerms.objects.all(), empty_label="select") BaseFormSet.add_fields(self, form, index)
def __new__(cls, class_name, bases, attrs): new_class = super(FormSetFactoryMetaClass, cls).__new__(cls, class_name, bases, attrs) meta = new_class._meta declared_fields = meta.declarations if meta.form: fields = { TOTAL_FORM_COUNT: min(meta.form.max_num, meta.form.extra), INITIAL_FORM_COUNT: 0, MAX_NUM_FORM_COUNT: meta.form.max_num } meta.count = meta.form.extra meta.sub_form_factory = construct_factory_from_form(meta.form.form, meta.fields, meta.exclude, meta.settings) fields.update(declared_fields) else: fields = declared_fields meta.prefix = meta.prefix or BaseFormSet.get_default_prefix() meta.declarations = fields return new_class
def __init__(self, *args, **kwargs): BaseFormSet.__init__(self, *args, **kwargs) for form in self.forms: form.empty_permitted = False
def _construct_form(self, i, **kwargs): try: return super(UserLanguagelineFormSet, self)._construct_form(i, **kwargs) except (IndexError, ValueError): return BaseFormSet._construct_form(self, i, **kwargs)
def _construct_form(self, i, **kwargs): if self.is_bound and i < self.initial_form_count(): # Import goes here instead of module-level because importing # django.db has side effects. from django.db import connections pk_field = self.model._meta.pk pk_name = "%s" % pk_field.name pk_key = "%s-%s" % (self.add_prefix(i), pk_name) # HERE IS THE DIFFERENT BIT # (OH, AND THE ABOVE 3 VARIABLES AHVE BEEN MOVED AROUND AND SIMPLIFIED A BIT JUST TO MAKE THE CODE NICER) # (AND DON'T FORGET THAT add_prefix HAS BEEN CHANGED AS NEEDED FOR MetadataModelFormSet) try: pk = self.data[pk_key] except KeyError: # MultiValueDictKeyError: # if I am here then the pk_key was not found in data # given that this is a bound form, # this is probably b/c the form is unloaded # double-check this... initial = self.initial_extra[i] if initial["loaded"] == False: # ...and get the pk another way pk = initial[pk_name] kwargs["initial"] = initial else: # ...if it failed for some other reason, though, raise an error msg = "Unable to determine pk from form w/ prefix %s" % self.add_prefix(i) raise QError(msg) if not pk: # since I am including the "id" field (for other reasons) # if this is a _new_ rather than _existing_ model # then that field will be blank and will be cleaned as u'' # convert that to None, so that get_db_prep_lookup below returns None pk = None # HERE ENDS THE DIFFERENT BIT pk = pk_field.get_db_prep_lookup('exact', pk, connection=connections[self.get_queryset().db]) if isinstance(pk, list): pk = pk[0] kwargs['instance'] = self._existing_object(pk) # SAME LOGIC HERE AS IN MetadataEditingFormSet ABOVE # if i < self.initial_form_count() and not kwargs.get('instance'): if i < self.initial_form_count() and "instance" not in kwargs: try: kwargs['instance'] = self.get_queryset()[i] except IndexError: # if this formset has changed based on add/delete via AJAX # then the underlying queryset may not have updated # if so - since I've already worked out the pk above - just get the model directly # (note that in the case of new models, pk will be None and this will return an empty model) # (which is the desired behavior anyway - see this same bit of code for MetadataEditingFormSet) model_class = self.model kwargs['instance'] = model_class.objects.get(pk=pk) if i >= self.initial_form_count() and self.initial_extra: # Set initial values for extra forms try: kwargs['initial'] = self.initial_extra[i-self.initial_form_count()] except IndexError: pass # rather than call _construct_form() from super() here (which winds up calling BaseModelFormset), # I explicitly call it from BaseFormSet; # the former repeates the above "get instance" code w/out handling loaded & unloaded forms # since I've already done that, I just want to call the code that builds the actual form form = BaseFormSet._construct_form(self, i, **kwargs) if self.save_as_new: # Remove the primary key from the form's data, we are only # creating new instances form.data[form.add_prefix(self._pk_field.name)] = None # Remove the foreign key from the form's data # TODO: WHY IS THIS HAPPENING? # TODO: I ASSUME B/C INLINE_FORMSETS AUTOMATICALLY HANDLE FK FIELDS? form.data[form.add_prefix(self.fk.name)] = None # Set the fk value here so that the form can do its validation. setattr(form.instance, self.fk.get_attname(), self.instance.pk) return form
def _construct_form(self, i, **kwargs): try: return super(UserLanguagelineFormSet, self). _construct_form(i, **kwargs) except (IndexError, ValueError): return BaseFormSet._construct_form(self, i, **kwargs)
def initial_form_count(self): if self.data or self.files: cleaned_data = getattr(self.management_form, 'cleaned_data', {}) return cleaned_data.get(INITIAL_FORM_COUNT, 0) else: return DjangoBaseFormSet.initial_form_count(self)
def _construct_form(self, i, **kwargs): if self.is_bound and i < self.initial_form_count(): # Import goes here instead of module-level because importing # django.db has side effects. from django.db import connections pk_field = self.model._meta.pk pk_name = "%s" % pk_field.name pk_key = "%s-%s" % (self.add_prefix(i), pk_name) # HERE IS THE DIFFERENT BIT # (OH, AND THE ABOVE 3 VARIABLES HAVE BEEN MOVED AROUND AND SIMPLIFIED A BIT JUST TO MAKE THE CODE NICER) # (AND DON'T FORGET THAT add_prefix HAS BEEN CHANGED AS NEEDED FOR MetadataModelFormSet) try: pk = self.data[pk_key] except KeyError: # MultiValueDictKeyError: # if I am here then the pk_key was not found in data # given that this is a bound form, # this is probably b/c the form is unloaded # double-check this... initial = self.initial_extra[i] if initial["loaded"] == False: # ...and get the pk another way pk = initial[pk_name] kwargs["initial"] = initial else: # ...if it failed for some other reason, though, raise an error msg = "Unable to determine pk from form w/ prefix %s" % self.add_prefix(i) raise QError(msg) if not pk: # since I am including the "id" field (for other reasons) # if this is a _new_ rather than _existing_ model # then that field will be blank and will be cleaned as u'' # convert that to None, so that get_db_prep_lookup below returns None pk = None # HERE ENDS THE DIFFERENT BIT pk = pk_field.get_db_prep_lookup('exact', pk, connection=connections[self.get_queryset().db]) if isinstance(pk, list): pk = pk[0] kwargs["instance"] = self._existing_object(pk) # I LIED; HERE IS ONE MORE DIFFERENT BIT # this bit of code exists in case instance has not been set # but the above changes will set it to None in the case of new models # so get() below will return None; I want to check not that "instance" is None # but that it hasn't been set (ie: is not in kwargs) # if i < self.initial_form_count() and not kwargs.get('instance'): if i < self.initial_form_count() and "instance" not in kwargs: kwargs['instance'] = self.get_queryset()[i] # HERE ENDS THE ONE MORE DIFFERENT BIT if i >= self.initial_form_count() and self.initial_extra: # Set initial values for extra forms try: kwargs['initial'] = self.initial_extra[i-self.initial_form_count()] except IndexError: pass # rather than call _construct_form() from super() here (which winds up calling BaseModelFormset), # I explicitly call it from BaseFormSet; # the former repeates the above "get instance" code w/out handling loaded & unloaded forms # since I've already done that, I just want to call the code that builds the actual form form = BaseFormSet._construct_form(self, i, **kwargs) return form