我正在尝试使用django构建一个cookbook web-app。您可以创建的收件人可以在您可以创建的几本烹饪书中。这就是为什么' cookbook'是收件人中的ManyToMany字段。 通过创建配方,它会显示多个复选框,您可以在其中查看多个食谱。 保存这个会引发错误说:
ValueError: invalid literal for int() with base 10: 'a'
在views.py
:
def create_recipe(request):
if not request.user.is_authenticated():
return render(request, 'cookbook/login.html')
else:
form = RecipeForm(request.POST or None, request.FILES or None)
if form.is_valid():
recipe = form.save(commit=False)
recipe.user = request.user
recipe.picture = request.FILES['picture']
file_type = recipe.picture.url.split('.')[-1]
file_type = file_type.lower()
if file_type not in IMAGE_FILE_TYPES:
context = {
'recipe': recipe,
'form': form,
'error_message': 'Image file must be PNG, JPG, or JPEG',
}
return render(request, 'cookbook/create_recipe.html', context)
recipe.save()
form.save_m2m()
cookbook = Cookbook.objects.filter(user=request.user)
return render(request, 'cookbook/index.html', {'cookbook': cookbook})
context = {
"form": form,
}
return render(request, 'cookbook/create_recipe.html', context)
在forms.py
:
class RecipeForm(forms.ModelForm):
directions = forms.CharField(widget=forms.Textarea)
ingredients = forms.CharField(widget=forms.Textarea)
class Meta:
model = Recipe
fields = ['title', 'ingredients', 'directions', 'picture', 'cookbooks']
def __init__ (self, *args, **kwargs):
super(RecipeForm, self).__init__(*args, **kwargs)
self.fields["cookbooks"].widget = forms.widgets.CheckboxSelectMultiple()
self.fields["cookbooks"].help_text = ""
self.fields["cookbooks"].queryset = Cookbook.objects.all()