Django -分页时保存表单域

von4xj4u  于 2023-01-10  发布在  Go
关注(0)|答案(1)|浏览(115)

这将是一个很长的帖子,请耐心等待,我刚刚开始使用Django,并试图了解它。我创建了一个网站,将通过考试问题一次一个,显示问题和多项选择题的答案,就像在无数其他网站。我遇到的挑战是,当用户点击分页按钮上的“下一步”,我想为选择的答案(选项)保存回数据库。我尝试了 AJAX 脚本,但视图从来没有得到执行。也许有一个更好的方法来做到这一点,或者你可以请我指出正确的方向?我将张贴我所有的代码,并希望有人可以请协助我。感谢您抽出时间查看此内容。
我从www.example.com开始models.py:

from django.db import models

class QuesModel(models.Model):
    question = models.TextField(null=True)
    code_snippet = models.TextField(null=True)
    op1 = models.CharField(max_length=200,null=True)
    op2 = models.CharField(max_length=200,null=True)
    op3 = models.CharField(max_length=200,null=True)
    op4 = models.CharField(max_length=200,null=True)
    ans = models.CharField(max_length=200,null=True)
    def __str__(self):
        return self.question

class Answer(models.Model):
    ans_id = models.AutoField(primary_key=True)
    question_id = models.ForeignKey(QuesModel, on_delete=models.CASCADE)
    fname = models.CharField(max_length=50)
    lname = models.CharField(max_length=50)
    examdate = models.DateField(auto_now_add =True)
    answer = models.PositiveSmallIntegerField()
    def __int__(self):
        return QuesModel.question[self.question_id]

模板是主页。html:

