我对modelformset自定义字段有问题可以这么说。这是到目前为止的代码,它工作正常:
models.py:
class Workplace(models.Model):
user = models.ForeignKey(User)
description = models.TextField(blank=True, null=True)
organization = models.ForeignKey(Organization)
position = models.CharField(max_length=250, null=True)
start = models.DateTimeField(null=True, blank=True)
end = models.DateTimeField(null=True, blank=True)
place = models.ForeignKey(Place, null=True, blank=True)
deleted = models.BooleanField(default=False)
forms.py:
class UserWorkplaceForm(forms.ModelForm):
class Meta:
model = Workplace
labels = {
'deleted': 'Delete this position'
}
def __init__(self, *args, **kwargs):
super(UserWorkplaceForm, self).__init__(*args, **kwargs)
self.fields['position'].required = True
self.fields['organization'].required = True
self.fields['start'].required = True
views.py:
def settings_workplace(request):
workplace_formset = modelformset_factory(Workplace,
form=UserWorkplaceForm,
fields=('user', 'position', 'organization', 'start', 'end', 'deleted'),
widgets={'user': forms.HiddenInput(),
'start': forms.DateInput(attrs={'class': 'workplace-date'}),
'end': forms.DateInput(attrs={'class': 'workplace-date'}),
'deleted': forms.CheckboxInput(),
'organization': forms.TextInput()
},
extra=0)
if request.method == "POST":
formset = workplace_formset(request.POST)
if formset.is_valid():
formset.save()
formset = workplace_formset(queryset=request.user.get_profile().workplace.filter(deleted=False))
else:
formset = workplace_formset(queryset=request.user.get_profile().workplace.filter(deleted=False))
context = {
'formset': formset
}
return render_to_response('accounts/settings_workplaces.html', context, RequestContext(request))
'组织'字段呈现为Select HTML元素。我无法做到这一点,因为数据库中有数千个组织。我想要做的是将组织显示为文本字段。这就是我在小部件中所做的。但是,这给了我字段的ID,通常不是名称。 我有办法同时获得两者吗?我需要一个更好的显示名称,我需要ID以防情况编辑(在不同的字段上),因为该字段是必需的。
有什么想法吗?
答案 0 :(得分:0)
您可以将其设为ChoiceField
,其中第一个值是组织的ID,第二个值是组织的人类可读名称吗?这是我建议处理这种情况。以下是关于在Django中设置“选择”的文档:
https://docs.djangoproject.com/en/1.7/ref/forms/fields/#choicefield
https://docs.djangoproject.com/en/1.7/ref/models/fields/#choices