Как создать и обновить объект внешнего ключа в Django с помощью Ajax
У меня есть модель Poller
и Vote
с внешним ключом. Теперь в моем шаблоне я отображаю VoteForm
следующим образом:
<form method="post" action="" id="vote-form">
{% csrf_token %}
<div id="vote-choice-one" class="vote-choice-div">
{{ vote_form.poller_choice_one_vote.label }}
{{ vote_form.poller_choice_one_vote }}
</div>
<div id="vote-choice-two" class="vote-choice-div">
{{ vote_form.poller_choice_two_vote.label }}
{{ vote_form.poller_choice_two_vote }}
</div>
</form>
VoteForm
class VoteForm(ModelForm):
poller_choice_one_vote = forms.BooleanField(widget=forms.CheckboxInput(attrs={
'required': False,
'hidden': True
}))
poller_choice_two_vote = forms.BooleanField(widget=forms.CheckboxInput(attrs={
'required': False,
'hidden': True
}))
class Meta:
model = Vote
fields = ['poller_choice_one_vote', 'poller_choice_two_vote']
Теперь, когда пользователь нажимает на поле choice_one_vote
в шаблоне, я хочу, чтобы ajax обновил базу данных async. Теперь я застрял на обработке желаемого результата через представление в базу данных.
Также я не уверен, что это самый простой подход, особенно в плане рендеринга формы и использования ajax, поскольку я не смог сделать это с помощью $('#vote-choice-one').on('check'
Вид
def submit_vote(request, poller_id):
# Get poller
poller = Poller.objects.get(poller_id=poller_id)
# Get the current user
user = request.user
if request.method == 'POST':
poller.vote.poller_choice_one_vote == True
## How to create a vote object at first and
## update it later on using the uuid of the poller object?
print('fired vote function')
response_data = 'worked'
return HttpResponse(json.dumps(response_data), content_type="application/json")
Вы можете создать объект Vote
с помощью poller_id=poller_id
:
from django.http import JsonResponse
from django.views.decorators.http import require_POST
@require_POST
def submit_vote(request, poller_id):
vote_object = Vote.objects.create(
poller_id=poller_id,
user=request.user,
poller_choice_one_vote=True
)
print('fired vote function')
response_data = 'worked'
return JsonResponse({'response': 'worked'})