Django框架:使用save_m2m()方法在表单中保存ManyToMany字段会引发错误

时间:2017-06-15 11:50:52

标签: python django many-to-many

我正在尝试使用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()

0 个答案:

没有答案