Home > Software design >  View not returning ID
View not returning ID

Time:12-19

I have a view that requires two args to be provided. Project_id and Questionnaire_ID

There is a Project and Questionnaire model.

class Questionnaire(models.Model):
    title = models.CharField(max_length=50, blank=False, unique=True)
class Project(models.Model):

    project_name = models.CharField(max_length=50, blank=False, unique=True)
    project_website = models.URLField(max_length=50, blank=True)
    project_description = models.TextField(blank=True)

I have a project details page, which is basically just a project landing page and from there I have a link to the questionnaire.

the link is formed via a For loop

{% for item in questionnaire %}
<a  href="{% url 'questions' project.id questionnaire.id %}?next={{ request.path|urlencode }}">Questionnaire</a>
{% endfor %}

and my url conf is path('questions/<int:project_id>/<int:questionnaire_id>', view=add_fundamental_answers_view, name="questions"),

but when i load the project_details page i get an error

Reverse for 'questions' with arguments '(1, '')' not found. 1 pattern(s) tried: ['questions/(?P<project_id>[0-9] )/(?P<questionnaire_id>[0-9] )$']

So it looks like the questionnaire_id is not being past in, but i'm not sure why?

def add_fundamental_answers_view(request, project_id, questionnaire_id):
    project = get_object_or_404(Project, pk=project_id)
    questionnaire = Question.objects.filter(questionnaire_id=questionnaire_id)
    next = request.POST.get('next', '/')
    if request.method =='POST':
            formset = AnswersForm()(request.POST)
            if formset.is_valid():
                answer = formset.save(commit=False)
                answer.project_name = project
                answer.save()
                return HttpResponseRedirect(next)
    else:
        form = AnswersForm()
    return render(request, 'pages/formset.html', {'project': project, "form": form,'questionnaire':questionnaire})   

Any ideas where I'm going wrong?

Thanks

CodePudding user response:

If you see the error, it says : with arguments '(1, '')'

1st argument is 1, second is None/Empty. But, your url expects 2 arguments.

path('questions/<int:project_id>/<int:questionnaire_id>'...)

You need to change :

{% for item in questionnaire %}
<a  href="{% url 'questions' project.id questionnaire.id %}?next={{ request.path|urlencode }}">Questionnaire</a>
{% endfor %}

To this

{% for item in questionnaire %}
<a  href="{% url 'questions' project.id item.id %}?next={{ request.path|urlencode }}">Questionnaire</a>
{% endfor %}

instead of questionnaire.id use item.id.

Questionnaire is a queryset, instead you want the id of instance.

  • Related