有没有一种方法可以自动在Django表单中包含文本字段?

时间:2019-11-12 12:11:58

标签: django python-3.x pandas django-forms django-views

我正在Django中创建一个表单。有一些静态字段,但我也想基于csv文件包括一些字段。但是,我不知道如何使这些文本字段成为表单提交的一部分。

forms.py

class OptimizerForm(forms.Form):
    no_lineups = forms.IntegerField(label='Number of Lineups', min_value=1, initial=1)
    min_deviation = forms.DecimalField(label='Minimum Deviation %', min_value=0, initial=0)
    max_deviation = forms.DecimalField(label='Maximum Deviation %', min_value=0, initial=15)
    randomize = forms.BooleanField(label='Randomize Lineups', initial=True)

views.py

def create_optimizer(request):
    if request.method == 'POST':
        form = OptimizerForm(request.POST)
        if form.is_valid():
            no_lineups = form.cleaned_data['hjk']
            with open('C:\\Users\\Charlie\\Desktop\\Fantasy Fire\\website\\optimizer\\lineups.csv') as myfile:
                response = HttpResponse(myfile, content_type='text/csv')
                response['Content-Disposition'] = 'attachment; filename=lineups.csv'
                return response

    else:
        form = OptimizerForm()
        df = Optimizer.get_daily_roster(
            'C:\\Users\\Charlie\\Desktop\\Fantasy Fire\\website\\optimizer\\Predictions.csv')
        df = df.drop(columns=['Name + ID', 'Game Info', 'Unnamed: 0', 'Unnamed: 0.1', 'name'])
        df = df.rename(columns={'TeamAbbrev': 'Team', 'AvgPointsPerGame': 'Predicted FP'})
        df['Predicted FP'] = df['Predicted FP'].apply(lambda x: round(float(x), 2))
        df['Predicted FP'] = df['Predicted FP'].apply(
            lambda x: "<input type='text' value=" + str(x) + " id='id_predicted_fp'>")
        df['Min Exposure'] = "<input type='text' value=" + str(0) + ">"
        df['Max Exposure'] = "<input type='text' value=" + str(100) + ">"
        html_table = df.to_html(index=False, justify='left', escape=False,
                                classes=[
                                    'table table-bordered table-striped table-hover table-responsive table-sm, container-fluid'])
    return render(request, 'optimizer/optimizer.html', {'form': form, 'player_table': html_table})

optimizer.html

{% extends "optimizer/base.html" %}
{% block content %}
<h1>Optimizer</h1>
<form method="post" action="/optimizer/">
    {% csrf_token %}
    <button type="submit" name="Generate Lineups">Generate Lineups</button>
    <!--<p>Number of Lineups: <input id="no_lineups" type="number" name="no_lineups" value=1 min="1"></p>-->
    <!--<br>-->
    <!--<br>-->
    {{form}}
    <div class="table-responsive">
        {{ player_table |safe }}
    </div>
</form>
{% endblock content %}

提交表单时,表中可编辑的值未包含在cleaned_data字典中。包括的唯一字段是在forms.py中静态创建的字段。我希望表中的字段包含在字典中。

0 个答案:

没有答案