You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python统计代码转为Django模板,基于django fobi表单生成报表?

Hey there! Let's walk through how to adapt your existing Python statistics code into a Django solution for your fobi custom forms. I'll break this down into actionable steps, from data handling to template rendering.

1. First: Parse & Structure Your Form Data

Looking at your saved_data example, it's a nested JSON string where each outer list item represents a single user's form submission, and each inner object is a field with its answer. First, we need to convert this into usable Python objects (or pull it directly from fobi's database models if you haven't already).

If you're fetching data from fobi's built-in storage, use the SavedFormData model—this is where fobi stores user submissions by default:

from fobi.models import SavedFormData

# Get all submissions for a specific form (filter by form entry if needed)
submissions = SavedFormData.objects.filter(form_entry__title="Your Custom Form")

If you're working with the raw saved_data string you provided, parse it with json.loads:

import json

saved_data_str = '''[[{"label": "Question 1?", ... }]]'''
saved_data = json.loads(saved_data_str)

2. Integrate Your Statistics Code into a Django View

Take your existing stats logic and wrap it in a Django view. This view will process the data, run your calculations, and pass the results to a template.

Here's an example (adjust the stats logic to match your existing code):

from django.shortcuts import render
from collections import defaultdict
from fobi.models import SavedFormData
import json

def form_statistics(request):
    # Fetch submissions (or use your parsed saved_data)
    submissions = SavedFormData.objects.all()
    total_submissions = submissions.count()

    # Initialize stats structure (customize this to match your needs)
    question_stats = defaultdict(lambda: defaultdict(int))

    for entry in submissions:
        # Parse the JSON data stored in fobi's SavedFormData
        form_fields = entry.data
        for field in form_fields:
            question_label = field["label"]
            answer = field["answer"]
            question_stats[question_label][answer] += 1

    # Add percentage calculations (if needed)
    for question, answers in question_stats.items():
        for answer, count in answers.items():
            percentage = round((count / total_submissions) * 100, 2) if total_submissions > 0 else 0
            answers[answer] = {"count": count, "percentage": percentage}

    # Pass stats to the template
    context = {
        "question_stats": question_stats,
        "total_submissions": total_submissions
    }
    return render(request, "form_statistics.html", context)

3. Create a Django Template to Display the Report

Now build a template to render the stats in a user-friendly way. Use Django's template tags to loop through your data and format it into tables or charts.

Example templates/form_statistics.html:

<!DOCTYPE html>
<html>
<head>
    <title>Form Statistics</title>
    <style>
        .stat-section { margin: 20px 0; padding: 15px; border: 1px solid #eee; border-radius: 4px; }
        table { border-collapse: collapse; width: 100%; margin-top: 10px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f5f5f5; }
    </style>
</head>
<body>
    <h1>Custom Form Submission Statistics</h1>
    <p><strong>Total Submissions:</strong> {{ total_submissions }}</p>

    {% if question_stats %}
        {% for question, answers in question_stats.items %}
            <div class="stat-section">
                <h2>{{ question }}</h2>
                <table>
                    <thead>
                        <tr>
                            <th>Answer</th>
                            <th>Count</th>
                            <th>Percentage</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for answer, data in answers.items %}
                            <tr>
                                <td>{{ answer }}</td>
                                <td>{{ data.count }}</td>
                                <td>{{ data.percentage }}%</td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        {% endfor %}
    {% else %}
        <p>No submissions found to generate statistics.</p>
    {% endif %}
</body>
</html>

4. Wire Up the URL

Don't forget to add a URL pattern so users can access the report. In your app's urls.py:

from django.urls import path
from .views import form_statistics

urlpatterns = [
    # ... your other URLs
    path("form-stats/", form_statistics, name="form_statistics"),
]

Quick Tips for Enhancement

  • Filter by Form: If you have multiple fobi forms, add a filter to the SavedFormData query (e.g., filter(form_entry__slug="my-form-slug")) to generate stats for a specific form.
  • Add Charts: For visual reports, use a library like Chart.js. Pass the stats as JSON to the template and render bar/pie charts (e.g., {{ question_stats|json_script:"stats-data" }} in the template).
  • Reusable Stats Function: Move your statistics logic into a separate utils.py file to keep your view clean and make it reusable across your project.
  • Handle Edge Cases: Add checks for zero submissions, empty answers, or malformed data to avoid errors.

内容的提问来源于stack exchange,提问作者Dragos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:55:32