Django Formset错误“ JournalVoucherEnteryForm”对象没有属性“ instance”

时间:2019-10-27 07:27:16

标签: python django django-models django-forms django-views

我正在使用jQuery动态添加表单字段。我正在将python 3.7和Django 2.2.6与postgrsql一起使用。
我遵循一个教程和Github代码。这是链接

Youtube: https://www.youtube.com/watch?v=Tg6Ft_ZV19M

Github代码: https://github.com/shitalluitel/formset

我收到此错误,请检查并帮助我解决此问题。 “ JournalVoucherEnteryForm”对象没有属性“ instance” 谢谢

Views.py

def acc_journal(request):
    entriesFormset = modelformset_factory(JournalVoucherEntery, form=JournalVoucherEnteryForm, fields=('ajve_group','ajve_account','ajve_location','ajve_narration','ajve_currency','ajve_ex_rate','ajve_debit_amt','ajve_credit_amt','ajve_debit_base','ajve_credit_base','ajve_balance'), extra=2)
    form = AccountJournalVoucherForm(request.POST or None)
    formset = entriesFormset(request.POST or None, queryset=JournalVoucherEntery.objects.none(), prefix='journalvc')
    if request.method == 'POST':
        if form.is_valid() and formset.is_valid():
            try:
                with transaction.atomic():
                    journalv = form.save(commit=False)
                    journalv.save()

                    for entry in formset:
                        data = entry.save(commit=False)
                        data.ajve_journal_vc = journalv
                        data.save()
            except IntegrityError:
                print('Error Encountered')

    context = {
        'acc_journal_acti': 'active',
        'main_header': 'Accounts',
        'header_heading': 'Journal',
        'acc_journals': JournalVoucher.objects.all(),
        'form': form,
        'formset': formset
    }
    return render(request, 'accounts/journal.html', context)

models.py

class JournalVoucher(models.Model):
    journal_voucher_id = models.AutoField(primary_key=True)
    acc_jurnl_vc_num = models.CharField(max_length=50, blank=False)
    acc_jurnl_vc_loc = models.CharField(max_length=50, blank=False)
    acc_jurnl_vc_date = models.DateField(auto_now=False)
    acc_jurnl_vc_ref_num = models.CharField(max_length=50, blank=True)
    acc_jurnl_vc_total_debit = models.DecimalField(
        max_digits=30, decimal_places=2, blank=True, null=True)
    acc_jurnl_vc_total_credit = models.DecimalField(
        max_digits=30, decimal_places=2, blank=True, null=True)
    acc_jurnl_vc_info = models.TextField(blank=True)
    acc_jurnl_vc_added_by = models.CharField(max_length=200, blank=True)
    jv_date_added = models.DateTimeField(
        default=datetime.now)

    def __str__(self):
        return str(self.journal_voucher_id)

    class Meta:
        db_table = 'journalvoucher'


class JournalVoucherEntery(models.Model):
    ajve_id = models.AutoField(primary_key=True)
    ajve_journal_vc = models.ForeignKey(
        JournalVoucher, related_name='journalvc', on_delete=models.CASCADE)
    ajve_group = models.CharField(max_length=200)
    ajve_account = models.CharField(max_length=200)
    ajve_location = models.CharField(max_length=200, default='')
    ajve_narration = models.CharField(max_length=200, default='')
    ajve_currency = models.CharField(max_length=100)
    ajve_ex_rate = models.BigIntegerField()
    ajve_debit_amt = models.DecimalField(
        max_digits=99, decimal_places=2, default='')
    ajve_credit_amt = models.DecimalField(
        max_digits=99, decimal_places=2, default='')
    ajve_debit_base = models.DecimalField(
        max_digits=99, decimal_places=2, default='')
    ajve_credit_base = models.DecimalField(
        max_digits=99, decimal_places=2, default='')
    ajve_balance = models.DecimalField(
        max_digits=99, decimal_places=2, default='')
    ajve_added_by = models.CharField(max_length=200, blank=True)
    ajve_date_added = models.DateTimeField(
        default=datetime.now)

    def __str__(self):
        return self.ajve_journal_vc

    class Meta:
        db_table = 'journalvoucherentery'

forms.py

