如何使用Django中先前提交的HTML表单提交的数据预先填充表单?

时间:2019-04-19 11:49:11

标签: python html django

我正在尝试使用我已提交到上一个HTML页面(也是ModelForm)的一些数据填充ModelForm。 我只想将其传递给另一种形式,因此不必写两次。

我已经尝试了stackoverflow的几种解决方案,但是它们已有6年以上的历史,有点过时了,也无法提供Django文档https://docs.djangoproject.com/en/2.2/topics/forms/的解决方案 我有两个模型,它们具有相同的字段,分别是nameboxid 我需要将其从第一个输入传递到第二个(填充)。

forms.py

class NewCashierForm(forms.ModelForm):
    class Meta:
        model = Cashier
        fields = ("cashier_company", "cashier_dealer", "cashier_name", "cashier_boxid", "cashier_type", "cashier_package", "cashier_otheritem", "cashier_otheritemserial", "cashier_length", "cashier_promotion", "cashier_amount", "cashier_paymenttype")
        labels = {"cashier_company":('Firma'), "cashier_dealer": ('Diler'), "cashier_name":('Ime i prezime'), "cashier_boxid":('Box ID'), "cashier_type":('Tip'), "cashier_package":('Paket'), "cashier_otheritem":('Drugi uredjaj'), "cashier_otheritemserial":('SBU'), "cashier_length":('Dužina'), "cashier_promotion":('Promocija'), "cashier_amount":('Iznos'), "cashier_paymenttype":('Nacin uplate')}
        exclude = ['cashier_published']


def save(self, commit=True):
    cashier = super(NewCashierForm, self).save(commit=False)
    if commit:
        cashier.save()
    return cashier



class NewPersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = {"person_name", "person_adress", "person_phone", "person_boxid"}
        labels = {"person_name":('Ime i prezime'), "person_adress":('Adresa'), "person_phone":('Telefon'), "person_boxid":('Box ID')}

def save(self, commit=True):
    person = super(NewPersonForm, self).save(commit=False)
    if commit:
        person.save()
    return person

views.py

def addcashier(request):

    if request.method == 'GET':
        form = NewCashierForm()
    else:
        form = NewCashierForm(request.POST)
        if form.is_valid():
            fs = form.save(commit=False)
            fs.user = request.user
            fs.save()

            return redirect('/byauthor')
    return render (request, 'main/addcashier.html', {'form':form})

def addperson(request):

    if request.method == 'GET':
        form = NewPersonForm()
    else:
        form = NewPersonForm(request.POST)
        if form.is_valid():
            fs = form.save(commit=False)
            fs.user = request.user
            fs.save()

            return redirect('/addcashier')

    return render (request, 'main/addperson.html', {'form':form})

addperson.html addcashier.html

{% extends "main/base.html" %}


{% block content %}

    <form method="POST">
        {% csrf_token %}

        {{form.as_p}}

        <button class="btn" type="submit">Unos i dodavanje pretplate</button>
    </form>

    <input type="button" value="Otkazi unos" onclick="window.history.back()" /> 

{% endblock %}

感谢任何帮助和/或提示。

1 个答案:

答案 0 :(得分:1)

要预填充表单,在初始化initial={}调用的表单时,需要传递参数GET。由于要将数据从一个视图传递到另一个视图,因此应使用sessions

def addperson(request):

    if request.method == 'GET':
        form = NewPersonForm()
    else:
        form = NewPersonForm(request.POST)
        if form.is_valid():
            fs = form.save(commit=False)
            fs.user = request.user
            fs.save()
            request.session["person_form"] = request.POST.dict()  #save the form as a dict in request.sessions

            return redirect('/addcashier')

    return render (request, 'main/addperson.html', {'form':form})

然后在第二个视图中,使用会话中的数据初始化表单。

def addcashier(request):

    if request.method == 'GET':
        # get the form data from the request.session
        form_data = request.session.pop('person_form', {})
        box_id = form_data.get("person_boxid")
        name = form_data.get("person_name")

        form = NewCashierForm(initial={"cashier_name":name, "cashier_boxid":box_id})  # initialize the form with the data

    else:
        form = NewCashierForm(request.POST)
        if form.is_valid():
            fs = form.save(commit=False)
            fs.user = request.user
            fs.save()

            return redirect('/byauthor')
    return render (request, 'main/addcashier.html', {'form':form})