来自多个模型的预填充表单,用于"更新"

时间:2016-02-26 03:00:19

标签: python django django-models django-forms

我对Django很新,所以请原谅我需要提出的相当新的问题。基本上,我遇到了一个问题,我在无数次搜索后很难实现。

我想要做的是在页面中创建输入表单,并使用数据库中的数据填充它。然后,我希望能够单击一个按钮来更新我对表单所做的任何更改。这里的问题是表单将从两个模型,主模型和与之相关的子模型中获取数据。正如发票可能包含多个项目一样。

我得到的最远的是显示主模型但不显示子模型,或显示所有内容,但按钮没有做任何事情。以下是代码:

models.py

import datetime
from django.db import models
from django.utils import timezone

class InvoiceList(models.Model):
    invoice_number = models.IntegerField(default=0)
    recipient = models.CharField(max_length=100)
    issue_date = models.DateField()
    deadline = models.DateField()
    additional_info = models.CharField(max_length=500)

def __str__(self):
    return self.recipient

class InvoiceItem(models.Model):
    item_description = models.CharField(max_length=150)
    number = models.IntegerField(default=1)
    price = models.IntegerField(default=0)
    tax = models.IntegerField(default=0)
    list = models.ForeignKey(InvoiceList)

    def __str__(self):
        return self.item_description + " (" + str(self.list) + ")"

forms.py (已编辑)(已添加" can_delete + = False"以防止出现"删除"复选框。需要检查复选框以便" is_valid"标记为True ...这是废话。所以删除它!)

import datetime
from bill.models import *
from django.utils import timezone
from django.forms import ModelForm
from django.forms.models import inlineformset_factory

class InvoiceListForm(ModelForm):
    class Meta:
        model = InvoiceList
        fields = ['invoice_number', 'recipient', 'issue_date', 'deadline', 'additional_info']

class InvoiceItemForm(ModelForm):
    class Meta:
        model = InvoiceItem
        exclude = ('list',)
        fields = ['item_description', 'number', 'price', 'tax']

InvoiceFormSet = inlineformset_factory(InvoiceList, InvoiceItem, fields=('id','item_description','number','price','tax',), extra=0, can_delete=False)

views.py (已编辑)的部分视图(可能可以大量清理,但这里是使其更新的引擎!)

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, render
from django.utils import timezone
from django.core.context_processors import csrf
from django.forms.formsets import formset_factory, BaseFormSet
from django.forms.models import modelformset_factory
from bill.forms import *
from .forms import InvoiceFormSet
from django.views.generic.edit import UpdateView
from django.forms import inlineformset_factory
from django.template import RequestContext

def update_edit(request, invoice_id):
    a = get_object_or_404(InvoiceList, pk=invoice_id)
    b = InvoiceFormSet(instance=a, prefix="item")
    c = InvoiceListForm(instance=a, prefix="list")

    if request.method == 'POST':
        gaga = InvoiceListForm(request.POST, instance=a, prefix="list")
        lala = InvoiceFormSet(request.POST, instance=a, prefix="items")
        if gaga.is_valid() and lala.is_valid():
            gaga.save()
            lala.save()
            return HttpResponse('Good, saved the thing!')
        else:
            return HttpResponse('No shway! Didn't save cos not valid!')
    else:
        c = InvoiceListForm(instance=a, prefix="list")
        b = InvoiceFormSet(instance=a, prefix="items")

    d = {'invoice_info': c, 'items': b}
    d.update(csrf(request))
    return render(request, 'bill/update.html', {'form': invoice_info, 'items': invoice_stuff})

这里是前端update.html (已编辑)(已添加管理事项)

<h1>Updating Invoice</h1>

<form action="." name="stock_details" method="post">
{% csrf_token %}
<hr>
{{ form.as_p }}
{{ items.management_form }}
{% for item in items %}
    {{ item }}
{% endfor %}

<hr>

<input type='submit' value='Update'/>
</form>

我会放入{{item.as_p}},但不幸的是,这并没有显示任何内容。我不确定为什么。以上显示了所有数据。唯一的例外是项目,它们不会出现在输入标记内......我想我必须手动执行此操作。

编辑 - 我已经修改了代码,以便将发票及其子项显示在表单集中,该表单集显示良好且已填充内容。假设有变化,我试图弄清楚如何保存表格。帮助

全部解决了!非常感谢你!

0 个答案:

没有答案