class AccountJournalVoucherForm(forms.ModelForm):
    class Meta:
        model = JournalVoucher

        fields = [
            'acc_jurnl_vc_num',
            'acc_jurnl_vc_loc',
            'acc_jurnl_vc_date',
            'acc_jurnl_vc_ref_num',
            'acc_jurnl_vc_total_debit',
            'acc_jurnl_vc_total_credit',
            'acc_jurnl_vc_info',
        ]
        labels = {
            'acc_jurnl_vc_num': 'Number',
            'acc_jurnl_vc_loc': 'Location',
            'acc_jurnl_vc_date': 'Date',
            'acc_jurnl_vc_ref_num': 'Ref Number',
            'acc_jurnl_vc_total_debit': 'Total Debit',
            'acc_jurnl_vc_total_credit': 'Total Credit',
            'acc_jurnl_vc_info': 'Info',
        }
        widgets = {
            'acc_jurnl_vc_num': forms.TextInput(attrs={'class': 'form-control formset-field'}),
            'acc_jurnl_vc_loc': forms.TextInput(attrs={'class': 'form-control formset-field'}),
            'acc_jurnl_vc_date': forms.DateInput(attrs={'class': 'form-control formset-field'}),
            'acc_jurnl_vc_ref_num': forms.TextInput(attrs={'class': 'form-control formset-field'}),
            'acc_jurnl_vc_total_debit': forms.NumberInput(attrs={'class': 'form-control formset-field'}),
            'acc_jurnl_vc_total_credit': forms.NumberInput(attrs={'class': 'form-control formset-field'}),
            'acc_jurnl_vc_info': forms.TextInput(attrs={'class': 'form-control formset-field'}),
        }

class JournalVoucherEnteryForm(forms.Form):
    class Meta:
        model = JournalVoucherEntery

        fields = [
            'ajve_group',
            'ajve_account',
            'ajve_location',
            'ajve_narration',
            'ajve_currency',
            'ajve_ex_rate',
            'ajve_debit_amt',
            'ajve_credit_amt',
            'ajve_debit_base',
            'ajve_credit_base',
            'ajve_balance',
        ]
        labels = {
            'ajve_group': 'Group',
            'ajve_account': 'Account',
            'ajve_location': 'Location',
            'ajve_narration': 'Narration',
            'ajve_currency': 'Currency',
            'ajve_ex_rate': 'Ex Rate',
            'ajve_debit_amt': 'Debit Amount',
            'ajve_credit_amt': 'Credit Amount',
            'ajve_debit_base': 'Debit Base',
            'ajve_credit_base': 'Credit Base',
            'ajve_balance': 'Balance',
        }
        widgets = {
            'ajve_group': forms.TextInput(attrs={'class': 'form-control formset-field'}),
            'ajve_account': forms.TextInput(attrs={'class': 'form-control formset-field'}),
            'ajve_location': forms.TextInput(attrs={'class': 'form-control formset-field'}),
            'ajve_narration': forms.TextInput(attrs={'class': 'form-control formset-field'}),
            'ajve_currency': forms.TextInput(attrs={'class': 'form-control formset-field'}),
            'ajve_ex_rate': forms.NumberInput(attrs={'class': 'form-control formset-field'}),
            'ajve_debit_amt': forms.NumberInput(attrs={'class': 'form-control formset-field'}),
            'ajve_credit_amt': forms.NumberInput(attrs={'class': 'form-control formset-field'}),
            'ajve_debit_base': forms.NumberInput(attrs={'class': 'form-control formset-field'}),
            'ajve_credit_base': forms.NumberInput(attrs={'class': 'form-control formset-field'}),
            'ajve_balance': forms.NumberInput(attrs={'class': 'form-control formset-field'}),
        }

HTML模板

