Django:创建类似于管理界面的内联表单集 [英] Django: Creating an Inline Formset Similar to the Admin Interface

查看:125
本文介绍了Django:创建类似于管理界面的内联表单集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django新手,我对在生产代码中重用管理界面的内联表单集有疑问。考虑以下模型:

I'm a Django newbie, and I have a question about reusing the inline formset of the admin interface in the production code. Consider the following model:

class Attribute(models.Model):
    name       = models.CharField(max_length=50)

class Person(models.Model):
    lastName   = models.CharField(max_length=50)
    firstName  = models.CharField(max_length=50)
    email      = models.CharField(max_length=50)
    attributes = models.ManyToManyField(Attribute, through='AttributeValue')

class AttributeValue(models.Model):
    person     = models.ForeignKey(Person, on_delete=models.CASCADE)
    attribute  = models.ForeignKey(Attribute, on_delete=models.PROTECT)
    isConsumer = models.BooleanField()
    value      = models.CharField(max_length=50)

管理界面非常漂亮。我使用了以下admin.py:

The admin interface for this comes out beautifully. I used the following admin.py:

class AttributeValueInline(admin.TabularInline):
    model = AttributeValue
    extra = 3

class PersonAdmin(admin.ModelAdmin):
    list_display = ('lastName', 'firstName','email')
    fieldsets = [
       ('Name',        {'fields': ['firstName', 'lastName']}),
       ('Contact Info',{'fields': ['email','phoneNumber']})
    ]
    inlines = [AttributeValueInline]

admin.site.register(Person, PersonAdmin)
admin.site.register(Attribute)

这几乎正是我想要的。看起来像这样:

This is almost exactly what I want. It looks like this:

当我试图在非管理员网站中实现相同功能时,除了实际的业务逻辑之外,我不得不编写大量代码来进行内联表单集,表单处理。除此之外,我还遇到了此处所提到的问题。

When I tried to implement the same in the non-admin website, I had to write quite a bit of code to do the inline formsets, form processing, in addition to the actual business logic. In addition to this, I faced the problem mentioned here.

我无法向最终用户公开管理界面,因为我们需要定制的Web设计和页面流。但是,我可以重用管理界面代码的一部分而不是重新实现相同的功能吗?

I can't expose the admin interface to the end-user because we need to have a customized web design, and page flow. But, can I reuse parts of the admin interface code instead of re-implementing the same functionality?

任何其他减少代码的建议都将受到欢迎。

Any other suggestions to reduce the code would be most welcome.

推荐答案

这是如何实现内联表单集的答案,例如Django admin
http://kevindias.com/writing/django-class-based-views-multiple-inline-formsets/
但是仅描述了CreateWiew。如果您还想实现UpdateView,则需要做一些修改来复制代码

Here is the answer how to implement inline formsets like in Django admin http://kevindias.com/writing/django-class-based-views-multiple-inline-formsets/ However only CreateWiew is described. If you want to implement also UpdateView you need to do duplicate your code for it with a little tweaks

def get(self, request, *args, **kwargs):
    """
    Handles GET requests and instantiates blank versions of the form
    and its inline formsets.
    """
    self.object = self.get_object()
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    sample_form = SampleFormSet(instance=self.object)
    return self.render_to_response(
        self.get_context_data(form=form,
                              sample_form=sample_form))

def post(self, request, *args, **kwargs):
    """
    Handles POST requests, instantiating a form instance and its inline
    formsets with the passed POST variables and then checking them for
    validity.
    """
    self.object = self.get_object()
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    sample_form = SampleFormSet(self.request.POST, instance=self.object)
    if (form.is_valid() and sample_form.is_valid()):
        return self.form_valid(form, sample_form)
    else:
        return self.form_invalid(form, sample_form)

def form_valid(self, form, sample_form):
    """
    Called if all forms are valid. Creates a Recipe instance along with
    associated Ingredients and Instructions and then redirects to a
    success page.
    """
    self.object = form.save()
    sample_form.save()
    return HttpResponseRedirect(self.get_success_url())

不要忘了在模板中添加DELETE表单集字段

and don`t forget to add DELETE formset field to your template

          {% for form in sample_form %}
          {{ form.id }}
          <div class="inline {{ sample_form.prefix }}">
              {{ form.description.errors }}
              {{ form.description.label_tag }}
              ...
              {{ form.DELETE }}
          </div>
          {% endfor %}

这篇关于Django:创建类似于管理界面的内联表单集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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