NoReverseMatch at/

hello there …was crating a quiz app for my e learning project and i faced NoReverseMatch probelm my all code is here
models.py:

from django.db import models
from django.contrib.auth.models import User
from courses.models import Modules,Courses



class Answer(models.Model):
	answer_text = models.CharField(max_length=900)
	is_correct = models.BooleanField(default=False)
	user = models.ForeignKey(User, on_delete=models.CASCADE)

	def __str__(self):
		return self.answer_text

class Question(models.Model):
	question_text = models.CharField(max_length=900)
	answers = models.ManyToManyField(Answer)
	points = models.PositiveIntegerField()
	user = models.ForeignKey(User, on_delete=models.CASCADE)

	def __str__(self):
		return self.question_text

class Quizzes(models.Model):
	module=models.ForeignKey(Modules,related_name='Quizzes',on_delete=models.CASCADE)
	title = models.CharField(max_length=200)
	description = models.CharField(max_length=200)
	date = models.DateTimeField(auto_now_add=True)
	due = models.DateField()
	allowed_attempts = models.PositiveIntegerField()
	time_limit_mins = models.PositiveIntegerField()
	questions = models.ManyToManyField(Question)
	


	def __str__(self):
		return self.title

class Attempter(models.Model):
	user = models.ForeignKey(User, on_delete=models.CASCADE)
	quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE)
	score = models.PositiveIntegerField()
	completed = models.DateTimeField(auto_now_add=True)

	def __str__(self):
		return self.user.username

class Attempt(models.Model):
	quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE)
	attempter = models.ForeignKey(Attempter, on_delete=models.CASCADE)
	question = models.ForeignKey(Question, on_delete=models.CASCADE)
	answer = models.ForeignKey(Answer, on_delete=models.CASCADE)

	def __str__(self):
		return self.attempter.user.username + ' - ' + self.answer.answer_text

class Completion(models.Model):
	user = models.ForeignKey(User, on_delete=models.CASCADE)
	course = models.ForeignKey(Courses, on_delete=models.CASCADE)
	completed = models.DateTimeField(auto_now_add=True)
	quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE, blank=True, null=True)

	def __str__(self):
		return self.user.username

class Completion(models.Model):
	user = models.ForeignKey(User, on_delete=models.CASCADE)
	course = models.ForeignKey(Courses, on_delete=models.CASCADE)
	completed = models.DateTimeField(auto_now_add=True)
	quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE, blank=True, null=True)
	#assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=True, null=True)

	def __str__(self):
		return self.user.username

my view.py

from django.shortcuts import render, redirect, get_object_or_404,reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden

from quiz.forms import NewQuizForm, NewQuestionForm
from quiz.models import Answer, Question, Quizzes, Attempter, Attempt,Completion
from django.contrib.auth.models import User
from courses.models import Modules,Courses


# Create your views here.

def NewQuiz(request, courses_id, modules_id):
	user = request.user
	module = get_object_or_404(Modules, id=modules_id)
	new_quiz=None
	if request.method == 'POST':
		quiz_form = NewQuizForm(request.POST)
		if quiz_form.is_valid():
			new_quiz=quiz_form.save(commit=False)
			new_quiz.module = module
			new_quiz.save()
			return reverse('quiz:new-question', courses_id=courses_id, modules_id=modules_id, new_quiz_id=new_quiz.id)
	else:
		quiz_form = NewQuizForm()

	context = {
		'quiz_form': quiz_form,
	}
	return render(request, 'quiz/newquiz.html', context)


