Python / Django-为视图生成的表添加自定义列

时间:2016-11-28 16:33:45

标签: python django

我的Django网站上有一个页面,它根据存储在数据库中的信息显示了许多表格。

用于创建显示表格的页面的视图定义为:

def current_budget(request, budget_id):
    """ View the active provisional/deposit budget """
    budget = Budget.objects.select_related('project',     'project__budget_overview').prefetch_related('project__projectroom_set', 'project__budget_versions', 'budget_items').get(id=budget_id)
    project = budget.project
    # project.projectroom_set.filter(budgetitem__isnull=True, cciitem__isnull=True).delete()

    if project.budget_overview.deposit_budget_saved: return HttpResponseRedirect(reverse('costing:combined_budget', args=[project.id]))

    #This is now done in the costing_home view
    # if not budget:
    #   Budget.objects.create(project=project, current_marker=1)

    if not budget.budget_items.exists() and not project.budget_overview.deposit_budget_saved: init_budget(budget) # Create initial BudgetItem objects as standard
    budget_items = budget.budget_items.select_related('budget', 'budget__project', 'project_room', 'project_room__room', 'room')#.order_by('build_type', 'build_type_detail', 'project_room', 'order') # .exclude(build_type=None)
    budget_items2 = None #budget.budget_items.filter(build_type=None).order_by('build_type_detail', 'project_room', 'room')

    context = {
        'project': project,
        'budget': budget,
        'offset1': -5,
        'offset2': -4,
        }

    try: context['current_budget'] = project.budget_versions.get(current_marker=1) #For option name/date on top of pdfs
    except ObjectDoesNotExist: pass

    if request.GET.get('version') or project.budget_overview.deposit_budget_saved: #Make the fields all readonly
        context['readonly'] = True
        context['offset1'] = -7

    if request.GET.get('report'): #Schedule of works report uses same data as current budget form
        """ Client view of budget. IMPORTANT: Hidden items are not displayed here """

        items_grouped = groupby(budget_items.filter(hidden_cost=False), lambda x: x.build_type)
        grouped_items = [(x, list(y)) for x, y in items_grouped]
        context['grouped_items'] = grouped_items
        if request.GET.get('pdf'):
            template = get_template('costing/report_schedule_of_works.html')
            html  = template.render(context)

            file = open('test.pdf', "w+b")
            pisaStatus = pisa.CreatePDF(html.encode('utf-8'), link_callback=fetch_resources, dest=file,
                encoding='utf-8')

            file.seek(0)
            pdf = file.read()
            file.close()            
            return HttpResponse(pdf, 'application/pdf')
        else:
            context['webview'] = 1
            context['html'] = render_to_string('costing/report_schedule_of_works.html', context)
            context['active_tab'] = '3'
            return render(request, 'costing/reports_pre_deposit.html', context)

    else:
        if not context.get('readonly'):
            context['skill_day_rate'] = skill_day_rate
            context['labour_day_rate'] = labour_day_rate
        # Dict with ProjectRoom ids and the total for the room
        room_totals = {}

        for project_room in project.projectroom_set.all():
            room_totals[project_room.id] = sum(item.total_inc_profit for item in budget_items if item.project_room == project_room)

        context['room_totals'] = room_totals

        item_formset = BudgetItemFormset(queryset=budget_items, form_kwargs={'project': project})
        item_form = item_formset.forms[0]
        context['field_count'] = len(item_form.visible_fields())
        context['ao_field_count'] = len(item_form.visible_fields())

        room_choices = project.room_choices

        context['formset'] = item_formset
        context['widths'] = budget_item_column_widths #First column is add/delete options to allow for forloop count offset
        context['options_width'] = options_width #First column is add/delete options to allow for forloop count offset
        context['labour_rate'] = labour_day_rate
        context['skill_rate'] = skill_day_rate
        context['item_code_options'] = ItemCodeForm()
        skill_total = int(budget_items.aggregate(Sum('skill_days'))['skill_days__sum'] or 0)
        if budget_items2: labour_total = int(budget_items2.aggregate(Sum('labour_days'))['labour_days__sum'])
        else: labour_total =  0

        return render(request, 'costing/budget_current.html', context)

我现在想在这些表中添加一个“自定义”列,以允许用户输入自己的注释(即不会显示从数据库中检索到的数据,但是应该向每行添加信息)数据库保存时。)

