def render(self, context): form = self.form.resolve(context, True) hidden_fields_errors = ErrorDict() for field in form.hidden_fields(): if field.errors: hidden_fields_errors.update({field.name: field.errors}) context[self.as_var] = hidden_fields_errors return ''
def render(self, context): """Render.""" form = self.form.resolve(context, True) hidden_fields_errors = ErrorDict() for field in form.hidden_fields(): if field.errors: hidden_fields_errors.update({field.name: field.errors}) context[self.as_var] = hidden_fields_errors return ''
def post(self, request, *args, **kwargs): print(request.POST) response_dict = {} if request.POST.get('form_key') == 'edit_profile': form_a = self.user_form(pk=request.user.pk, data=request.POST) form_b = self.profile_form(user=request.user, data=request.POST) errors = ErrorDict() if form_a.errors: errors.update(form_a.errors) if form_b.errors: errors.update(form_b.errors) if not (form_a.is_valid() and form_b.is_valid()): response_dict.update({ 'status': 0, 'message': errors.as_ul() }) elif authenticate(username=request.user.username, password=request.POST.get('password')): u1 = form_a.save() u2 = form_b.save() response_dict.update({ 'status': 1, 'message': 'User was successfully updated.', 'instance': { 'username': u1.username, 'email': u1.email, 'about_me': u2.about_me, } }) else: response_dict.update({ 'status': 0, 'message': 'Password is incorrect.' }) return HttpResponse(json.dumps(response_dict, cls=DjangoJSONEncoder)) elif request.POST.get('form_key') == 'change_pw': form = self.password_form(pk=request.user.pk, data=request.POST) if not form.is_valid(): response_dict.update({ 'status': 0, 'message': form.errors.as_ul() }) elif authenticate(username=request.user.username, password=request.POST.get('old_password')): form.save() response_dict.update({ 'status': 1, 'message': 'Password was successfully updated.' }) else: response_dict.update({ 'status': 0, 'message': 'Old password is incorrect.' }) return HttpResponse(json.dumps(response_dict, cls=DjangoJSONEncoder)) return super(ProfileView, self).get(request, *args, **kwargs)
class NestedFormMixinBase(object): """ Allows a form to contain multiple and optional nested forms. The form configurations are defined in nested_form_configs and is defined by instances of NestedFormConfig """ nested_form_configs = [] def __init__(self, *args, **kwargs): super(NestedFormMixinBase, self).__init__(*args, **kwargs) # Build a list of all nest form configs self.nested_forms = [] # Keep track of form prefixes to guarantee multiple of the same form are properly prefixed form_prefixes = {} for nested_form_config in self.nested_form_configs: # Deep copy the form kwargs to pass to each form instance form_kwargs = deepcopy(kwargs) prefix = nested_form_config.field_prefix # Check if this form class already exists if nested_form_config.cls in form_prefixes: # Make sure both have a prefix value if not form_prefixes[ nested_form_config. cls] or not nested_form_config.field_prefix: raise ValidationError( 'Form {0} must have a field prefix'.format( nested_form_config.cls.__name__)) # Set the prefix value to the form config prefix form_prefixes[ nested_form_config.cls] = nested_form_config.field_prefix # Process the form field keys when there is a prefix defined on the nested form if form_kwargs.get('data') and prefix: for prefixed_key, value in deepcopy( form_kwargs['data']).items(): # Check if the prefix is there to replace to_replace = '{0}_'.format(prefix) if prefixed_key.startswith(to_replace): # Replace the prefix key = prefixed_key.replace(to_replace, '') form_kwargs['data'][key] = value # Get rid of the prefixed key form_kwargs['data'].pop(prefixed_key) # Create the form instance and pass the form data nested_form_config.set_instance(*args, **form_kwargs) # Add the form config to the list of nested form configs self.nested_forms.append(nested_form_config) def get_pre_save_method_kwargs(self): # pragma: no cover """ Optionally return a dict of data that will be passed through the chain of save methods with pre-forms, parent form, and post-forms """ return {} def get_post_save_method_kwargs(self, **kwargs): # pragma: no cover """ Optionally return a dict of data that will be passed to the post-forms. All previous form data will be available here including pre-save data and parent form save data. """ return kwargs def get_required_forms(self): """ Checks which forms are required based on the params and returns a list of only the required forms :rtype: list of NestedFormConfig """ return [ nested_form for nested_form in self.nested_forms if self.form_is_required(nested_form) ] def save_form(self, **kwargs): """ Hook for the parent form to save an object so that it doesn't override the mixin's save method and logic. """ return None def form_is_required(self, nested_form): """ Handles the logic to check if an individual form is required """ if nested_form.required: return True # Get the required flag value return self.cleaned_data.get(nested_form.required_key) def full_clean(self): """ Cleans all of self.data and populates self._errors and self.cleaned_data. This is copied from django with an addition at the bottom """ # This is the django code self._errors = ErrorDict() if not self.is_bound: # pragma: no cover return self.cleaned_data = {} if self.empty_permitted and not self.has_changed(): # pragma: no cover return self._clean_fields() self._clean_form() self._post_clean() # This is the additional code that updates the form's errors with the nested form's errors required_forms = self.get_required_forms() for form in required_forms: self._errors.update(form.instance.errors)
def errors(self): _errors = ErrorDict() for form in self._subforms: _errors.update({self._get_error_key(form.prefix, name): error for name, error in form.errors.items()}) return _errors
def errors(self): errors = ErrorDict() for form_class, form in self.forms.items(): errors.update(form.errors) return errors