简体   繁体   中英

Django form is blank after submit

I have a simple form in django's template:

<div class="container">
    <form action="{% url 'reporter:new_report' %}" method="post" novalidate>{% csrf_token %}
        {{ report_form.as_p }}
        <button type="submit" value="submit" class="btn btn-primary">Generuj raport</button>
    </form>
</div>

but when I want submit it it send blank fields to my form and I don't know why.

This is my views.py:

def report_create(request, template_name='reporter/created.html'):
    report = Report()
    if request.POST:
        report_form = ReportForm(request.POST or None, prefix="report_form")

        if report_form.is_valid():

            report = report_form.save(commit=False)
            report.report_name = report_form.cleaned_data['report_name']
            report.save()

            return render(request, template_name, {})

    return redirect('reporter:empty_form')

forms.py:

class ReportForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = ['report_name', 'create_date', 'additional_findings',
                  'additional_recommendations', 'report_type']

and models.py:

class Report(models.Model):
    report_name = models.CharField(max_length=100, blank=True)
    create_date = models.DateField('date of creation', blank=True)
    additional_findings = models.TextField(max_length=10000, blank=True)
    additional_recommendations = models.TextField(max_length=10000, blank=True)

    FULL_REPORT = 'FULL REPORT'
    NOT_FULL_REPORT = 'NOT FULL REPORT'

    REPORT_TYPE = (
        (FULL_REPORT, 'Full report'),
        (NOT_FULL_REPORT, 'Not full report')
    )
    report_type = models.CharField(max_length=100, choices=REPORT_TYPE, default=FULL_REPORT, blank=True)

I learn Django, I do everything like in tutorials, but I cannot understand why this form is still blank when I want submit it.

EDIT: I changed report_create function but result i still same - data from a form is blank there.

如果所有字段均有效,则可以使用report_form.cleaned_data访问值

I finally solved problem. I added name="{{ field.name }}" to the input fields in html file. And then print all values with cleaned_data . It works fine.

EDIT: I changed {{ report_form.as_p }} to the loop for over fields in form and added name tag to inputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM