Django stepped pit: PK

Verbatim large column  https://www.dazhuanlan.com/2019/08/26/5d634d9cb14d2/

In the "first Django application" , I summed up my for a preliminary understanding of Django application development process and sort of application development steps, I tried only appeared to process applications reproducible according to the blog post reads as follows according to the curriculum error:

This error occurs when selecting one title to vote in the polls after I entered the home, after the jump to the vote http://127.0.0.1:8000/polls/1/vote/, should have stands to reason http://127.0.0.1:8000/polls/1/results/, then I will check the target set in the vote /polls/views.py document () method, because I set the jump page in this method, as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

Analyze and solve

Combined information being given the information 'not enough values to unpack (excepted 2, got 1)', meaning that less of a value in the unpacking process, find get by Attorney source () method: Perform the query and return a single object matching the given keyword arguments. by a given keyword statement executes the query and return the object matching. request.POST is a dictionary-like object, allowing you to submit data access by key name. In the present embodiment, request.POST [ 'choice'] returns the ID of the selected option, the ID is the primary key, and therefore instead pk=request.POST['choice']can.

to sum up

When you create a new models instance, if no primary key, then Django will automatically create an id field as the primary key of the model, sometimes with id and pk to achieve the desired results, but pk more independent of the real primary key, that do not care about the primary key is called id or object_id. Pk may improve consistency and use, even if the model has a different primary key.

Reference material

Guess you like

Origin www.cnblogs.com/JimmyShen/p/11411771.html