Django表单不保存与ModelChoiceField - ForeignKey [英] Django form not saving with ModelChoiceField - ForeignKey

查看:671
本文介绍了Django表单不保存与ModelChoiceField - ForeignKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有多个表单,可以将信息保存到我的PostgreSQL数据库中。
我想创建一个表单来保存我的集合模型的信息:
$ b $ pre codelass 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)

Set Form看起来像这样。我使用ModelChoiceField从Action模型中提取Action名称字段的列表,它将在表单上显示为select下拉列表。

  class SetForm(ModelForm):

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

createset的视图如下:

  def createset(request):
如果不是request.user.is_authenticated():
return redirect('%s?next =%s'%(settings.LOGIN_URL,request.path))
elif request.method ==GET :
#创建对象 - Setform
form = SetForm;
#pass
return request(request,'app / createForm.html',{'form':form})
elifcancelrequest.POST:
返回HttpResponseRedirect('/ actions')
elif request.method ==POST:
#获取所有输入的用户数据,在表中创建一个新的实例
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})

当表格被填写并且有效且保存被按下时,没有任何反应。没有错误,页面只是刷新到一个新的形式。
如果我没有在forms.py中使用(action = forms.ModelChoiceField(queryset = Action.objects.values_list('name',flat = True),to_field_name =id))来设置action字段,数据保存,所以这可能是我在做错事的地方。只是不知道是什么?

解决方案

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



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



您应该定义 __ str __ 你的Action模型的方法,你不需要重新定义表单中的action字段。



如果设置了它并且想要使用另一个标签,可以子类ModelChoiceField。

lockquote
__ str __ __ unicode __ on Python 2)模型的方法将被调用来生成对象的字符串表示以供字段的选择使用;提供定制的表示,子类 ModelChoiceField 并覆盖 label_from_instance 。这个方法将接收一个模型对象,并且应该返回一个适合于表示它的字符串。例如:

  from django.forms import ModelChoiceField 
$ b $ class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self,obj):
returnMy Object#%i%obj.id




因此,对于你的情况,要么设置 __ str __ 方法 Action model,然后移除表单中的 action = forms.ModelChoiceField(...)行:

<$ p $ (Model.Model):
def __str __(self):
返回self.name
$ b $ class SetForm(ModelForm):

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



或者定义一个自定义的ModelChoiceField:

  class MyModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self,obj):
return obj.name
$ b $ class SetForm(Mo delForm):

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

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


I have multiple forms on my site that work and save info to my PostgreSQL database. I am trying to create a form to save information for my 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")

The Set Form looks like this. I am using ModelChoiceField to pull a list of Action name fields from the Action model, this displays on the form as a select dropdown

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")

The view for createset is below:

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})

When the form is filled in and valid and Save is pressed, nothing happens. No errors, the page just refreshes to a new form. If I don't set the action field in forms.py using (action = forms.ModelChoiceField(queryset = Action.objects.values_list('name', flat=True), to_field_name="id")) then the data saves, so that is likely where I am doing something wrong. Just not sure what?

解决方案

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

The queryset attribute should be a QuerySet. values_list returns a list.

You should just define the __str__ method of your Action model and you won't have to redefine the action field in the form.

If it is set and you want to use another label, you can subclass 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

So, in your case, either set the __str__ method of Action model, and remove the action = forms.ModelChoiceField(...) line in your form:

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

class SetForm(ModelForm):

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

Or either define a custom 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())

这篇关于Django表单不保存与ModelChoiceField - ForeignKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