Django 表单未使用 ModelChoiceField 保存 -foreignkey

2024-02-25

我的网站上有多个表单,可以将信息保存到我的 PostgreSQL 数据库中。 我正在尝试创建一个表单来保存我的设置模型的信息:

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 从操作模型中提取操作名称字段的列表,这在表单上显示为选择下拉列表

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="id")) 在 forms.py 中设置操作字段,则数据将保存,所以这很可能是我做错的地方。只是不确定什么?


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

The queryset属性应该是一个查询集。values_list返回一个列表。

你应该只定义__str__方法,您不必在表单中重新定义操作字段。

如果已设置并且您想使用另一个标签,则可以对 ModelChoiceField 进行子类化。

The __str__ (__unicode__在 Python 2) 上,将调用模型的方法来生成对象的字符串表示形式,以用于字段的选择;提供定制的表示、子类ModelChoiceField并覆盖label_from_instance。此方法将接收一个模型对象,并应返回一个适合表示它的字符串。例如:

from django.forms import ModelChoiceField

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

因此,就您而言,要么设置__str__的方法Action模型,并删除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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django 表单未使用 ModelChoiceField 保存 -foreignkey 的相关文章

随机推荐