-
-
Save patrys/1123933 to your computer and use it in GitHub Desktop.
satchless model example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
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): | |
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 __init__(self, *args, **kwargs): | |
super(ShoeVariantForm, self).__init__(*args, **kwargs) | |
used_colors = self.product.variants.values_list('color', flat=True).distinct() | |
color_choices = [(k, v) | |
for k, v in models.ShoeVariant.COLOR_CHOICES | |
if k in used_colors] | |
self.fields['color'].choices = color_choices | |
used_sizes = self.product.variants.values_list('size', flat=True).distinct() | |
size_choices = [(k, v) | |
for k, v in models.ShoeVariant.SIZE_CHOICES | |
if k in used_sizes] | |
self.fields['size'].choices = 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("We are sorry but we don't carry this" | |
" particular color and size combination") | |
return self.cleaned_data | |
def get_variant(self): | |
return self._get_variant_queryset().get() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment