Django 表单不使用 ModelChoiceField - ForeignKey 保存

Django form not saving with ModelChoiceField - ForeignKey

我的网站上有多个表单可以工作并将信息保存到我的 PostgreSQL 数据库中。 我正在尝试创建一个表格来保存我的 Set Model 的信息:

class Set(models.Model):
    settitle = models.CharField("Title", max_length=50)
    setdescrip = models.CharField("Description", max_length=50)
    action = models.ForeignKey(Action)
    actorder = models.IntegerField("Order number")

设置表格如下所示。我正在使用 ModelChoiceField 从 Action 模型中提取 Action 名称字段列表,这在表单上显示为 select 下拉列表

class SetForm(ModelForm):

    class Meta:
        model = Set
        fields = ['settitle', 'setdescrip', 'action', 'actorder']
    action = forms.ModelChoiceField(queryset = Action.objects.values_list('name', flat=True), to_field_name="id")

createset 的视图如下:

def createset(request):
    if not request.user.is_authenticated():
        return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
    elif request.method == "GET":
        #create the object - Setform 
        form = SetForm;
        #pass into it 
        return render(request,'app/createForm.html', { 'form':form })
    elif "cancel" in request.POST:
        return HttpResponseRedirect('/actions')
    elif request.method == "POST":
    # take all of the user data entered to create a new set instance in the table
        form = SetForm(request.POST, request.FILES)
        if  form.is_valid():
            form.save()
            return HttpResponseRedirect('/actions')
        else:
            form = SetForm()
            return render(request,'app/createForm.html', {'form':form})

当表单填写有效并按下保存时,没有任何反应。没有错误,页面只是刷新为一个新表单。 如果我不使用 (action = forms.ModelChoiceField(queryset = Action.objects.values_list('name', flat=True), to_field_name= 在 forms.py 中设置操作字段"id")) 然后数据保存,所以这很可能是我做错了什么。只是不确定什么?

https://docs.djangoproject.com/en/stable/ref/forms/fields/#django.forms.ModelChoiceField.queryset

queryset 属性应该是一个 QuerySet。 values_list returns 一个列表。

您应该只定义 Action 模型的 __str__ 方法,而不必重新定义表单中的 action 字段。

如果已设置并且您想使用其他标签,您可以继承 ModelChoiceField。

The __str__ (__unicode__ on Python 2) method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it. For example:

from django.forms import ModelChoiceField

class MyModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id

因此,在您的情况下,要么设置 Action 模型的 __str__ 方法,然后删除表单中的 action = forms.ModelChoiceField(...) 行:

class Action(models.Model):
    def __str__(self):
        return self.name

class SetForm(ModelForm):

    class Meta:
        model = Set
        fields = ['settitle', 'setdescrip', 'action', 'actorder']

或者定义自定义 ModelChoiceField:

class MyModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.name

class SetForm(ModelForm):

    class Meta:
        model = Set
        fields = ['settitle', 'setdescrip', 'action', 'actorder']

    action = MyModelChoiceField(Action.objects.all())