def NewQuestion(request, course_ids, module_ids, new_quiz_id):
	user = request.user
	quiz = get_object_or_404(Quizzes, id=new_quiz_id)
	if request.method == 'POST':
		form = NewQuestionForm(request.POST)
		if form.is_valid():
			question_text = form.cleaned_data.get('question_text')
			points = form.cleaned_data.get('points')
			answer_text = request.POST.getlist('answer_text')
			is_correct = request.POST.getlist('is_correct')

			question = Question.objects.create(question_text=question_text, user=user, points=points)

			for a, c in zip(answer_text, is_correct):
				answer = Answer.objects.create(answer_text=a, is_correct=c, user=user)
				question.answers.add(answer)
				question.save()
				quiz.questions.add(question)
				quiz.save()
			return redirect('new-question', courses_id=courses_id, modules_id=modules_id, new_quiz_id=new_quiz_id)
	else:
		form = NewQuestionForm()

	context = {
		'form': form,
	}
	return render(request, 'quiz/newquestion.html', context)


def QuizDetail(request, courses_id, modules_id, new_quiz_id):
	user = request.user
	quiz = get_object_or_404(Quizzes, id=quiz_id)
	my_attempts = Attempter.objects.filter(quiz=quiz, user=user)

	context = {
		'quiz': quiz,
		'my_attempts': my_attempts,
		'courses_id': courses_id,
		'modules_id': modules_id,
	}
	return render(request, 'quiz/quizdetail.html', context)

def TakeQuiz(request, courses_id, modules_id, new_quiz_id):
	quiz = get_object_or_404(Quizzes, id=new_quiz_id)
	context = {
		'quiz': quiz,
		'courses_id': courses_id,
		'modules_id': modules_id,
	}
	return render(request, 'quiz/takequiz.html', context)

def QuizDetail(request, courses_id, modules_id, new_quiz_id):
	user = request.user
	quiz = get_object_or_404(Quizzes, id=new_quiz_id)
	my_attempts = Attempter.objects.filter(quiz=quiz, user=user)

	context = {
		'quiz': quiz,
		'my_attempts': my_attempts,
		'courses_id': course_id,
		'modules_id': module_id,
	}
	return render(request, 'quiz/quizdetail.html', context)


def SubmitAttempt(request, courses_id, modules_id, new_quiz_id):
	user = request.user
	quiz = get_object_or_404(Quizzes, id=new_quiz_id)
	earned_points = 0
	if request.method == 'POST':
		questions = request.POST.getlist('question')
		answers = request.POST.getlist('answer')
		attempter = Attempter.objects.create(user=user, quiz=quiz, score=0)

		for q, a in zip(questions, answers):
			question = Question.objects.get(id=q)
			answer = Answer.objects.get(id=a)
			Attempt.objects.create(quiz=quiz, attempter=attempter, question=question, answer=answer)
			Completion.objects.create(user=user, courses_id=courses_id, quiz=quiz)
			if answer.is_correct == True:
				earned_points += question.points
				attempter.score += earned_points
				attempter.save()
		return redirect('index')


def AttemptDetail(request, courses_id, modules_id, new_quiz_id, attempt_id):
	user = request.user
	quiz = get_object_or_404(Quizzes, id=new_quiz_id)
	attempts = Attempt.objects.filter(quiz=quiz, attempter__user=user)

	context = {
		'quiz': quiz,
		'attempts': attempts,
		'courses_id': courses_id,
		'modules_id': modules_id,
	}
	return render(request, 'quiz/attemptdetail.html', context)

urls.py:

from django.urls import path
from quiz.views import NewQuiz, NewQuestion, QuizDetail, TakeQuiz, SubmitAttempt, AttemptDetail

app_name ='quiz'
urlpatterns = [
	path('<courses_id>/modules/<modules_id>/quiz/newquiz/', NewQuiz, name='new-quiz'),
    path('<courses_id>/modules/<modules_id>/quiz/<new_quiz_id>/detail/', QuizDetail, name='quiz-detail'),
	path('<courses_id>/modules/<modules_id>/quiz/<new_quiz_id>/newquestion', NewQuestion, name='new-question'),
	path('<courses_id>/modules/<modules_id>/quiz/<new_quiz_id>/take', TakeQuiz, name='take-quiz'),
	path('<courses_id>/modules/<modules_id>/quiz/<new_quiz_id>/take/submit', SubmitAttempt, name='submit-quiz'),
	path('<courses_id>/modules/<modules_id>/quiz/<new_quiz_id>/<attempt_id>/results', AttemptDetail, name='attempt-detail'),

]

