Skip to content

Instantly share code, notes, and snippets.

@octaflop
Created August 3, 2011 22:11
Show Gist options
  • Save octaflop/1123931 to your computer and use it in GitHub Desktop.
Save octaflop/1123931 to your computer and use it in GitHub Desktop.

Revisions

  1. octaflop created this gist Aug 3, 2011.
    38 changes: 38 additions & 0 deletions forms.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    from satchless.forms.widgets import DecimalInput
    from satchless.product.forms import BaseVariantForm
    from . import models

    class ProductPriceForm(forms.ModelForm):
    class Meta:
    widgets = {
    'price': DecimalInput(min_decimal_places=2),
    }

    class ShoeVariantForm(BaseVariantForm):
    def __init__(self, *args, **kwargs):
    super(ShoeVariantForm, self).__init__(*args, **kwargs):
    self.fields['color'].choices =
    [
    (k,v) for k,v in models.ShoeVariant.COLOR_CHOICES if k in
    self.product.variants.values_list('color', flat=True).distinct()
    ]

    color = forms.CharField(
    max_length=10,
    widget=forms.Select(choices=models.ShoeVariant.COLOR_CHOICES))
    size = forms.CharField(
    max_length=6,
    widget=forms.Select(choices=models.ShoeVariant.SIZE_CHOICES))
    def _get_variant_queryset(self):
    return models.ShoeVariant.objects.filter(
    product=self.product,
    color=self.cleaned_data['color'],
    size=self.cleaned_data['size'],
    )
    def clean(self):
    if not self._get_variant_queryset().exists():
    raise forms.ValidationError("Variant does not exist")
    return self.cleaned_data

    def get_variant(self):
    return self._get_variant_queryset().get()