如何通过 Ajax 在 Django 中创建外键对象 - Model.Foo"必须是"Bar"实例错误



我有一个模型PollerVote与外键。现在在我的模板中,我渲染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>
[...]
</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']

VoteModel

class Vote(models.Model):
poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote')
user = models.ForeignKey(Account, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
poller_choice_one_vote = models.BooleanField(default=False)
poller_choice_two_vote = models.BooleanField(default=False)

现在,一旦用户单击模板中的choice_one_vote字段,我希望ajax异步更新数据库。现在我被困在创建和处理由用户为投票人创建的新投票对象上。

/p>

// AJAX for posting
function create_vote() {
console.log("create post is working!") // sanity check
console.log($('#vote-choice-one').val())
$.ajax({
url : "submit-vote/", // the endpoint
headers: {'X-CSRFToken': csrftoken}, // add csrf token
type : "POST", // http method
data : { vote : $('#vote-choice-one').val() }, // data sent with the post request
[...]
});
};
<<p>视图/strong>

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':
# Create new Vote object
vote_object = Vote(poller=poller_id, user=user, poller_choice_one_vote=True)
# Save the object
vote_object.save()
print('fired vote function')
response_data = 'worked'
return HttpResponse(json.dumps(response_data), content_type="application/json")

返回

ValueError: Cannot assign "UUID('0bf8bb0d-cfdd-404c-93f6-34850388d87c')"; "Vote.poller"必须是"民意调查者"。实例。

您可以使用poller_id=poller_id:

创建Vote对象
from django.http importJsonResponse
from django.views.decorators.http importrequire_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'
returnJsonResponse({'response': 'worked'})

相关内容

  • 没有找到相关文章

最新更新