从包含Foreignkey的模型创建编辑表单?

2024-04-29 20:11:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个应用程序,在这个应用程序中我存储了员工的完整信息,现在我开发的问题是,我输入员工的家属时,他添加为家属的人在Person模型中得到一个条目。在

从属和从属关系模型如下所示:

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输入从属项的数据这是用于添加从属项的窗体:

^{pr2}$

我想在编辑表单中显示所有家属的信息以及与员工的关系。那么有没有可能的观点呢。在

任何建议或链接可以帮助我很多。。。。。。。在

提前感谢。。。。。。。。。。。。。。。。。。。。。在


Tags: 模型信息应用程序models员工employeelengthmax
1条回答
网友
1楼 · 发布于 2024-04-29 20:11:14
@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))

正如我在问题中定义了模型表单一样,我创建了一个编辑表单,并传递两个参数,一个是查询为

^{pr2}$

其中第二个id是从属的id

其次,将关系保存在依赖关系模型中,并将其所有属性保存在依赖关系模型中,具有关系的值,并从模型形式中依赖。

所以,通过这种方式,我可以为我的应用程序创建编辑表单。经过长时间的搜索,效果很好。

相关问题 更多 >