JSRB
JSRB

Reputation: 2613

How to create a foreign key object in Django via Ajax - Model.Foo" must be a "Bar" instance error

I have a model Poller and Vote with foreign key. Now in my template I render the VoteForm as follows:

<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)

Now once the user clicks on the choice_one_vote field in the template I want ajax to update the database async. Now I'm stuck at creating and processing a new vote object made by the user for the poller.

Ajax

// 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

[...]
    });
};

View

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")

Returns

ValueError: Cannot assign "UUID('0bf8bb0d-cfdd-404c-93f6-34850388d87c')": "Vote.poller" must be a "Poller" instance.

Upvotes: 1

Views: 160

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

You can create a Vote object with 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'})

Upvotes: 1

Related Questions