Django Forms - 有没有办法将数据保存到表单中的单独模型?

时间:2016-11-28 04:43:10

标签: django django-models django-forms

如果我使用form.clean()方法处理简单的formset,并且我使用输入值从其关联模型中提取数据,我该如何将该数据保存到单独的模型中是什么类,没有由formset定义?

代码:

#forms.py
class SlotInlineFormSet(BaseInlineFormSet):
    def clean(self):
        super(SlotInlineFormSet, self).clean()
        y = self.cleaned_data
        print(y)

        # Access each form one at a time
        for idx, form in enumerate(self.forms):
            form_data = form.cleaned_data
            print('idx: ' + str(idx+1))

            #Pull Necessary Port Variables
            port_type = (form_data['installed_card'].default_port_type)
            max_ports = (form_data['installed_card'].max_port_num)
            port_start_num = (form_data['installed_card'].port_start_num)
            port_naming = (form_data['installed_card'].port_naming)

            #Save Ports to Port model
            #???

#views.py
def manage_slots(request, node_id):
    node = Node.objects.get(pk=node_id)
    max_slots = node.chassis.num_slots
    SlotFormSet = inlineformset_factory(Node, Slot, max_num=max_slots, extra = max_slots-node.slot_set.count(),
                                            can_order = False, fields=('installed_card', ), can_delete=False, formset = SlotInlineFormSet)
    if request.method == "POST":
        formset = SlotFormSet(request.POST, request.FILES, instance=node)
        if formset.is_valid():
            forms = formset.save(commit=False)
            ### Save form slot number as an enumeration ###
            formset.save()
            messages.success(request, "Slot details saved!")
            return redirect("appDB:apphome")
    else:
        formset = SlotFormSet(instance=node)
    return render(request, 'forms/manage_slots.html', {'formset': formset})


#models.py - Port class to save to

class Port(models.Model):
    slot = models.ForeignKey(Slot)
    port_num = models.PositiveSmallIntegerField()
    port_type = models.ForeignKey(PortDef)

    class Meta:
        unique_together = ("slot", "port_num")

    def __str__(self):
        if self.slot.sub_slot_num is None:
            return u'%s - Port: %s%s/%s' % (self.slot.node, self.slot.installed_card.port_naming, self.slot.slot_num, self.port_num)
        if self.slot.sub_slot_num is not None:
            return u'%s - Port: %s%s/%s/%s' % (self.slot.node, self.slot.installed_card.port_naming, self.slot.slot_num, self.slot.sub_slot_num, self.port_num)

    def get_absolute_url(self):
        return reverse('Port-detail', kwargs={'pk': self.pk})

谢谢。

1 个答案:

答案 0 :(得分:0)

您只需将Port模型导入forms.py并将必要的字段保存到该模型对象中。 像这样:

#import your Port model from models.py here.
from .models import Port

#forms.py
class SlotInlineFormSet(BaseInlineFormSet):
def clean(self):
    super(SlotInlineFormSet, self).clean()
    y = self.cleaned_data
    print(y)

    # Access each form one at a time
    for idx, form in enumerate(self.forms):
        form_data = form.cleaned_data
        print('idx: ' + str(idx+1))

        #Pull Necessary Port Variables
        port_type = (form_data['installed_card'].default_port_type)
        max_ports = (form_data['installed_card'].max_port_num)
        port_start_num = (form_data['installed_card'].port_start_num)
        port_naming = (form_data['installed_card'].port_naming)
        #import your port model here and get the desired port_object based on data passd by you

        port_object = Port.objects.get(slot=Your_slot) #Your_slot is the slot passed by you in the cleaned data.
        port_object.port_type = port_type
        port_object.port_num = port_start_num
        port_object.save()
        #here the data will be saved for that perticular port_object with port_type and port_num fields.