Я пытаюсь отправить запрос по почте через Ajax и Django, но получаю сообщение об ошибке 404, хотя URL-адрес POST является правильным URL-адресом, который я хочу использовать.
Вот моя форма свернуто Я пытаюсь отправить и оценить через кнопку.
<form class='my-ajax-form' method='POST'>{% csrf_token %}
<div class="btn-group" role="group" aria-label="Basic example">
<button type="text" class="btn btn-danger hard" name="hard" value="HARD">HARD </button>
</div>
</form>
Вот моя форма Ajax:
Мой код CSRF, поскольку я получал ошибку раньше, но не сейчас.
<script>
$(document).ready(function() {
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;
}
var csrftoken = getCookie('csrftoken');
var $endpoint = $(location).attr('href')
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Мой Ajax вызов:
$('.hard').click(function(e) {
event.preventDefault();
var $hard = $(".hard").text();
console.log($hard)
$.ajax({
method:'POST',
url: $endpoint,
data: $hard,
})
})
});
Мой файл URL
urlpatterns =[
path('profile/<int:pk>/', login_required(UserUpdateView.as_view()), name='profile'),
]
И мой результат → POST http://127.0.0.1: 8000 / profile / 11 / 404 (Not Found)
URL, по которому создается вызов: http://127.0.0.1: 8000 / profile / 11 /
Я просто хочу отправить запрос в View, нет ошибки на экране только в консоли.
Спасибо за любую помощь
View был запрошен, но POST запрос не достигает вида. Вот это
class UserUpdateView(UpdateView):
model = user_content
template_name = 'users/profile.html'
model_words = single_words_cards
def get(self, request, *args, **kwargs):
model = user_content
model_words = single_words_cards
template_name = 'users/profile.html'
user_id_fk = request.user.id
# Hide the sentance
if request.method == "POST":
if request.GET.get('hard') == 'hard':
print('hard was found')
else:
print('nothing')
hide = model.objects.filter(show_sentance = True).values('sentance_eng').filter(id=query)
model.objects.filter(id=retire).update(show_sentance='False')
print(retire )
#Querysets
user_sentances = model.objects.filter(show_sentance = True).values('sentance_eng', 'sentance_esp', 'id', 'username_id', 'show_sentance').filter(username_id = user_id_fk)
zip_flash_sentances = model.objects.filter(show_sentance=True).order_by("?").filter(username_id = user_id_fk).values_list('sentance_eng', 'sentance_esp', 'id').first()
number_sentances_today = model.objects.filter(show_sentance=True).values_list('sentance_eng').filter(username_id = user_id_fk).count()
word_cards_esp = list(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk))
word_cards_eng = list(model_words.objects.filter(show_word=True).values_list('word_eng').filter(username_id = user_id_fk))
number_of_cards = len(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk))
value = random.randint(0,number_of_cards)-1
words_esp = word_cards_esp[value]
words_eng = word_cards_eng[value]
return render(request, template_name, {'sentances_list': user_sentances,
'zip_flash_sentances':zip_flash_sentances,
'words_esp':words_esp,
'words_eng':words_eng,
'number_sentances_today':number_sentances_today,
'number_of_cards':number_of_cards,
'user_id_fk': user_id_fk,
})