如何使用javascript更改Django循环体?

2024-04-24 22:58:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一种方法可以在每次按下按钮时使用javascript更改django中for循环的主体

在我的例子中,我想在本周显示匹配项,当我按下下一步时,我想使用javascript更改列表,然后在重组部分将django模板传递给它,我想更改匹配项列表

我知道如何使用javascript编写代码来创建新列表以及上一个和下一个按钮,但我不知道如何将其传递给django模板

或者另一种方法可能是用javascript编写django代码,任何人都可以提供帮助


在views.py中,matches返回从今天到6天后的词典列表

def home(request):
    start = datetime.now().date()
    end = today + timedelta(6)

    matches = request_games(today, after_week)

    return render(request, "sporty/home.html",{
        "matches": matches,
        "start" : start,
        "end": end
    })

在home.html中

{% extends "sporty/layout.html" %}
{% load static %}


{% block body %}
<div class="box">
    {{start}},{{end}}
    
    {% regroup matches by date as date_list %}

    {% for date in date_list %}

        <div class="the_date">
            {{date.grouper}}
        </div>

        {% for match in date.list %}
            <div class="match_container">
                <div class="status">
                    {% if match.status_code == 1%}
                        {{match.minute}}'
                    {% elif match.status_code == 11%}
                        HT
                    {% elif match.status_code == 3 %}
                        Finished
                    {% endif %}
                </div>
                <div class="match">
                    <div class="home">
                        {{match.home_name}} <img src="{{match.home_logo}}">
                    </div>
                    <div class="score">
                        {% if match.status_code == 0 %}
                            {{match.time}}

                        {% elif match.status_code == 17 %}
                            TBD

                        {% elif match.status_code == 1%}
                            {{match.home_score}} : {{match.away_score}}

                        {% elif match.staus_code == 11%}
                            {{match.home_score}} : {{match.away_score}}

                        {% elif match.status_code == 3 %}
                            {{match.home_score}} : {{match.away_score}}

                        {% endif %}
                        
                    </div>
                    <div class="away">
                        <img src="{{match.away_logo}}"> 
                        {{match.away_name}}
                    </div>
                </div>
            </div>
        {% endfor %}
    {% endfor %}
</div>
{% endblock %}

def request_games(start, end):

params = (
   ("season_id","1511"),
   ("date_from",start.strftime("%Y-%m-%d")),
   ("date_to",end.strftime("%Y-%m-%d"))
);

headers = {
"apikey": //my api key
}

response = requests.get('https://app.sportdataapi.com/api/v1/soccer/matches', headers=headers, params=params)
r = response.json()

data = r["data"]
number = len(data)
matches = []
for i in range(number):
    match = {}
    match['status'] = data[i]["status"]
    match['status_code'] = data[i]["status_code"]
    match['minute'] = data[i]['minute']

    full_date = data[i]["match_start"]
    dt = datetime.strptime(full_date, '%Y-%m-%d %H:%M:%S')
    match['date'] = dt.date()
    match['time'] = dt.time()
    match['start'] = full_date

    home_team = data[i]["home_team"]
    match['home_name'] = home_team['name']
    match['home_logo'] = home_team['logo']

    away_team = data[i]["away_team"]
    match['away_name'] = away_team['name']
    match['away_logo'] = away_team['logo']

    stats = data[i]['stats']
    match['home_score'] = stats['home_score']
    match['away_score'] = stats['away_score']
    matches.append(match)

matches.sort(key = lambda x: datetime.strptime(x['start'], '%Y-%m-%d %H:%M:%S'))

return matches

Tags: divhomedatadatematchstatuscodestart
1条回答
网友
1楼 · 发布于 2024-04-24 22:58:24

首先,一旦您决定开始处理不刷新但仍查询服务器并进行更改的页面,您的解决方案之一就是开始使用AJAX调用来查询服务器上的不同数据

这将为您的项目添加一些代码。 例如,您的home.html模板需要分成两部分。确保还将jQuery添加到您的头部

sporty/home.html

{% extends "sporty/layout.html" %}
{% load static %}


{% block body %}
    <div id="matchweek" class="box">
        {% include "sporty/matchweek.html" %}
    </div>
    <button type="button" value="p" onclick="weekControl(this)">Previous</button>
    <button type="button" value="n" onclick="weekControl(this)">Next</button>
    {% comment %} 
        Either place weekupdate.js in /static/ or give the path within static, 
        best would be to have a folder for javascript in static and use 'js/weekupdate.js' 
    {% endcomment %}
    <script src="{% static 'js/weekupdate.js' %}"></script>
{% endblock %}

sporty/matchweek.html

{{start}},{{end}}

{% regroup matches by date as date_list %}

{% for date in date_list %}

    <div class="the_date">
        {{date.grouper}}
    </div>

    {% for match in date.list %}
        <div class="match_container">
            <div class="status">
                {% if match.status_code == 1%}
                    {{match.minute}}'
                {% elif match.status_code == 11%}
                    HT
                {% elif match.status_code == 3 %}
                    Finished
                {% endif %}
            </div>
            <div class="match">
                <div class="home">
                    {{match.home_name}} <img src="{{match.home_logo}}">
                </div>
                <div class="score">
                    {% if match.status_code == 0 %}
                        {{match.time}}

                    {% elif match.status_code == 17 %}
                        TBD

                    {% elif match.status_code == 1%}
                        {{match.home_score}} : {{match.away_score}}

                    {% elif match.staus_code == 11%}
                        {{match.home_score}} : {{match.away_score}}

                    {% elif match.status_code == 3 %}
                        {{match.home_score}} : {{match.away_score}}

                    {% endif %}
                    
                </div>
                <div class="away">
                    <img src="{{match.away_logo}}"> 
                    {{match.away_name}}
                </div>
            </div>
        </div>
    {% endfor %}
{% endfor %}



因为每次都需要更新matchweekdiv的全部内容

views.py

def home(request):
    if request.is_ajax():
        template = 'matchweek.html'
        direction = request.GET.get('dir')
        if direction == 'n':
            request.session['weekoffset'] += 1
        elif direction == 'p':
            request.session['weekoffset'] -= 1
    else:
        template = 'home.html'
        request.session['weekoffset'] = 0
    offset = request.session['weekoffset']
    start = datetime.now().date() + timedelta(days=7*offset)
    end = start + timedelta(days=6)

    matches = request_games(start, end)

    return render(request, f"sporty/{template}",{
        "matches": matches,
        "start": start,
        "end": end
    })

您在函数中看到的是检查请求是否来自AJAX调用,并确定从那里做什么

/static/js/weekupdate.js

function weekControl(id) {
    var value = id.value;
    $.ajax({
        url: '', // The url suffix that leads to your home function, example: '/home/'
        type: "GET", // Http method
        data: {'dir': value}, // The data to be sent to the server.
        success: function (htmlres) { // What to do on success and response reaching back
            $("#matchweek").html(htmlres);
        }
    });
}

这里您看到的是对django视图的AJAX get调用,其中包含'dir'及其值的数据。返回时,jQuery将用新内容更改^div的内容

我还没有测试过,但请告诉我这是否有效,如果您有任何问题

相关问题 更多 >