Кажется, работает для меня ... но я использую jQuery $ (document) .ready (), чтобы убедиться, что моя страница загружена перед присоединением какого-либо события. Я думаю, вы могли бы сделать это на голом javascript с помощью:
window.onload = function()
{
els = document.getElementsByTagName("*");
for(i=0;i<els.length;i++) {
els[i].onkeypress=function(){alert("hello!");};
}
}
Кстати, вы не можете прикрепить к событию больше одной функции:
for(i=0;i<els.length;i++){
els[i].onkeypress=function(){alert("hello!");};
els[i].onkeypress=function(){alert("hello2!");};
els[i].onkeypress=function(){alert("hello3!");};
}
Элемент будет зарегистрировать только последний (он переопределяет предыдущую функцию), в этом случае «alert (« hello3! »);»
Предполагая, что в вашем urls.py
from django.urls import path
from .views import add_vote
urlpatterns = [
path('post/<int:post_id>/vote/add/', add_vote, name='add-vote'),
]
В вашем views.py
from django.shortcuts import redirect, render
def add_vote(request, post_id):
if request.method == 'POST':
# receive your POST data here
user_id = request.user.id
post_id = post_id
if not Votes.objects.filter(user_id=user_id, post_id=post_id).exists():
Votes.objects.create(**your_data)
redirect('your-desired-url')
else:
# your logic here
Я вижу, вы уже определили unique_together
в Meta
, так что вы можете использовать try except
from django.db import IntegrityError
try:
# your model create or update code here
except except IntegrityError as e:
if 'unique constraint' in e.message:
# duplicate detected