{% extends 'Quiz/dependencies.html' %}
{% block content %}
    {% load static %}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>       
       
    <div class="container">
        <h1>Welcome to my Quiz</h1>   
        {% for q in page_obj %}
            <form method="post" action="{% url 'submit_answers' %}">
                {% csrf_token %}
                <input type="hidden" name="question_id" value="{{ q.id }}">
                <!-- <input type="hidden" name="answer" value="{{ answer }}"> -->
                <input type="hidden" name="date" value="{{ default_date }}">
                <div class="form-group">
                    <div class="card text-bg-light mb-0" style="max-width: 50rem;">
                        <div class="card-header">
                            <code>
                                Question {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}<br>
                                {{q.question}}
                            </code>
                        </div>
                        <div class="card-body">
                        <class="card-text">
                        <label for="question">
                        <pre class="python"><code>{{q.code_snippet|linebreaks|escape}}</code></pre>
                        </label>
                        </div>
                    </div>
                    <br>
                    <div class="form-check">
                       
                        <input class="form-check-input" type="radio" name="{{ q.question }}" id="option1" value="1" data-question-id="{{ q.id }} required>
                        <label class="form-check-label" for="option1">
                            {{ q.op1 }}
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="{{ q.question }}" id="option2" value="2" data-question-id="{{ q.id }} required>
                        <label class="form-check-label" for="option2">
                            {{ q.op2 }}
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="{{q.question}}" id="gridRadios1" data-question-id="{{ q.id }} value="3">
                        <label class="form-check-label" for="gridRadios1">
                            {{q.op3}}
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="{{q.question}}" id="gridRadios2" data-question-id="{{ q.id }} value="4">
                        <label class="form-check-label" for="gridRadios2">
                            {{q.op4}}
                        </label>
                    </div>
                    <br>
                </div>                 
            </div>
          </div>                
    </div>       
    {% endfor %}
    
    <div class="container">
        <nav aria-label="Page navigation example">
            <ul class="pagination">
                {% if page_obj.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a>
                </li>
                {% endif %}
                <li class="page-item disabled">
                    <a class="page-link" tabindex="-1" aria-disabled="true">Question {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</a>
                </li>
                {% if page_obj.has_next %}
                <li class="page-item">
                    <a class="page-link" href="{% url 'home' %}?page={{ page_obj.next_page_number }}" >Next</a>
                </li>
                {% endif %}
            </ul>
        </nav>
    </div>
    
    <div class="container">
        <input id='timer' type='hidden' name="timer" value="">
        <br>
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </form>
  
    {% block script %}
        <script>            
            const timer=document.getElementById('displaytimer')
            console.log(timer.textContent)
            const inputtag = document.getElementById('timer') 
            t=0
            setInterval(()=>{
                t+=1
                timer.innerHTML ="<b>Timer: " +t+" seconds</b>"
                inputtag.value = t
            },1000)
        </script>
        
    {% endblock script %}   
</div>
{% endblock %}

最后是views.py:

from django.shortcuts import redirect,render
from django.contrib.auth import login,logout,authenticate
from .forms import *
from .models import *
from django.http import HttpResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
import datetime

def home(request):
    print("HOMEVIEW")
    print("REQUEST METHOD=" + request.method)  # Debugging line
    print("POST=")
    print(request.POST)  # Debugging line
    # Render the question page
    if request.method == 'POST':
        print("IN POST")
    
    questions=QuesModel.objects.all()
    paginator = Paginator(questions, 1)
    page_number = request.GET.get('page')
    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        # If the page is not an integer, show the first page of results
        page_obj = paginator.page(1)
    except EmptyPage:
        # If the page is out of range, show the last page of results
        page_obj = paginator.page(paginator.num_pages)
    context = {
        'page_obj': page_obj,
        'answer': request.POST.get('answer'),  # define and pass answer to template
    }
    
    return render(request,'Quiz/home.html',context)

def save_answer(request):
  print("XXXXXXX")
  print(request.method)  # Debugging line
  print(request.POST)  # Debugging line
  if request.method == 'POST':
#         answer = request.POST['answer']
#         question_id = request.POST['question_id']
#         # Save the answer to the database
#         answer = Answer(question_id=question_id, examdate=default_date, answer=answer)
#         answer.save()
    return HttpResponse('Success')
  #Return an error response if the request method is not 'POST'
  return HttpResponse('Error: Invalid request method')

def submit_answers(request):
    print("submit_answers")
    if request.method == 'POST':
        print(request.POST)
        questions=QuesModel.objects.all()
        score=0
        wrong=0
        correct=0
        total=0
        incorrect_answers = []
        
        for q in questions:
            items = {'op1': q.op1, 'op2': q.op2, 'op3': q.op3, 'op4': q.op4}
            total+=1
            answer = request.POST.get(q.question) # Gets user’s choice, i.e the key of answer 
            print(request.POST.get(q.question))
            print(q.ans)
            print()
            if q.ans ==  request.POST.get(q.question):
                score+=10
                correct+=1
            else:
                if q.ans != request.POST.get(q.question):
                    wrong += 1
                    testvar=request.POST.get(q.question)
                    incorrect_answers.append({'question': q.question, 'correct_answer': q.ans, 'user_answer': request.POST.get(q.question) } )
                    
        percent = score/(total*10) *100
        context = {
            'score':score,
            'time': request.POST.get('timer'),
            'correct':correct,
            'wrong':wrong,
            'percent':percent,
            'total':total,
            'incorrect_answers': incorrect_answers,  # pass list to template
        }
        return render(request,'Quiz/result.html',context)



def default_date():
    return datetime.datetime.now()
 
def pageme(request):
    print("pageme_here")
    questions = QuesModel.objects.all()
    paginator = Paginator(questions, 1)
    page_number = request.GET.get('page')
    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    context = {
         'page_obj': page_obj,
     }

    
    return render(request, 'Quiz/pageme.html', context)
def saveme(request):
    # Perform some actions here, such as saving data to the database
    print("saveme_here")  # Debug statement
    return HttpResponse("Save successful")  # Return a response to the client


# def save_answer(request):
#   if request.method == 'POST':
#     answer = request.POST['answer']
#     question_id = request.POST['question_id']
#     # Save the answer to the database
#     answer = Answer(question_id=question_id, examdate=default_date, answer=answer)
#     answer.save()
#     return HttpResponse('Success')
#   return HttpResponse('Error')

# def home(request):
#     if request.method == 'POST':
#         print(request.POST)
#         questions=QuesModel.objects.all()
#         #answer
#         answer = request.POST.get('answer')
#         question_id = request.POST.get('question_id')
#         examdate = request.POST.get('date')
#         answer = Answer(question_id=question_id, examdate=examdate, answer=answer)
#         answer.save()
#         #end answer
#         score=0
#         wrong=0
#         correct=0
#         total=0
#         incorrect_answers = []
        
#         for q in questions:
#             items = {'op1': q.op1, 'op2': q.op2, 'op3': q.op3, 'op4': q.op4}
#             total+=1
#             answer = request.POST.get(q.question) # Gets user’s choice, i.e the key of answer 
#             print(request.POST.get(q.question))
#             print(q.ans)
#             print()
#             if q.ans ==  request.POST.get(q.question):
#                 score+=10
#                 correct+=1
#             else:
#                 if q.ans != request.POST.get(q.question):
#                     wrong += 1
#                     testvar=request.POST.get(q.question)
#                     incorrect_answers.append({'question': q.question, 'correct_answer': q.ans, 'user_answer': request.POST.get(q.question) } )
                    
#         percent = score/(total*10) *100
#         context = {
#             'score':score,
#             'time': request.POST.get('timer'),
#             'correct':correct,
#             'wrong':wrong,
#             'percent':percent,
#             'total':total,
#             'incorrect_answers': incorrect_answers,  # pass list to template
#         }
#         return render(request,'Quiz/result.html',context)

#     else:
#         questions=QuesModel.objects.all()
#         paginator = Paginator(questions, 1)
#         page_number = request.GET.get('page')
#         try:
#             page_obj = paginator.page(page_number)
#         except PageNotAnInteger:
#             page_obj = paginator.page(1)
#         except EmptyPage:
#             page_obj = paginator.page(paginator.num_pages)
#         context = {
#             'page_obj': page_obj,
#         }
#         return render(request,'Quiz/home.html',context)

 
def addQuestion(request):    
    if request.user.is_staff:
        form=addQuestionform()
        if(request.method=='POST'):
            form=addQuestionform(request.POST)
            if(form.is_valid()):
                form.save()
                return redirect('/')
        context={'form':form}
        return render(request,'Quiz/addQuestion.html',context)
    else: 
        return redirect('home') 
 
def registerPage(request):
    if request.user.is_authenticated:
        return redirect('home') 
    else: 
        form = createuserform()
        if request.method=='POST':
            form = createuserform(request.POST)
            if form.is_valid() :
                user=form.save()
                return redirect('login')
        context={
            'form':form,
        }
        return render(request,'Quiz/register.html',context)
 
def loginPage(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
       if request.method=="POST":
        username=request.POST.get('username')
        password=request.POST.get('password')
        user=authenticate(request,username=username,password=password)
        if user is not None:
            login(request,user)
            return redirect('/')
       context={}
       return render(request,'Quiz/login.html',context)
 
def logoutPage(request):
    logout(request)
    return redirect('/')

请原谅这个混乱的代码,我尝试了各种各样的东西,现在我希望我能完成它与您的帮助。

ggazkfy8

ggazkfy81#

在这里,我尝试更改您的代码,并做了一些更改。
models.py

from django.db import models

class QuesModel(models.Model):
    question = models.TextField(null=True)
    code_snippet = models.TextField(null=True)
    op1 = models.CharField(max_length=200,null=True)
    op2 = models.CharField(max_length=200,null=True)
    op3 = models.CharField(max_length=200,null=True)
    op4 = models.CharField(max_length=200,null=True)
    ans = models.CharField(max_length=200,null=True)

    def __str__(self):
        return self.question

class Answer(models.Model):  
    ques = models.ForeignKey(QuesModel, on_delete=models.CASCADE)             
    fname = models.CharField(max_length=50)
    lname = models.CharField(max_length=50)
    examdate = models.DateField(auto_now_add =True)
    answer = models.CharField(max_length=200,null=True)

    def __int__(self):
        return self.ques__question

注意:Django为每个模型提供了一个默认的"id"字段,所以不需要ans_id,并且在Answer模型中,"question"字段被更新为别名"ques"
然后转到命令行并执行命令

python manage.py makemigrations
 python manage.py migrate

添加一些问题和答案

    • 查看次数. py**
from django.contrib.auth import login,logout,authenticate
from .forms import *
from .models import *
from django.http import HttpResponse, JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
import datetime
import json
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect

# here Disabling CSRF protection for this view function
@csrf_exempt
def home(request):
     if request.method == "GET":
          questions=QuesModel.objects.all()
          paginator = Paginator(questions, 1)
          page_number = request.GET.get('page')
          try:
               page_obj = paginator.get_page(page_number)
          except PageNotAnInteger:
               page_obj = paginator.page(1)
          except EmptyPage:
               page_obj = paginator.page(paginator.num_pages)

          context = {
                'page_obj': page_obj,
                'default_date': default_date
               }
          return render(request,'Quiz/home.html',context)

    # Render the question page
    if request.method == 'POST':
          parse_json = json.loads(request.body)
          for k,v in parse_json.items():
          ques = QuesModel.objects.get(id=int(k))
          answer = v
          obj, created = Answer.objects.update_or_create(
                      ques=ques, answer=answer,  
        defaults={'answer': answer, 'examdate': default_date, 'fname': "Bhavesh", "lname": "Patil"})

          return redirect('get-results')

# GET Result Page
def get_result(request):
     score=0
     wrong=0
     correct=0
     total= (QuesModel.objects.all().count()) * 10

    # Note you have to map user here I am keeping user static with fname -> Bhavesh and lname -> Patil ... Its me 
     get_answers = Answer.objects.filter(fname='Bhavesh', lname='Patil')
     for i in get_answers:
           if i.answer == i.ques.ans:
                score += 10
                correct += 1 
           else:
                wrong += 1

    percentage = score/total*100

    context = {'percent': round(percentage,2), 'correct':correct, 'wrong': wrong, 'total':total, 'score': score}
    return render(request, 'Quiz/results.html', context)

  
def default_date():
    return datetime.datetime.now()

def addQuestion(request):    
    if request.user.is_staff:
         form=addQuestionform()
         if request.method=='POST':
              form=addQuestionform(request.POST)
              if form.is_valid():
                  form.save()
                  return redirect('/')
         context={'form':form}
         return render(request,'Quiz/addQuestion.html',context)
   else: 
         return redirect('home') 

def registerPage(request):
    if request.user.is_authenticated:
         return redirect('home') 
    else: 
         form = createuserform()
    if request.method=='POST':
        form = createuserform(request.POST)
        if form.is_valid() :
            user=form.save()
            return redirect('login')
    context={
        'form':form,
    }
    return render(request,'Quiz/register.html',context)

def loginPage(request):
    if request.user.is_authenticated:
         return redirect('home')
    else:
         if request.method=="POST":
             username=request.POST.get('username')
             password=request.POST.get('password')
             user=authenticate(request,username=username,password=password)
         if user is not None:
             login(request,user)
             return redirect('/')
         context={}
         return render(request,'Quiz/login.html',context)

def logoutPage(request):
     logout(request)
     return redirect('/')
    • 注意:**复制代码时要小心......可能会出现 * 缩进错误 *,因此也要检查一下

现在用这个home.html替换你的主页模板(这里,我不知道'dependencies.html',所以我没有扩展它,所以我创建了home.html和results.html)
在文件夹"测验"中添加以下两个模板。测验将包含这些模板

Quiz |--- home.html
     |--- results.html
     |--- dependencies.html
     |--- ...
    • 主页. html**
{% comment %}<!-- {% extends 'Quiz/dependencies.html' %} --> {% endcomment %}

<!doctype html>
<html lang="en">
   <head>
   <!-- Required meta tags -->
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   <!-- Bootstrap CSS -->
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>      
</head>
 <body>
  {% block content %}
    {% load static %}
    <div class="container">
        <h1>Welcome to my Quiz</h1>   
        {% for q in page_obj %}
            <form>
                <input type="hidden" name="question_id" value="{{ q.id }}" id="questionID">
                <!-- <input type="hidden" name="answer" value="{{ answer }}"> -->
                <input type="hidden" name="date" value="{{ default_date }}">
                <div class="form-group">
                    <div class="card text-bg-light mb-0" style="max-width: 50rem;">
                        <div class="card-header">
                            <code>
                                Question {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}<br>
                                {{q.question}}
                            </code>
                        </div>
                        <div class="card-body">
                        <class="card-text">
                        <label for="question">
                        <pre class="python"><code>{{q.code_snippet|linebreaks|escape}}</code></pre>
                        </label>
                        </div>
                    </div>
                    <br>
                        <div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="question" id="option1" value="{{ q.op1 }}" data-question-id="{{ q.id }}" onchange="submitValue(this)">
                                <label class="form-check-label" for="option1">
                                    {{ q.op1 }}
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="question" id="option2" value="{{ q.op2 }}"" data-question-id="{{ q.id }}" onchange="submitValue(this)">
                                <label class="form-check-label" for="option2"  >
                                    {{ q.op2 }}
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="question" id="option3" data-question-id="{{ q.id }}" value="{{ q.op3 }}" onchange="submitValue(this)">
                                <label class="form-check-label" for="option3" >
                                    {{q.op3}}
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="question" id="option4" data-question-id="{{ q.id }}" value="{{ q.op4 }}" onchange="submitValue(this)">
                                <label class="form-check-label" for="option4">
                                    {{q.op4}}
                                </label>
                            </div>
                        </div>
                            <br>
                        </div>                 
                    </div>
                </div>                
            </div>       
            {% endfor %}
            
            <div class="container">
                <nav aria-label="Page navigation example">
                    <ul class="pagination">
                        {% if page_obj.has_previous %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a>
                        </li>
                        {% endif %}
                        <li class="page-item disabled">
                            <a class="page-link" tabindex="-1" aria-disabled="true">Question {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</a>
                        </li>
                        {% if page_obj.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="{% url 'home' %}?page={{ page_obj.next_page_number }}" >Next</a>
                        </li>
                        {% endif %}
                    </ul>
                </nav>
            </div>
            
            <div class="container">
                <input id='timer' type='hidden' name="timer" value="">
                <br>
                <button type="submit" onclick="submitResult()" class="btn btn-primary">Submit</button>
            </div>
        </form>
        
            {% block script %}
                <script>            
                    const timer=document.getElementById('displaytimer')
                    console.log(timer.textContent)
                    const inputtag = document.getElementById('timer') 
                    t=0
                    setInterval(()=>{
                        t+=1
                        timer.innerHTML ="<b>Timer: " +t+" seconds</b>"
                        inputtag.value = t
                    },1000)
                </script>
                
            {% endblock script %}   
        </div>
        {% endblock %}

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script>
    // this function will store user choose answer in session storage
    // you can see this storage -> just google it "how to see session storage in browser?"
    function submitValue(ele){
        var questionID = document.getElementById('questionID').value
        var answer = ele.value
        sessionStorage.setItem(questionID, answer);
    }
</script>

<script>
    // this script will keep track of user activity i.e retrive user answers from session storage. ie if you move to previous or next page user's choosed answers will be displayed.
    $(window).on('load', function(){
        console.log(sessionStorage)
        var questionID = document.getElementById('questionID').value
        var arrayElements = document.getElementsByClassName('form-check-input')
        if (sessionStorage.length){
            var value = sessionStorage.getItem(questionID)
            // console.log(arrayElements)
            const ele = Array.prototype.filter.call(arrayElements, (ele) => ele.value == value)
            console.log(ele)
            if (ele.length > 0){
                ele[0].checked = true;
            }
        }
    });
</script>

<script>
    // this function will send user result to server and redirect to result page
    function submitResult(){
        fetch("{% url 'home' %}", {
        method: "POST",
        body: JSON.stringify(sessionStorage),
        headers: {
            "Content-type": "text/html; charset=UTF-8"
        }
        }).then((response) => {
            window.location.replace("{% url 'get-results' %}");
            sessionStorage.clear();
        });
    }
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

</html>

下一步,将results.html添加到测验

    • 结果. html**
<!doctype html>
<html lang="en">
  <head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>Results</title>
  </head>
  <body>
     <div class="m-4">
     <table class="table table-bordered">
        <thead>
           <tr>
            <th colspan="2">Result</th>
           </tr>
        </thead>
        <tbody>
           <tr>
              <th scope="row">Wrong Answers</th>
                <td>{{wrong}}</td>
           </tr>
           <tr>
              <th scope="row">Correct Answers</th>
                <td>{{correct}}</td>
           </tr>
           <tr>
              <th scope="row">Total Score</th>
               <td>{{score}} / <span><b>{{total}}</b></span></td>
           </tr>
           <tr>
              <th scope="row">Percentage</th>
                 <td>{{percent}} %</td>
           </tr>
       </tbody>
  </table>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
 </body>
</html>
    • 注意:**:您可以在此处自定义上述模板...我保持了模板的简单性,并重点关注您的问题陈述

最后一步是路由URL,

    • 网址. py**
from django.contrib import admin
from django.urls import path
from .views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'),
    path('get-result/', get_result, name='get-results'),
    # ... your url routes
]
    • 这花了我一天的时间,所以请验证并让我知道这是否解决了您的问题...**

"谢谢你"

相关问题