{% load crispy_forms_tags %}
                        <form method="POST">
                            {% csrf_token %}
                            <fieldset>
                                <div class="row">
                                    <div class="form-group">
                                        <div class="col-md-3 col-sm-6 col-xs-12">
                                            {{ form.acc_jurnl_vc_num|as_crispy_field }}
                                        </div>
                                        <div class="col-md-3 col-sm-6 col-xs-12">
                                            {{ form.acc_jurnl_vc_date|as_crispy_field }}
                                        </div>
                                        <div class="col-md-3 col-sm-6 col-xs-12">
                                            {{ form.acc_jurnl_vc_loc|as_crispy_field }}
                                        </div>
                                        <div class="col-md-3 col-sm-6 col-xs-12">
                                            {{ form.acc_jurnl_vc_ref_num|as_crispy_field }}
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                            <br><br>
                            <div class="col-md-12 col-sm-12 col-xs-12">
                                <ul class="nav nav-tabs nav-top-border">
                                    <li class="active"><a href="#home" data-toggle="tab">Voucher Entries</a></li>
                                    <li><a href="#profile" data-toggle="tab">Attachments</a></li>
                                </ul>

                                <div class="tab-content">
                                    <div class="tab-pane fade in active" id="home">
                                        <div class="row">
                                            {% for entries in formset %}
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_group|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_account|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_location|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_narration|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_currency|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_ex_rate|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_debit_amt|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_credit_amt|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_debit_base|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_credit_base|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    {{ entries.ajve_balance|as_crispy_field }}
                                                </div>
                                                <div class="col-lg-1 col-md-1 col-sm-3 col-xs-6">
                                                    <button type="button" class="btn btn-danger btn-sm remove-form-row" id="{{ formset.prefix }}">
                                                        X
                                                    </button>
                                                </div>
                                            {% endfor %}
                                        </div>
                                    </div>
                                    <div class="tab-pane fade" id="profile">

                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 col-sm-6 col-xs-6">
                                    <button type="button" class="btn btn-featured btn-blue btn-inverse margin-top-30 add-form-row" id="{{ formset.prefix }}">
                                        <span>ADD ENTERY</span>
                                        <i class="et-book-open"></i>
                                    </button>
                                </div>
                                {{ formset.management_form }}
                                <div class="col-md-6 col-sm-6 col-xs-6">
                                    <button type="submit" name="submit"
                                        class="btn btn-featured btn-blue btn-inverse margin-top-30">
                                        <span>SAVE NEW JOURNAL VOUCHER</span>
                                        <i class="et-book-open"></i>
                                    </button>
                                </div>
                            </div>
                        </form>

终端错误

System check identified no issues (0 silenced).
October 27, 2019 - 07:14:59
Django version 2.2.6, using settings 'ifbs.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /accounts/journal
Traceback (most recent call last):
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/azharsaleem/Desktop/ifbs/accounts/views.py", line 96, in acc_journal
    return render(request, 'accounts/journal.html', context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/template/defaulttags.py", line 166, in render
    len_values = len(values)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/forms/formsets.py", line 75, in __len__
    return len(self.forms)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/forms/formsets.py", line 136, in forms
    for i in range(self.total_form_count())]
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/forms/formsets.py", line 136, in <listcomp>
    for i in range(self.total_form_count())]
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/forms/models.py", line 620, in _construct_form
    form = super()._construct_form(i, **kwargs)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/forms/formsets.py", line 173, in _construct_form
    self.add_fields(form, i)
  File "/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/forms/models.py", line 847, in add_fields
    qs = qs.using(form.instance._state.db)
AttributeError: 'JournalVoucherEnteryForm' object has no attribute 'instance'
[27/Oct/2019 07:15:07] "GET /accounts/journal HTTP/1.1" 500 188499

浏览器错误

AttributeError at /accounts/journal
'JournalVoucherEnteryForm' object has no attribute 'instance'
Request Method: GET
Request URL:    http://127.0.0.1:8000/accounts/journal
Django Version: 2.2.6
Exception Type: AttributeError
Exception Value:    
'JournalVoucherEnteryForm' object has no attribute 'instance'
Exception Location: /Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages/django/forms/models.py in add_fields, line 847
Python Executable:  /Users/azharsaleem/Desktop/ifbs/venv/bin/python
Python Version: 3.7.4
Python Path:    
['/Users/azharsaleem/Desktop/ifbs',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
 '/Users/azharsaleem/Desktop/ifbs/venv/lib/python3.7/site-packages']

1 个答案:

答案 0 :(得分:0)

您正在从“ forms.Form”继承JournalVoucherEntryForm,请尝试从“ forms.ModelForm”继承。