Получение : Not Found: /{% url "postQuestion" %} в приложении Django
Я запускаю приложение django, которое представляет собой поисковую систему базы знаний FAQ. Приложение работает на порту 8000 на localhost, в то время как модель BERT работает на localhost 5000. К сожалению, при нажатии на опцию "post a question" на фронтальной html-странице, запрос не попадает в созданное представление.
Фрагмент кода view.py моего приложения:
def postQuestion(request):
print ("---------------reposting-----------------")
dataOwners=db.dataOwners
if request.method=="POST":
json_dict={}
json_dict['User_ID']=request.user.id
json_dict['Question_asked']=request.POST['question']
json_dict['Category']=request.POST['cat']
json_dict['Sub-Category']=request.POST['subCat']
moderator_document = dataOwners.find({'Category' : json_dict['Category']})
mods_list=[]
for i in moderator_document:
mods_list.append(i['Moderator'])
json_dict['Moderators_available']=mods_list
json_dict['Moderator_assigned']='null'
json_dict['Status']="Pending Assignment"
json_dict['Answer_given']= 'null'
if 'revision' in request.POST and 'qid' in request.POST:
json_dict['Comments']="Query details corrected"
questionColl.find_one_and_update({"_id" : ObjectId(request.POST['qid'])},
{"$set":
{"Question_asked":json_dict['Question_asked'],"Category":json_dict['Category'] ,"Sub-Category":json_dict['Sub-Category'],"Moderators_available":mods_list,"Comments":json_dict['Comments'],"Status":json_dict['Status'] }
},upsert=True)
else:
json_dict['Comments']=request.POST['comments']
questionColl.insert_one(json_dict)
data=json.loads(json_util.dumps(json_dict))
return HttpResponse(data)
Идея заключается в том, что когда кто-то публикует вопрос из html front-end, управление переходит к вышеуказанной функции, которая затем помещает детали вопроса в коллекцию базы данных (локальная mongodb). Данные собираются через ajax вызов, который должен подтолкнуть детали вопроса к представлению "postQuestion". Однако я получаю ошибку, как показано ниже:
[28/Dec/2021 15:20:27] "POST /%7B%%20url%20%22postQuestion%22%20%%7D HTTP/1.1" 404 5624
Not Found: /{% url "postQuestion" %}
Мой сниппет вызова ajax:
// Post a question ajax call //
$(document).ready(function(event){
$(document).on("click","#postQuestion",function(event){
event.preventDefault();
//data to be pushed
//var userId=//get in views func
var question=$("#questionArea").val();
var category=$("#qCategory").val();
var subCat=$("#qSubCategory").val();
var comments=$("#commentArea").val();
$.ajax({
type: 'POST',
url: '{% url "postQuestion" %}',
data: {
'question':question,
'cat':category,
'subCat':subCat,
'comments':comments,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(response){
//get success object from python function and if submitted print success message
closeForm();
tata.success('Question posted for submission', 'Successful', {
animate: 'slide',
})
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
});
Проверил и мой urls.py, но ничего не работает
Мой код urls.py:
from django.urls import path
from django.conf.urls import url
from qgenie_app.views import read_file
from . import views
urlpatterns = [
path('',views.login,name='login'),
path('',views.login_sso,name='login_sso'),
path('home',views.home,name='home'),
path('review_content',views.review,name='review_content'),
path('view_status',views.viewStatus,name='view_status'),
path('searchresult',views.searchresult,name='searchresult'),
path('noresult',views.noresult,name='noresult'),
path('test',views.test,name='test'),
url('submitqnaquery',views.submitqnaquery,name='submitqnaquery'),
url('127.0.0.1:8000/autoComplete',views.autoComplete),
path('autoComplete',views.autoComplete,name='autoComplete'),
path('.well-known/pki-validation/C682779A4E94498415C0A5671AE311CA.txt', read_file),
#url('127.0.0.1:8000/likeView', views.likeView),
path('likeView',views.likeView,name='likeView'),
path('disLikeView', views.disLikeView, name='disLikeView'),
path('postQuestion', views.postQuestion, name='postQuestion'),
path('postAnswer', views.postAnswer, name='postAnswer'),
path('updatePostedQuestion', views.updatePostedQuestion, name='updatePostedQuestion'),
path('rejectQuestion', views.rejectQuestion, name='rejectQuestion'),
#path('commentsView',views.commentsView, name='commentsView'),
#url(r'^like/<int:pk>/$', LikeView, name='like_faq'),
#url(r'^submitqnaquery/$', TemplateView.as_view(template_name='searchresult.html'))
]
Похоже, что он не находит представление "postQuestion" по какой-то причине, которую я не могу понять. Может ли кто-нибудь пролить свет на это? Дайте мне знать, если требуется что-то еще. Спасибо!