Foreign key의 choice 제한걸기
- 모델폼의 choice를 활용함
Model
class ShopCategory(models.Model):
category = models.CharField(max_length=50, verbose_name='카테고리명')
class Meta:
verbose_name = '카테고리'
verbose_name_plural = verbose_name
class ShopProduct(models.Model):
name = models.CharField(max_length=100, verbose_name='상품이름')
point = models.IntegerField(verbose_name='가격')
category = models.ForeignKey(ShopCategory, on_delete=models.CASCADE, null=True, verbose_name='상품카테고리')
class Meta:
verbose_name = '포인트 제품'
verbose_name_plural = verbose_name
Form
def get_shopcategory_choice():
choices = ShopCategory.objects.all()
return choices
class ShopForm(forms.ModelForm):
class Meta:
model = ShopProduct
fields = ('name', 'point', 'category', )
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'form-control'})
self.fields['point'].widget.attrs.update({'class': 'form-control'})
self.fields['category'].choices = get_shopcategory_choice()
View
class ShopCreateView(generic.CreateView):
template_name = 'help/admin/shop_register.html'
success_url = reverse_lazy('admin-help:shop_list')
model = ShopProduct
fields = ('category', 'name', 'point',)