nbc123
nbc123

Reputation: 31

Using a primary key within a form view (Django)

I have a form that is associated with a model, and want to specify the form data using the model's PK to log the response.

However, when I do this, I get the error: QuestionRecordSubmitView() got an unexpected keyword argument 'pk'

urls.py

    path('survey/<int:pk>/record_submit_question/', views.QuestionRecordSubmitView, name='survey-question-submit-record')

views.py

def QuestionRecordSubmitView(request):
model = Question

if request.method == 'POST':
    form = PostAudio(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('survey-share', kwargs={"pk": form.question}))
else:
    form = PostAudio()
return render(request, 'survey/question_audio_submit.html')

models.py

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    response_file = models.FileField(blank=True, upload_to='audio_responses')

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

forms.py

class PostAudio(forms.ModelForm):
    class Meta:
        model = Choice
        fields = ('response_file',)

Upvotes: 2

Views: 969

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

The view should accept a pk parameter, the primary key that is captured from the path. Furthermore, you should specify the question_id of the instance:

from django.shortcuts import redirect

def QuestionRecordSubmitView(request, pk):
    if request.method == 'POST':
        form = PostAudio(request.POST, request.FILES)
        if form.is_valid():
            form.instance.question_id = pk
            form.save()
            return redirect('survey-share', pk=pk)
    else:
        form = PostAudio()
    return render(request, 'survey/question_audio_submit.html')

Upvotes: 1

Related Questions