I'm new with django and i'm trying to update fields in my view without redirecting, i'm trying to return a JSON file when a view function is called, but i can't seem to find how to do so withouth redirecting to some url.
I think it may have something to do with my urls.py: ... path('#', views.myFunction, name='myFunctionName').
I'm messing arround with the django tutorial that appears in djangoproject.com
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
<a href="{% url 'polls:myfunction' %}">doFunction</a>
my view function goes like this:
def myfunction(request):
return JsonResponse({'ayy':'lmao'})
and the urls.py:
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path(r'#', views.myfunction, name='myfunction'),
path('form', views.FormView.as_view(), name='form'),
So what is most likely happening here is the Django URLS is finding the index page and redirecting to that view. The # pound or number symbol usually indicates a redirect in page.
First, there's no AJAX in your code. <a href="{% url 'polls:myfunction' %}">doFunction</a>
will redirect to an entire new page. Second, your path to myfunction
in urls.py is not correct.
Here's an example of what you can do. I also suggest you to read this . I use JQuery but feel free to adapt with what you prefer.
urls.py:
#...
path('ajax/domyfunction/', views.myfunction, name='myfunction')
]
html template:
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
<button id="b_function">doFunction</button>
<script>
$("#b_function").click(function () {
$.ajax({
url: '{% url "polls:myfunction" %}',
dataType: 'json',
success: function (data) {
alert(data.ayy);
}
});
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.