简体   繁体   English

自动重新加载页面,而无需再次重新输入URL Django

[英]reload page automatically without needing to RE-enter URL again Django

My webpage consists of 2 parts, upper part is a section that let user to enter data while bottom part displays all the data in database in a table form. 我的网页由两部分组成, 上半部分是让用户输入数据的部分,而下半部分则以表格形式显示数据库中的所有数据。 When user selects "Add" button in the upper part, the data will be saved into database and being outputted in a table in bottom part of the webpage. 当用户选择上部的“添加”按钮时,数据将被保存到数据库中并输出到网页底部的表格中。 Is there anyway to show the table once i select the "Add" button ? 选择“添加”按钮后,是否仍然可以显示表格? Right now what the code is doing is when "Add" button is being selected, it will load a new form but then the whole table will disappear. 现在,代码的作用是选择“添加”按钮时,它将加载新表格,但整个表格将消失。 I have to manually type this address again " http://127.0.0.1:8000/hrfinance/lscholarship/ " then only the table will appear. 我必须再次手动键入此地址“ http://127.0.0.1:8000/hrfinance/lscholarship/ ”,然后才会显示该表。 Even with refreshing the page will not work. 即使刷新页面也不起作用。 Below is my code in 下面是我的代码

views.py: views.py:

def scholarship(request, id=None):
    query_results = []
    if request.method == "POST":
        form = ScholarshipForm(request.POST)
        if form.is_valid():
            scholarship = form.save(commit=False)
            scholarship.save()
    else:
        form = ScholarshipForm()
        id = request.GET.get('scholarship')
    query_results = Scholarship.objects.all()
    data = {
            'query_results':query_results,
            'form': form
           }
    return render(request, 'hrfinance/add_remove_scholarship.html', data)

models.py models.py

class Application(models.Model):
    studentID = models.CharField("Student ID", max_length=8, validators=[MinLengthValidator(8)], primary_key=True, default="")
    studentName = models.CharField("Student Name", max_length=500, default="")
    scholarship = models.TextField("Scholarship")

add_remove_scholarship.html add_remove_scholarship.html

<div align="center" >
<form method="POST" onsubmit="return validation()" action="">
{% csrf_token %}
{{ form.errors }}
    <p>Upload File: {{ form.doc }}</p>
    <p>Faculty: {{ form.faculty }} </p>
    <p>Opening date: <input id="odate" type="date" name="openDate"> </p>
    <p>Closing date: {{ form.closeDate }} </p>
    <input type="submit" name="AddScholarship" value="Add Scholarship"   >
</form>
</div>
<br></br>
    <button id="button" type="button">Delete Selected Scholarship</button>
    <br></br>
    {{query_results}}
    <form method="POST" action="">
    {% csrf_token %}
<table  id="example" class="display" cellspacing="0" width="100%" border="1.5px">
    <tr align="center">
        <th> Scholarship </th>
        <th> Faculty </th>
        <th> Open Date </th>
        <th> Close Date </th>
    </tr>
    {% for item in query_results %}
    <tr align="center">
        <td>{{item.doc}}</td>
        <td>{{item.faculty}}</td>
        <td>{{item.openDate}}</td>
        <td>{{item.closeDate}}</td>
    </tr>
    {% endfor %}
    </table>
    </form>
def scholarship(request, id=None):
    query_results = []
    if request.method == "POST":
        form = ScholarshipForm(request.POST)
        if form.is_valid():
            scholarship = form.save(commit=False)
            scholarship.save()

    else:
        id = request.GET.get('scholarship')
    query_results = Scholarship.objects.all()
    form = ScholarshipForm()
    data = {
            'query_results':query_results,
            'form': form
           }
    return render(request, 'hrfinance/add_remove_scholarship.html', data)

you need to move the query out side the else condition. 您需要将查询移出else条件之外。

Although, this method would take a lot of time as the number of rows in the database increases. 虽然,随着数据库中行数的增加,此方法将花费大量时间。 A better method to do this would be to use jquery Ajax method to update the data in the database and show it dynamically using javascript/Jquery once the database is updated. 更好的方法是使用jquery Ajax方法更新数据库中的数据,并在更新数据库后使用javascript / Jquery动态显示它。

Best practice is to use the Post/Redirect/Get pattern. 最佳实践是使用Post / Redirect / Get模式。 This will solve your problems as well: the GET request will clear the form and show the new query results. 这也将解决您的问题:GET请求将清除表单并显示新的查询结果。

If the form is successfully saved, you simply return a redirect to the current page. 如果成功保存了表单,则只需将重定向返回到当前页面。 The browser will then do a GET request. 然后,浏览器将执行GET请求。 This prevents accidental duplicate form submissions when eg the user reloads the current page when it is still a POST request: 这样可以防止意外的表单提交,例如当用户仍是POST请求时重新加载当前页面时:

from django.shortcuts import redirect

def scholarship(request, id=None):
    query_results = []
    if request.method == "POST":
        form = ScholarshipForm(request.POST)
        if form.is_valid():
            scholarship = form.save(commit=False)
            scholarship.save()
            # Return a redirect to the same page
            return redirect('/path/to/current/page/')
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM