Reb*_*Rol 3 django foreign-keys save django-models django-forms
我的网站上有多个表单可以工作并将信息保存到我的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")
Run Code Online (Sandbox Code Playgroud)
Set Form看起来像这样.我正在使用ModelChoiceField从Action模型中提取Action名称字段列表,它在表单上显示为选择下拉列表
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")
Run Code Online (Sandbox Code Playgroud)
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})
Run Code Online (Sandbox Code Playgroud)
当表单填写并且有效且按下Save时,没有任何反应.没有错误,页面只刷新到新表单.如果我没有使用(action = forms.ModelChoiceField(queryset = Action.objects.values_list('name',flat = True),to_field_name ="id"))在forms.py中设置action字段,那么数据保存,所以这可能是我做错事的地方.只是不确定是什么?
https://docs.djangoproject.com/en/stable/ref/forms/fields/#django.forms.ModelChoiceField.queryset
该queryset属性应该是QuerySet.values_list返回一个列表.
您应该只定义__str__Action模型的方法,而不必重新定义表单中的action字段.
如果已设置并且您想要使用其他标签,则可以继承ModelChoiceField.
将调用模型的
__str__(__unicode__在Python 2上)方法来生成对象的字符串表示,以便在字段的选择中使用; 提供自定义表示,子类ModelChoiceField和覆盖label_from_instance.此方法将接收模型对象,并应返回适合表示它的字符串.例如:Run Code Online (Sandbox Code Playgroud)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']
Run Code Online (Sandbox Code Playgroud)
或者定义自定义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())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1565 次 |
| 最近记录: |