in the templates

 <div class="card pt-3 pb-3 text-center">
    <a href="{% url 'quiz:new-quiz' courses.id modules.id %}"> Create Exam </a>
  </div>

any one who can help me please

please help me any on who can???

In views.py you have return redirect(‘index’) and this index might be your index.html but in urls.py there is no index page where you are redirecting it specify a index path in urls.py, try this path(’’, views.Home, name=‘index’) because “return redirect(‘index’)” taking name from urls.py, and create Home page method in views. Hope this might help…

i removed TakeQuiz, SubmitAttempt, AttemptDetail views and urls but still it is now working the same errors shown

It might help if you provide more details about the error. What is the complete error you are receiving, and what url are you accessing that is causing the error to be thrown? What does your root urls.py file look like?

1 Like

this is the error

NoReverseMatch at /courses/detail/modules/create_content/

Reverse for 'new-quiz' with arguments '('', '')' not found. 1 pattern(s) tried: ['courses/(?P<courses_id>[^/]+)/modules/(?P<modules_id>[^/]+)/quiz/newquiz\\Z']

when i tray to add content the problem is coming

This error message is telling you that neither courses.id nor modules.id have values in your context. If a variable doesn’t exist, the template engine itself doesn’t throw an error. The template engine is trying to build the url quiz:new-quiz - but without the required parameters.

1 Like

i used courses.id modules.id in this URL because they are required parameters in the new-quiz view for crating the new-quiz …why should they have value in the context …i mean i used there only for determine in which course and module the quiz is belongs to .so if i where wrong what should i do?

Templates are rendered using data in the context. (The Django template language: for Python programmers | Django documentation | Django)

The url tag is trying to render a url using two fields, courses.id and modules.id.

Those two fields either don’t exist or have a value of None:

You need to ensure those values are provided, in the context.

1 Like

how can i check Those two fields either don’t exist or have a value of None??
and i used them in the context like this

return reverse('quiz:new-question', courses_id=courses_id, modules_id=modules_id, new_quiz_id=new_quiz.id)

This:

has nothing to do with this:

The first is a function call in a view, there is no template being rendered and therefore no context. The second is a fragment of a template being rendered.

If you are unsure as to where the problem is occurring, you need to provide a lot more detail about the error you’re receiving and the exact and precise situation in which it occurs.

i was using reverse like this

return redirect('quiz:new-question', courses_id=courses_id, modules_id=modules_id, new_quiz_id=new_quiz.id)

almost i spent 2 days on it but i don’t know why it is not working …if you are interested i can share the project code for checking please!

Please provide all information about the error, the complete traceback from the console, what the url is that you are going to when the error occurs, what view is being executed and what template is being rendered.

Also, have you worked your way through either or both of the Official Django Tutorial or the Django Girls Tutorial?

the error is


and the course-detail template ie here

{% extends 'home.html' %}
{% load index %}
{% block body %}

<div class="card-header"><h1 class="text-center">{{courses.title}}
        {% if user.id == courses.instructor.id %}
        <a href="" class="ml-5 pl-5">Edit</a>
        {% endif%}