我该怎么做?我原以为我会在视图(Python)中而不是在模板(HTML)中这样做,因为视图是构建表的地方吗?

修改

所以,我已经在models.py中为应用添加了额外字段:

class Deposit(models.Model):
    """ Each Deposit is linked to a Payment, whose is_booking_deposit field = True """
    project = models.OneToOneField('projects.Project', null=True, blank=True)
    half_paid = models.DateField(null=True, blank=True)
    date_received = models.DateField(null=True, blank=True)
    amount_exc_vat = models.DecimalField(decimal_places=2, max_digits=12, null=True, blank=True)
    invoice_raised = models.DateField(null=True, blank=True)
    notes = models.TextField(null=True, blank=True)
    # Create a column for 'custom notes' in the tables:
    custom_notes = models.TextField(null=True, blank=True) #Add the column to table in tables.py

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    payment = models.OneToOneField(Payment, null=True)
    ...

我在Deposit模型中添加的字段是custom_notes

我还尝试将同一字段添加到BudgetItemTable()中的tables.py

class BudgetItemTable(tables.Table):
    # Add a column for 'custom notes' to the tables for current budget
    custom_notes = tables.Column(accessor='self.custom_notes')
    class Meta:
        model = BudgetItem
        attrs = {"class": "paleblue"}
        exclude = ('id')

我已经python manage.py makemigrations& python manage.py migrate myApp,但是当我刷新浏览器再次查看此页面时,我的表的新列未显示 - 我是否需要以某种方式将其添加到视图中?我该怎么做?

修改

显示我要添加列的表的视图的HTML文件具有以下结构:

...
{% block page_options_style %}allow-footer{% endblock page_options_style %}
{% block page_options %}
    ...
    {% block report %}
    <div id='budget_form' class="col-12" data-pr="{{project.id}}" style="margin-bottom:7em;">
        <form class="autosave_form formset num_refresh text-sm" data-view-url="{% url 'costing:save_items' budget.id %}">{% csrf_token %}
            {{formset.management_form}}
            <div>
                <table ...>
                    <thead class=... >
                        <tr class=...>
                            ...
                            <!--  code to get table headings here -->
                            <th style="width:{{options_width}}">Custom Notes</th>
                            <!-- I added the 'Custom Notes' heading myself -->
                        </tr>
                    </thead>
                    ...
                    <tbody>
                        ...
                        <tr id="item_{{forloop.counter}}" class="{% cycle 'odd' 'even' %}">
                            ...
                            <!-- code add columns and populate rows here -->
                            <td>
                                <a class="delete" ... ></a>
                                <!-- I can see this column with the 'delete' values is the last column in the table on the webpage, so I want to manually add another column after it in the table- I tried doing this by adding the following tags: -->
                            </td>
                            <td>
                                <a class="custom_notes" type="text" value=""></a>
                            </td>
                            ...
                        </tr>
                    </tr>
                </tbody>
            </table>
            ...
        </tbody>
    </table>
</div>
</form>    

我尝试使用以下行添加“自定义备注”列:

<td>
    <a class="custom_notes" type="text" value=""></a>
</td>

当我在浏览器中查看此页面时,我可以看到我添加的Custom Notes列标题,显示在表格上方,但它显示在表格结束的右侧(我预期)我添加到表格中的列,显示在它下面。)

我尝试添加的“自定义备注”的表格列并未在表格中显示...

这是为什么?如何将新列显示在网页上的表格中?我已将相应字段添加到model中的models.py,因此虽然此时此数据库中的任何项目都没有任何数据,但用户输入数据时在表格的这个字段中,有些地方可以将这些值存储在数据库的模型中......

修改

我设法将这个附加字段添加到表中,方法是将以下HTML添加到表中,就在</tr>内的最后两个</tbody></table>标记内:

<td>
    <a class="custom_notes" type="text" value=""></a>
    <input id="budget_notes" type="text" width="100" value="">
</td>

但由于某种原因,我添加的文本输入字段非常窄 - 在输入文本时,您一次看不到多个文本字符。我尝试使用width="100"指定字段的宽度,如上所示,但这似乎没有任何区别。如何强制此列中的单元格具有设置宽度?

0 个答案:

没有答案