提问人:Яша Проценко 提问时间:11/13/2023 最后编辑:Яша Проценко 更新时间:11/14/2023 访问量:62
(Django、Ajax、FormMixin、Forms) 500(内部服务器错误) 在手机上提交表单时出错
(Django, Ajax, FormMixin, Forms) 500 (Internal Server Error) Error submitting form on mobile phone
问:
为了发送和接收响应,我使用了 Ajax、Django 和 Based View 类。 我想通过 Ajax 实现表单提交,以便在提交表单后页面不会重新加载。 为了将表单接收到服务器,我使用 FormMixin。 我不明白,这是服务器端的问题还是js的问题? 该网站的移动版本中存在 405 错误。
错误 Web 服务器:
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/django/template/bas
e.py", line 848, in _resolve_lookup
raise VariableDoesNotExist("Failed lookup for key "
django.template.base.VariableDoesNotExist: Failed lookup for
key [class] in {'required': True, 'id': 'id_form'}
Method Not Allowed (POST): /layouts/
Method Not Allowed: /layouts/
此错误仅在移动设备上出现。一切都可以在 PC 上运行。
urls.py
from django.urls import path
from .views import (
LayoutsDetail,
)
urlpatterns = [
path('layouts/<int:pk>', LayoutsDetail.as_view(), name='layouts_detail'
]
views.py:
import os
import json
from urllib import request
from django.conf import settings
from django.views.generic import TemplateView, ListView, DetailView
from django.views.generic.edit import FormMixin
from django.shortcuts import redirect
from django.http import JsonResponse
from mobile_template.views import MobileTemplateView
from .models import Layouts
from .forms import RequestPriceForm
class LayoutsDetail(MobileTemplateView, FormMixin, DetailView):
model = Layouts
template_name = 'main/layouts_detail.html'
form_class = RequestPriceForm
def get_success_url(self):
return reverse('layouts_detail', kwargs={'pk': self.object.id})
def get_context_data(self, **kwargs):
context = super(LayoutsDetail, self).get_context_data(**kwargs)
context['form'] = RequestPriceForm()
try:
pet = json.load(request.urlopen('https://pets.nlk.agency', timeout=1))
context['pet'] = pet['pet']
context['token'] = pet['token']
except:
context['token'] = None
context['pet'] = None
return context
def post(self, request, *args, **kwargs):
form = RequestPriceForm(request.POST)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_invalid(self, form):
response = super(LayoutsDetail, self).form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
url_from = self.request.META.get('HTTP_REFERER')
response = super(LayoutsDetail, self).form_valid(form)
if self.request.is_ajax():
form.send_email(url_from)
data = {
'message': "Successfully submitted form data."
}
return JsonResponse(data)
else:
return response
js:
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$(document).ready(function(){
async function SuccessReq(data, textStatus, jqXHR){
$("#form-request").modal("hide"),
$("#success-request").modal("show"),
$("#req-form")[0].reset(),
$("#success-request .success").css("display", "block"),
$("#success-request .error").css("display", "none")
}
async function ErrorReq(jqXHR, textStatus, errorThrown){
$("#success-request .error").css("display", "block"),
$("#success-request .success").css("display", "none")
}
$("#req-form").on("submit", function(e) {
e.preventDefault();
var $t = $(this).serialize(),
$o = $("#req-form").attr("data-url") || window.location.href;
$.ajax({
method: "POST",
url: $o,
data: $t,
success: SuccessReq,
error: ErrorReq
})
})
});
[HTML全文]
<div class="modal fade request-form" id="form-request" tabindex="-1" role="dialog" aria-labelledby="ModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h2 class="modal-title" id="ModalCenterTitle">Запит ціни на квартиру</h2>
</div>
<div class="modal-body">
<h4>Надішліть заповнену форму та ми зателефонуємо у зручний для вас час</h4>
<form id='req-form' method='POST' action='.'>
{% csrf_token %}
<div>
{% for field in form %}
<div class="form-group">
{{field.label_tag}}
<div>{{field}}</div>
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
{% if field.errors %}
{% for error in field.errors %}
<div class="alert alert-danger">
{{error}}
</div>
{% endfor %}
{% endif %}
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Скасувати</button>
<button type="submit" class="btn btn-primary">Надіслати</button>
</div>
<div class="msg-after-send" style="display:none">
<h5 class="modal-title">Запит надісланий! Очікуйте на дзвінок.</h5>
</div>
</form>
</div>
</div>
</div>
</div>```
How to fix the error? Need it very urgently.
答: 暂无答案
评论