【问题标题】:Django: How to submit the form and receive the result on the same page without reloading the pageDjango:如何在不重新加载页面的情况下在同一页面上提交表单并接收结果
【发布时间】:2021-09-11 14:27:23
【问题描述】:

我在 django 工作,在那里我提交输入数据并在同一页面上接收操纵结果。每当我提交表单时,页面都会重新加载。我想在同一页面上接收经过操作的输出数据,而无需重新加载/刷新页面。

model.py 文件是这样的:

from django.db import models
from django.urls import reverse
# Create your models here.

class BFS(models.Model):
    description = models.TextField(blank=True, null=True)

forms.py 文件是这样的:

from django import forms
from .models import BFS

class BFSForm(forms.ModelForm):
    description = forms.CharField(
                        required=False, 
                        label=False,
                        widget=forms.Textarea(
                                attrs={
                                    'id': 'TA1',
                                    'rows': '10vh',
                                    'cols': '8vw',
                                    'placeholder': 'Enter Your Map Here',
                                    'class': 'textfield-style',
                                    'style': 'max-width: 100%; max-height: 100%;outline: none; border: none; background-color: white; width: 100%; padding: 12px 20px; margin: 8px 0; box-sizing: border-box; font-size: 20px; spellcheck="false";',
                                }
                            )
                        )
    
    class Meta:
        model = BFS
        fields = [
            'description'
        ]

views.py文件是这样的;

from django.shortcuts import render, get_object_or_404, redirect
from .forms import BFSForm
from .models import BFS
from .ml import Maze

# def product_create_view(request):
def bfs_view(request):
    form = BFSForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = BFSForm()

    try:
        image_url_info = None
        num_states_explored = None
        final_solution = None

        text_file = open("BFS\outputs\maze.txt", "w")
        field_name = 'description'
        input_value = BFS.objects.latest('id')

        field_object = BFS._meta.get_field(field_name)
        field_value = field_object.value_from_object(input_value)

        field_string_value = str(field_value).split("\n")
        text_file.writelines(field_string_value)
        text_file.close()

        m = Maze("BFS\outputs\maze.txt")
        print("Solving...")
        m.solve()
        m.output_image("static/search/bfs/maze.png", show_explored=True)

        image_url_info = "/../../../static/search/bfs/maze.png"
        num_states_explored = m.num_explored
        final_solution = str(''.join(m.end_result))

    except:
        print("BFS ERROR: Error in the try session of BFS in views.py")

    context = {
        'form': form, 'image_url': image_url_info, 'states_explored': num_states_explored, 
        'solution': final_solution
    }
    return render(request, "BFS/bfs.html", context)

BFS 应用程序urls.py 文件是这样的:

from django.conf import settings
from django.conf.urls.static import static

from BFS.views import bfs_view

app_name = 'BFS'

urlpatterns = [
    path('bfs/', bfs_view),
]


if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

bfs.html 文件是这样的:

<form method='POST'>{% csrf_token %}
   {{ form.as_p }}
   <input type='submit' value='Search' class="submit-btn poppins"/></a>
</form>

【问题讨论】:

标签: python jquery django ajax django-forms


【解决方案1】:

如果您使用经典的 HTTP 公式,则无法避免重新加载页面。

要实现您想要的,您需要在前端:

  • 进行 AJAX 调用
  • 在 Javascript 中处理页面的重新呈现

可以使用 VanillaJS 完成,或者您可以使用库来帮助您完成,例如 axiosjquery

【讨论】:

    【解决方案2】:

    是的,当您进行 ajax 调用或使用 javascript 时,这是可能的。 在提交 ajax 表单后,您可以这样做

    event.preventDefault()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-20
      • 2016-12-05
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 2016-12-27
      相关资源
      最近更新 更多