</h1></div>
{% if user.id == courses.instructor.id %}
        <h2><a href="{% url 'courses:create_module' courses.pk %}" class="btn btn-primary btn-block mt-3 mb-3">Add Module</a></h2>
        
        {% endif %}
{% for module in courses.modules.all%}
{% csrf_token %}
        <div class="ml-auto card mt-2">
                <div class="card-header"><h3>{{module.title}}</h3></div>

                <div class="card-body">
                {% if module.description != None%}
                        <div>
                                {{module.description}}
                        </div>
                {% endif%}
                {% if user.id == courses.instructor.id %}
                    <a href="{% url 'courses:create_content' %}" class="btn btn-success btn-block mt-3 mb-3">Add Content</a>
                {% endif %}
                {% for contents in module.contents.all %}
                        {% if contents.note != None%}
                                <p class="unselectable unprintable">{{contents.note}}</p>
                        {% endif %}
                        {% if contents.file.url != None%}
                                {% if contents.extension|index:1 in '.mp4,.mkv'  %}
                                <video class="sensitive" width="700", height="430" controls="controls"
                                controlsList="nodownload"
                                name="{{contents.extension|index:0}}">
                                        <source src="{{contents.file.url}}" type="video/mp4"></video> 
                                
                                {% else %}
                                <a href="{{contents.file.url}}">{{contents.extension|index:0}}</a>
                                {% endif %}
        
                        {% endif %}
                {% endfor%}
               
                </div>
        </div>
{% endfor %}
{% endblock body %}

the courses url.py is here

from django.urls import path
from . views import *
#from quiz.views import NewQuiz

app_name = 'courses'
urlpatterns = [
    path('', CourseListView.as_view(), name='list'),
    path('detail/<int:pk>/', CourseDetailView.as_view(), name='detail'),
    path('create/', create_course, name="create"),
    path('detail/<int:pk>/create_module/', create_module, name="create_module"),
    path('detail/modules/create_content/', create_content, name="create_content"),
   
]

create-content template


<section id="body" class="card-deck mt-5 pt-lg-5">
  <div class="card pt-3 pb-3 text-center">
    <a href="">Upload A file</a>
  </div>
  <div class="card pt-3 pb-3 text-center">
    <a href="">Upload a Video</a>
  </div>
  <div class="card pt-3 pb-3 text-center">
    <a href=""> Write Note </a>
  </div>
  <div class="card pt-3 pb-3 text-center">
    <a href="{% url 'quiz:new-quiz' course_id module.id %}"> Create Exam </a>
  </div>
</section>

{% endblock body%}

but when i removed

{% url 'quiz:new-quiz' course_id module.id %}"

this code from the create content template it works and give what the expected page
please help me ?? and tank you for your time


the image is here that the error occurred when i clicked the add content button

Ok, so you have identified the right line where the problem occurs.

Those parameters (course_id and module.id) don’t have values within the context of your template being rendered. You need to supply that.

traceback from the console is

Internal Server Error: /courses/detail/modules/create_content/
Traceback (most recent call last):
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\user\Desktop\djangoProject\courses\views.py", line 61, in create_content
    return render(request, 'courses/create_content.html')
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\base.py", line 170, in render
    return self._render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\test\utils.py", line 100, in instrumented_test_render
    return self.nodelist.render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\test\utils.py", line 100, in instrumented_test_render
    return self.nodelist.render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\template\defaulttags.py", line 446, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\urls\base.py", line 86, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "C:\Users\user\.virtualenvs\djangoProject-FvtBbisM\lib\site-packages\django\urls\resolvers.py", line 698, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'new-quiz' with arguments '('', '')' not found. 1 pattern(s) tried: ['courses/(?P<course_id>[^/]+)/modules/(?P<module_id>[^/]+)/quiz/newquiz\\Z']
[23/Dec/2021 18:07:50] "GET /courses/detail/modules/create_content/ HTTP/1.1" 500 168021
[23/Dec/2021 18:19:30,484] - Broken pipe from ('127.0.0.1', 61868)

[23/Dec/2021 18:24:07] "GET /courses/detail/modules/create_content/ HTTP/1.1" 200 3521

(We were posting at the same time - see my post prior to your post here.)

how can i supply ??i mean i don’t understand it! can you show me please?

When you render a template, how do you supply data to that template to be rendered?