我正在创建一个应用程序,我在那里存储员工的完整信息,现在我的开发问题是我以这样一种方式进入员工的家属,他作为受抚养者添加的人在人员中获得了一个条目模型。
依赖和依赖关系模型看起来像:
class Dependent(Person):
"""Dependent models: dependents of employee"""
occupation = models.CharField(_('occupation'), max_length=50, null=True,
blank=True)
self_dependent = models.BooleanField(_('self dependent'))
class DependentRelation(models.Model):
"""Dependent Relation Model for Employee"""
employee = models.ForeignKey(Employee, verbose_name=_('employee'))
dependent = models.ForeignKey(Dependent, verbose_name=_('dependent'))
relationship = models.CharField(_('relationship with employee'),
max_length=50)
class Meta:
ordering = ('employee', 'dependent',)
unique_together = ('employee', 'dependent' )
我正在使用ModelForm输入依赖项的数据,这是添加依赖项的形式:
class DependentForm(forms.ModelForm):
relationship = forms.CharField(_('relationship')) # TODO: max_length??
class Meta:
model = Dependent
我想在编辑表单中显示所有Dependent的信息以及与员工的关系。那么有可能的观点。
任何建议或链接都可以帮助我很多.......
提前致谢.....................
答案 0 :(得分:0)
@login_required
def edit_dependents(request, id):
employee = request.user.get_profile()
try:
dependent = employee.dependent.get(id=id)
except Dependent.DoesNotExist:
messages.error(request, "You can't edit this dependent(id: %s)." %id)
return HttpResponseRedirect(reverse('core_show_dependent_details'))
dependent_relation = DependentRelation.objects.get(dependent=dependent, employee=employee)
if request.method == "POST":
form = DependentForm(data=request.POST, instance=dependent)
if form.is_valid():
dependent = form.save(commit=False)
dependent_relation = DependentRelation.objects.get(dependent=dependent, employee=employee)
dependent_relation.relationship = form.cleaned_data['relationship']
try:
dependent_relation.full_clean()
except ValidationError, e:
form = DependentForm(data=request.POST)
dependent.save()
dependent_relation.save()
return HttpResponseRedirect(reverse('core_show_dependent_details'))
else:
form = DependentForm(instance=dependent,
initial={'relationship': dependent_relation.relationship})
dictionary = {'form':form,'title':'Edit Dependents',}
return render_to_response('core/create_edit_form.html',dictionary, context_instance = RequestContext(request))
正如我在我的问题中定义了我的模型表单,我创建了一个编辑表单,同时传递了两个参数,一个是依赖人的实例,查询为
dependent = employee.dependent.get(id = id)
其中第二个id是从属的id。
其次,我在DependentRelationship模型中保存了它的所有属性,具有关系值,并且依赖于ModelForm。
因此,通过这种方式,我可以为我的应用创建编辑表单。经过长时间的搜索,这是很好的。