在django中,我已经制作了这个inlineformset_factory,并尝试在其中一个字段中添加一个小部件。但我得到的错误是它缺失了#34; attrs"。然后我添加" attrs"我得到另一个错误,说"意外的关键字参数' attrs'"
这是inlineformset_factory。
UNIT_CHOICES = (('dl', 'dl'), ('l', 'l'), ('kg', 'kg'),)
IngredientFormSet = inlineformset_factory(RecipeModel, Ingredient, can_delete=False, extra=MAX_INGREDIENTS, exclude=[],
widgets={'unit_type': forms.ChoiceField(attrs={}, label="Måleenhet", required=True, widget=forms.Select, choices=UNIT_CHOICES)})
这是我遗漏的东西。
forms.py:
class AddRecipeForm(ModelForm):
products = Product.objects.all()
recipes = RecipeModel.objects.all()
choices = ()
iterate = 1
for product in products:
if not recipes.filter(title=product.name).exists():
choices = ((product.name, product.name),) + choices
iterate += 1
title = forms.ChoiceField(label="Navn på produktet til oppskriften", required=True, widget=forms.Select, choices=choices)
class Meta:
model = RecipeModel
exclude = []
class IngredientForm(ModelForm):
title = forms.CharField(max_length=255, widget=TextInput(attrs={'id': 'ingredient_title',
'class': 'ingredient_class'}))
class Meta:
model = Ingredient
exclude = ['recipe']
views.py
def add_recipe(request):
if request.POST:
form = AddRecipeForm(request.POST)
if form.is_valid():
recipe = form.save(commit=False)
ingredient_formset = IngredientFormSet(request.POST, instance=recipe)
if ingredient_formset.is_valid():
recipe.save()
ingredient_formset.save()
return redirect('admin_site')
else:
return redirect('admin_site')
else:
return redirect('admin_site')
else:
form = AddRecipeForm()
ingredient_formset = IngredientFormSet(instance=RecipeModel())
return render(request, 'admin/add_recipe.html', {
'form': form,
'ingredient_formset': ingredient_formset,
}, context_instance=RequestContext(request))
models.py
class RecipeModel(models.Model):
title = models.CharField("Navn på produktet", max_length=255, default="")
kilogram_bottle = models.FloatField("Kg råvare for et produkt", blank=True)
deciliter_bottle = models.FloatField("Deciliter råvare for et produkt", blank=True)
description = models.TextField("Oppskrifts detaljer", default="")
class Ingredient(models.Model):
recipe = models.ForeignKey(RecipeModel, on_delete=models.CASCADE)
ingredient_title = models.CharField("Navn på ingrediens", max_length=255, default="")
unit_before = models.FloatField("Råvare", blank=True, null=True)
unit_after = models.FloatField("Ferdig behandlet råvare", blank=True, null=True)
unit_type = models.CharField("Måleenhet", max_length=255)
答案 0 :(得分:0)
由于您指定了小部件,因此不必再次指定字段类型。
widgets={
'unit_type': forms.Select
}
但是看起来你正在尝试对该字段做更多的事情,所以你可以创建一个模型表,并将其作为参数传递。
class RecipeForm(forms.ModelForm):
...
forms.ChoiceField(label="Måleenhet", required=True, widget=forms.Select(attrs={}), choices=UNIT_CHOICES)
inlineformset_factory(RecipeModel, Ingredient, form=RecipeForm, can_delete=False, extra=MAX_INGREDIENTS)
You can read more on this topic here
另请注意,attrs
是窗口小部件上的属性,而不是表单字段