Skip to content

Instantly share code, notes, and snippets.

@Karmak23
Last active August 29, 2015 14:06
Show Gist options
  • Save Karmak23/14d10e00d821f891bddb to your computer and use it in GitHub Desktop.
Save Karmak23/14d10e00d821f891bddb to your computer and use it in GitHub Desktop.

Revisions

  1. Karmak23 revised this gist Sep 26, 2014. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions dynamic_form_attrs.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,6 @@
    import types
    from django import forms

    class DynamicAttrsForm(forms.ModelForm):

    class Meta:
  2. Karmak23 created this gist Sep 26, 2014.
    48 changes: 48 additions & 0 deletions dynamic_form_attrs.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    class DynamicAttrsForm(forms.ModelForm):

    class Meta:
    model = models.DynamicAttrs
    fields = ['template', 'mood', 'text' ]


    def __init__(self, *args, **kwargs):
    super(DynamicAttrsForm, self).__init__(*args, **kwargs)

    # This method generator must leave out of the for loop,
    # and must return an indirected function, else bad things
    # will happen.
    def clean_sample_wrapper(sstype):

    def clean_sample_generic(self):
    sample = self.cleaned_data[sstype]
    if sample.mood != self.cleaned_data['mood']:
    raise forms.ValidationError(
    '%(sstype)s is not a sample of the selected mood!',
    params={'sstype': sstype})

    return sample

    return clean_sample_generic

    for stid, stype in models.SAMPLE_TYPE_CHOICES.items():

    stype = unicode(stype).lower()
    sstype = str(stype)

    queryset = models.Sample.objects.filter(
    is_published=True, conv_status=1, type=stid
    ).order_by('name')

    if self.instance.pk:
    self.fields[sstype] = forms.ModelChoiceField(
    label=stype, queryset=queryset,
    initial=self.instance.sample_set.get(
    sample__type=stid).sample.pk)

    else:
    self.fields[sstype] = forms.ModelChoiceField(
    label=stype, queryset=queryset)

    setattr(self, 'clean_{0}'.format(stype),
    types.MethodType(clean_sample_wrapper(sstype), self))