No Reverse Match error - django

I'm trying to make quiz_application by referring this one.https://github.com/tomwalker/django_quiz
When i try to access category page, i get this error.
NoReverseMatch at /quiz/category/
Reverse for 'quiz_category_list_matching' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['quiz/category/(?P<category_name>[\\w-]+)/$']
My files are following,
urls.py
from django.conf.urls import patterns, url
from .views import QuizListView, CategoriesListView,\
ViewQuizListByCategory, QuizUserProgressView, QuizDetailView
urlpatterns = patterns('quiz.views',
url(regex=r'^$',
view=QuizListView.as_view(),
name='quiz_index'),
url(regex=r'^category/$',
view=CategoriesListView.as_view(),
name='quiz_category_list_all'),
url(regex=r'^category/(?P<category_name>[\w.-]+)/$',
view=ViewQuizListByCategory.as_view(),
name='quiz_category_list_matching'),
url(regex=r'^progress/$',
view=QuizUserProgressView.as_view(),
name='quiz_progress'),
# passes variable 'quiz_name' to quiz_take view
url(regex=r'^(?P<slug>[\w-]+)/$',
view=QuizDetailView.as_view(),
name='quiz_start_page'),
url(regex=r'^(?P<quiz_name>[\w-]+)/take/$',
view='quiz_take',
name='quiz_question'),
)
views.py
import random
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render, render_to_response
from django.template import RequestContext
from django.utils.decorators import method_decorator
from django.views.generic import DetailView, ListView, TemplateView
from .models import Quiz, Category, Progress, Sitting, Question
class QuizListView(ListView):
model = Quiz
class QuizDetailView(DetailView):
model = Quiz
slug_field = 'url'
class CategoriesListView(ListView):
model = Category
class ViewQuizListByCategory(ListView):
model = Quiz
template_name = 'view_quiz_category.html'
def get_context_data(self, **kwargs):
context = super(ViewQuizListByCategory, self)\
.get_context_data(**kwargs)
category = get_object_or_404(Category,
category=self.kwargs['category_name'])
context['category'] = category
return context
def get_queryset(self):
category = get_object_or_404(Category,
category=self.kwargs['category_name'])
queryset = super(ViewQuizListByCategory, self).get_queryset()
return queryset.filter(category=category)
class QuizUserProgressView(TemplateView):
template_name = 'progress.html'
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(QuizUserProgressView, self)\
.dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(QuizUserProgressView, self).get_context_data(**kwargs)
progress = get_object_or_404(Progress, user=self.request.user)
context['cat_scores'] = progress.list_all_cat_scores()
context['exams'] = progress.show_exams()
return context
def quiz_take(request, quiz_name):
quiz = Quiz.objects.get(url=quiz_name.lower())
if request.user.is_authenticated() is True:
return user_load_sitting(request, quiz)
else: # anon user
return anon_load_sitting(request, quiz)
def user_load_sitting(request, quiz):
if quiz.single_attempt is True and\
Sitting.objects.filter(user=request.user,
quiz=quiz,
complete=True)\
.count() > 0:
return render(request, 'single_complete.html')
try:
sitting = Sitting.objects.get(user=request.user,
quiz=quiz,
complete=False)
except Sitting.DoesNotExist:
sitting = Sitting.objects.new_sitting(request.user, quiz)
except Sitting.MultipleObjectsReturned:
sitting = Sitting.objects.filter(user=request.user,
quiz=quiz,
complete=False)[0]
finally:
return user_load_next_question(request, sitting, quiz)
def user_load_next_question(request, sitting, quiz):
previous = False
if 'guess' in request.GET:
progress, created = Progress.objects.get_or_create(user=request.user)
guess = request.GET['guess']
question = sitting.get_first_question()
is_correct = question.check_if_correct(guess)
if is_correct is True:
sitting.add_to_score(1)
progress.update_score(question.category, 1, 1)
else:
sitting.add_incorrect_question(question)
progress.update_score(question.category, 0, 1)
if quiz.answers_at_end is not True:
previous = {'previous_answer': guess,
'previous_outcome': is_correct,
'previous_question': question,
'answers': question.get_answers(),
'question_type': {question.__class__.__name__: True}}
sitting.remove_first_question()
next_q = sitting.get_first_question()
if next_q is False:
# no questions left
return final_result_user(request, sitting, quiz, previous)
return render_to_response('question.html',
{'quiz': quiz,
'question': next_q,
'question_type': {next_q.__class__.__name__:
True},
'answers': next_q.get_answers(),
'previous': previous},
context_instance=RequestContext(request))
def final_result_user(request, sitting, quiz, previous):
score = sitting.get_current_score
incorrect = sitting.get_incorrect_questions()
max_score = quiz.get_max_score
incorrect_score = max_score - score
percent = sitting.get_percent_correct
sitting.mark_quiz_complete()
if quiz.exam_paper is False: # if we do not plan to store the outcome
sitting.delete()
if quiz.answers_at_end is False:
return render_to_response('result.html',
{'quiz': quiz,
'score': score,
'max_score': max_score,
'incorrect_score':incorrect_score,
'percent': percent,
'previous': previous},
context_instance=RequestContext(request))
else:
questions = quiz.get_questions()
return render_to_response('result.html',
{'quiz': quiz,
'score': score,
'max_score': max_score,
'incorrect_score':incorrect_score,
'percent': percent,
'questions': questions,
'incorrect_questions': incorrect},
context_instance=RequestContext(request))
def anon_load_sitting(request, quiz):
if quiz.single_attempt is True:
return render(request, 'single_complete.html')
if quiz.anon_q_list() in request.session:
return load_anon_next_question(request, quiz)
else:
return new_anon_quiz_session(request, quiz)
def new_anon_quiz_session(request, quiz):
"""
Sets the session variables when starting a quiz for the first time
"""
request.session.set_expiry(259200) # expires after 3 days
questions = quiz.get_questions()
question_list = [question.id for question in questions]
if quiz.random_order is True:
random.shuffle(question_list)
# session score for anon users
request.session[quiz.anon_score_id()] = 0
# session list of questions
request.session[quiz.anon_q_list()] = question_list
return load_anon_next_question(request, quiz)
def load_anon_next_question(request, quiz):
previous = False
if 'guess' in request.GET:
previous = question_check_anon(request, quiz)
request.session[quiz.anon_q_list()] = (request.
session[quiz.anon_q_list()][1:])
if not request.session[quiz.anon_q_list()]:
return final_result_anon(request, quiz, previous)
next_question_id = request.session[quiz.anon_q_list()][0]
next_question = Question.objects.get_subclass(id=next_question_id)
question_type = {next_question.__class__.__name__: True}
return render_to_response('question.html',
{'quiz': quiz,
'question': next_question,
'question_type': question_type,
'previous': previous},
context_instance=RequestContext(request))
def question_check_anon(request, quiz):
question = Question.objects.get_subclass(id=request.GET['question_id'])
is_correct = question.check_if_correct(request.GET['guess'])
if is_correct is True:
request.session[quiz.anon_score_id()] += 1
anon_session_score(request, 1, 1)
else:
anon_session_score(request, 0, 1)
if quiz.answers_at_end is not True:
return {'previous_answer': request.GET['guess'],
'previous_outcome': is_correct,
'previous_question': question}
else:
return {}
def anon_session_score(request, to_add=0, possible=0):
"""
Returns the session score for non-signed in users.
If number passed in then add this to the running total and
return session score
examples:
anon_session_score(1, 1) will add 1 out of a possible 1
anon_session_score(0, 2) will add 0 out of a possible 2
x, y = anon_session_score() will return the session score
without modification
"""
if "session_score" not in request.session:
request.session["session_score"] = 0
request.session["session_score_possible"] = 0
if possible > 0:
request.session["session_score"] = (request.session["session_score"] +
to_add)
request.session["session_score_possible"] = \
(request.session["session_score_possible"] + possible)
return request.session["session_score"], \
request.session["session_score_possible"]
def final_result_anon(request, quiz, previous):
score = request.session[quiz.anon_score_id()]
max_score = quiz.get_max_score
incorrect_score = max_score - score
percent = int(round((float(score) / max_score) * 100))
if score is 0:
score = "0"
session_score, session_possible = anon_session_score(request)
del request.session[quiz.anon_q_list()]
if quiz.answers_at_end is False:
return render_to_response('result.html',
{'score': score,
'max_score': max_score,
'incorrect_score':incorrect_score,
'percent': percent,
'previous': previous,
'session': session_score,
'possible': session_possible},
context_instance=RequestContext(request))
else:
questions = quiz.get_questions()
return render_to_response('result.html',
{'score': score,
'max_score': max_score,
'incorrect_score':incorrect_score,
'percent': percent,
'questions': questions,
'session': session_score,
'possible': session_possible},
context_instance=RequestContext(request))
category_list.html
{% extends 'base.html' %}
{% block title %}All Quizzes{% endblock %}
{% block content %}
<h2>Category list</h2>
<ul>
{% for cat in category_list %}
<li>
<a href="{% url 'quiz_category_list_matching' category_name=cat.category %}">
{{ cat.category }}
</a>
</li>
{% endfor %}
</ul>
{% endblock %}
I think the problem is url.py because i got some information when i searched.
Which part is wrong?
i understand the problem is that i cannot pass category_name in category_list.html to urls.py because when i remove <a href="{% url 'quiz_category_list_matching' category_name=cat.category %}">, it works even though the category list is not linked.
could you give me some idea to resolve this problem.

Django in CBV's by default assigns the model to object_list in order to override the assignment name change the context_object_name attribute:
class CategoriesListView(ListView):
model = Category
context_object_name = "category_list"

Related

How to return ordered objects from django CBV(ListView) when you click a button or link in the template

So I'm building an e-commerce store with Django(First project after learning). I need to click on Sort in the template, and have the CBV return an object that's ordered by either, price, or whatever field I specify in the request. This is what I have so far
Template
Sort by Lowest Price
View
class ClotheListView(ListView):
model = Clothe
paginate_by = 8
def get_filter_param(self):
# Grab the absolute url and then retrieve the filter param
filter_param = self.request.path.split("/")[-1]
return filter_param
def get_queryset(self):
filter_param = self.get_filter_param()
if(filter_param != ""):
queryset = self.model.objects.filter(cloth_gender=filter_param)
else:
queryset = self.model.objects.all()
return queryset
return clothes_filtered_list.qs
def get_ordering(self):
ordering = self.request.GET.get('ordering', '-cloth_price')
return ordering
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
Url.py
urlpatterns = [
path('', views.ClotheListView.as_view(), name="clothe_list"),
path('<slug:slug>', views.ClotheListView.as_view(),
name="clothe_list_category"),
path('<int:pk>/', views.ClotheDetailView.as_view(), name="clothe_detail")
]
ok, so this is how I did it:
Template
<span class="float-end d-none d-lg-block mt-3">
Sort by: Price -
High To Low |
Price:
Low to High
</span>
View
class ClotheListView(ListView):
model = Clothe
paginate_by = 8
def get_filter_param(self):
# Grab the absolute url and then retrieve the filter param
filter_param = self.request.path.split("/")[-1]
return filter_param
def get_queryset(self):
# code for price sorting
default_order = "cloth_name"
order_param = ""
user_filter = ""
try:
order_param = self.request.GET.get('ordering').strip()
except:
pass
try:
user_filter = self.request.GET.get('filter').strip()
except:
pass
order_by = order_param or default_order
# End of sorting code
filter_param = self.get_filter_param()
if(filter_param != "" or not filter_param):
if(user_filter != ""):
queryset = self.model.objects.filter(
cloth_gender=filter_param, cloth_category=user_filter)
else:
queryset = self.model.objects.filter(
cloth_gender=filter_param)
else:
queryset = self.model.objects.all()
return queryset.order_by(order_by)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
url.py
urlpatterns = [
path('', views.ClotheListView.as_view(), name="clothe_list"),
path('<slug:slug>', views.ClotheListView.as_view(),
name="clothe_list_category"),
path('<int:pk>/', views.ClotheDetailView.as_view(), name="clothe_detail")
]

Reverse for 'new-quiz' with arguments '(11, '')' not found. 1 pattern(s) tried: ['course/(?P<course_id>[^/]+)/(?P<module_id>[^/]+)/quiz/newquiz$']

here is my code views.py
from django.shortcuts import render, redirect, get_object_or_404
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
from courses.models import Module
from completion.models import Completion
# Create your views here.
def NewQuiz(request, course_id, module_id):
user = request.user
module = get_object_or_404(Module, id=module_id)
if request.method == 'POST':
form = NewQuizForm(request.POST)
if form.is_valid():
title = form.cleaned_data.get('title')
description = form.cleaned_data.get('description')
due = form.cleaned_data.get('due')
allowed_attempts = form.cleaned_data.get('allowed_attempts')
time_limit_mins = form.cleaned_data.get('time_limit_mins')
quiz = Quizzes.objects.create(user=user, title=title, description=description, due=due, allowed_attempts=allowed_attempts, time_limit_mins=time_limit_mins)
module.quizzes.add(quiz)
module.save()
return redirect('new-question', course_id=course_id, module_id=module_id, quiz_id=quiz.id)
else:
form = NewQuizForm()
context = {
'form': form,
}
return render(request, 'quiz/newquiz.html', context)
def NewQuestion(request, course_id, module_id, quiz_id):
user = request.user
quiz = get_object_or_404(Quizzes, id=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', course_id=course_id, module_id=module_id, quiz_id=quiz.id)
else:
form = NewQuestionForm()
context = {
'form': form,
}
return render(request, 'quiz/newquestion.html', context)
def QuizDetail(request, course_id, module_id, 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,
'course_id': course_id,
'module_id': module_id,
}
return render(request, 'quiz/quizdetail.html', context)
and quiz/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<course_id>/<module_id>/quiz/newquiz', views.NewQuiz, name='new-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/newquestion', views.NewQuestion, name='new-question'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/', views.QuizDetail, name='quiz-detail'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/take', views.TakeQuiz, name='take-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/take/submit', views.SubmitAttempt, name='submit-quiz'),
path('<course_id>/modules/<module_id>/quiz/<quiz_id>/<attempt_id>/results', views.AttemptDetail, name='attempt-detail'),
]
and template
<i class="material-icons"></i>Add new quiz
in the project urls.py
path('quiz/',include('quiz.urls')),
it says like this "Reverse for 'new-quiz' with arguments '(11, '')' not found. 1 pattern(s) tried: ['course/(?P<course_id>[^/]+)/(?P<module_id>[^/]+)/quiz/newquiz$']"which means it detect the first argument but not the others why???
Use single quotes in your template, so 'new-quiz' instead of "new-quiz":
<i class="material-icons"></i>Add new quiz

Using multiple models for django ecommerce cart

I'm making a cart for an ecommerce project that I am working on, at the moment the cart does work. However it only works for one model and I'm not sure how to make it work with more than one.
This is my contexts.py file in my cart folder:
from django.shortcuts import get_object_or_404
from courses.models import Course
from food_order.models import Food_order
def cart_contents(request):
"""
Ensures that the cart contents are available when rendering
every page
"""
cart = request.session.get('cart', {})
cart_items = []
total = 0
course_count = 0
for id, quantity in cart.items():
course = get_object_or_404(Course, pk=id)
total += quantity * course.price
course_count += quantity
cart_items.append({'id': id, 'quantity': quantity, 'course': course})
return {'cart_items': cart_items, 'total': total, 'course_count': course_count}
Here is my views.py
from django.shortcuts import render, redirect, reverse
# Create your views here.
def view_cart(request):
"""A View that renders the cart contents page"""
return render(request, "cart.html")
def add_to_cart(request, id):
"""Add a quantity of the specified product to the cart"""
quantity = int(request.POST.get('quantity'))
cart = request.session.get('cart', {})
if id in cart:
cart[id] = int(cart[id]) + quantity
else:
cart[id] = cart.get(id, quantity)
request.session['cart'] = cart
return redirect(reverse('index'))
def adjust_cart(request, id):
"""
Adjust the quantity of the specified product to the specified
amount
"""
quantity = int(request.POST.get('quantity'))
cart = request.session.get('cart', {})
if quantity > 0:
cart[id] = quantity
else:
cart.pop(id)
request.session['cart'] = cart
return redirect(reverse('view_cart'))
So I have 2 different classes I would like to be able to add to the cart from 2 different places on the ecommerce site. I am just uncertain how to acheive this.
If I do something along the lines of:
from django.shortcuts import get_object_or_404
from courses.models import Course
from food_order.models import Food_order
def cart_contents(request):
"""
Ensures that the cart contents are available when rendering
every page
"""
cart = request.session.get('cart', {})
cart_items = []
total_food_order = 0
total_course = 0
total = 0
product_count = 0
for id, quantity in cart.items():
course = get_object_or_404(Course, pk=id)
food_order = get_object_or_404(Food_order, pk=id)
total_course += quantity * course.price
total_food_order += quantity * food_order.price
product_count += quantity
cart_items.append({'id': id, 'quantity': quantity, 'course': course, 'food_order':food_order})
total = total_course + total_food_order
return {'cart_items': cart_items, 'total': total, 'product_count': product_count}
Then the resulting cart_items will be:
[{'id': '1', 'quantity': 1, 'course': <Course: Basic Order Taking>, 'food_order': <Food_order: Onions>}, {'id': '2', 'quantity': 3, 'course': <Course: Advanced Order Taking>, 'food_order': <Food_order: Peppers>}]
I understand why it's doing this, but I cannot think of a way to adjust my code to get the desired result. Any pointers would be very appreciated.
Thank you for your time.
I would suggest making an base model for all your models that need to be added to the cart, and use multi-table inheritence.
class BaseCartItem(models.Model):
price = models.DecimalField()
item_type = models.CharField(max_length=20, editable_false)
....
def save(*args, **kwargs):
self.item_type = self._get_item_type()
return super().save(*args, **kwargs)
def _get_item_type(self):
raise NotImplementedError
class Course(BaseCartItem):
....
def _get_item_type(self):
return "Course"
class FoodOrder(BaseCartItem):
....
def _get_item_type(self):
return "Food Order"
# if you want to add to the db
class Cart(models.Model)
item = models.ForeignKey(BaseCartItem, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
....
And in the views everything remains the same. You just use the ids of the base model rather than the child models.
The cart_contents is simplified a bit
def cart_contents(request):
"""
Ensures that the cart contents are available when rendering
every page
"""
cart = request.session.get('cart', {})
cart_items = []
item_groups = defaultdict(int)
total = 0
product_count = 0
items_map = {
item.id: item
for item in BaseCartItem.objects.filter(id__in=cart.keys()
}
for id, quantity in cart.items():
item = items_map[id]
item_group[item.item_type] += quantity * item.price
product_count += quantity
cart_items.append({'id': id, 'quantity': quantity, 'course': item, 'food_order':item})
total = sum(item_groups.values())
return {'cart_items': cart_items, 'total': total, 'product_count': product_count}

fetch id from url in class in django

I want to fetch id from url so that i can use the queryset in diff. mehtods of class. but it is showing:
schedule = get_object_or_404(Schedule, id=kwargs['pk'])
NameError: name 'kwargs' is not defined
Here's My Code:
class SubmitAttendanceView(View):
template_name = 'schedule/submit_attendance.html' # this html file will be included in 'schedule/scheduledetail.html'
form_class = AttendanceForm
schedule = get_object_or_404(Schedule, id=kwargs['pk'])
students = Student.objects.filter(course__id__in=schedule.course.all(), sem=schedule.sem, subject__id__contains=schedule.subject.id).order_by('roll_no')
def get(self, request, pk):
form = self.form_class()
return render(request, self.template_name, {'form': form, 'students': self.students})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
date = form.cleaned_data['lecture_date']
lecture = self.schedule.id
subject = self.schedule.subject.id
x = 1 # a counter to fetch each checkbox from template by their name
for student in self.students:
course = Course.objects.get(id=student.course.id)
mark = self.request.POST[f'mark{x}']
if not mark:
mark = 0
attendance = Attendance(lecture=lecture, subject=subject, course=course, student=student, lecture_date=date, mark=mark)
attendance.save()
x += 1
return redirect('schedule')
return render(request, self.template_name, {'form': form, 'students': students})
urls.py:
path('<int:pk>/submit/', SubmitAttendanceView.as_view(), name='submit-attendance')
in template:
<a class="btn btn-md btn-danger add-new my-2" type="button" href="{% url 'submit-attendance' schedule.pk %}">Submit Attendance</a>
also tell if there's another way in which i can pass the queryset to variable and use it in my class methods
Solved:
class SubmitAttendanceView(View):
template_name = 'schedule/submit_attendance.html' # this html file will be included in 'schedule/scheduledetail.html'
form_class = AttendanceForm
def get_schedule(self, value):
return get_object_or_404(Schedule, id=value)
def get_students(self, value):
schedule = self.get_schedule(value)
# specify Students queryset
students_queryset = Student.objects.filter(course__id__in=schedule.course.all(), sem=schedule.sem, subject__id__contains=schedule.subject.id).order_by('roll_no')
return students_queryset
def get(self, request, **kwargs):
form = self.form_class()
students = self.get_students(kwargs['pk'])
return render(request, self.template_name, {'form': form, 'students': students})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
date = form.cleaned_data['lecture_date']
schedule = self.get_schedule(kwargs['pk'])
lecture = Schedule.objects.get(id=schedule.id)
subject = Subject.objects.get(id=schedule.subject.id)
x = 1 # a counter to fetch each checkbox from template by their name
students = self.get_students(kwargs['pk'])
for student in students:
course = Course.objects.get(id=student.course.id)
mark = self.request.POST.get(f'mark{x}')
if not mark:
mark = 0
attendance = Attendance(lecture=lecture, subject=subject, course=course, student=student, lecture_date=date, mark=mark)
attendance.save()
x += 1
return redirect('schedule')
return render(request, self.template_name, {'form': form, 'students': students})
After Doing Above Changes in Code , It is Working Fine
You can't use kwargs in class attribute, becaue it's keyword argument that were passed to your view. You can use it in the view only.
class SubmitAttendanceView(View):
template_name = 'schedule/submit_attendance.html' # this html file will be included in 'schedule/scheduledetail.html'
form_class = AttendanceForm
def get_schedule(self, **kwargs):
return get_object_or_404(Schedule, id=kwargs['pk'])
def get_students(self, **kwargs):
schedule = self.get_schedule(kwargs)
# specify Students queryset
students_queryset = Student.objects.filter(...)
return students_queryset
def get(self, request, **kwargs):
form = self.form_class()
students = self.get_students(kwargs)
return render(request, self.template_name, {'form': form, 'students': students})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
date = form.cleaned_data['lecture_date']
schedule = self.get_schedule(kwargs)
lecture = schedule.id
subject = schedule.subject.id
x = 1 # a counter to fetch each checkbox from template by their name
students = self.get_students(kwargs)
for student in self.students:
course = Course.objects.get(id=student.course.id)
mark = self.request.POST[f'mark{x}']
if not mark:
mark = 0
attendance = Attendance(lecture=lecture, subject=subject, course=course, student=student, lecture_date=date, mark=mark)
attendance.save()
x += 1
return redirect('schedule')
return render(request, self.template_name, {'form': form, 'students': students})

TypeError receive_money() takes exactly 3 arguments (1 given)-Django

I am trying to pass 2 parameters to a view but it gives this type error
i dont know if its a problem with the urls or my redirect
//urls.py
urlpatterns = [
#
url(r'^receive/[a-zA-Z]+/[0-9]+/$', receive_money)
]
//subtract_money view
def subtract_money(request):
if request.user:
users = User.objects.all()
users_ids = users.values_list('id', flat=True)
users_list = []
for id in users_ids:
user = users.get(pk=id)
if user.username != "ravinkohli" and user.username != request.user.username:
users_list.append(user)
if request.POST and request.POST.get('amount'):
username = request.user.username
withdraw = request.POST.get('amount')
wallet = Wallet.objects.get(pk=request.user.userprofile.wallet_id_id)
# if withdraw > wallet.amount:
# return render(request, 'send_money.html', {'error': 'Amount can not be greater than balance','users': users_list})
wallet.subtract_money(withdraw)
wallet.save()
now = datetime.now()
trans = Transaction(from_name=username, wallet_id=wallet,to=request.POST.get('receiver'), date=now, amount=withdraw)
trans.save()
return redirect('/receive/%s/%s/' % (request.POST.get('receiver'), withdraw))
else:
return render(request, 'send_money.html',{'users': users_list})
else:
return HttpResponseRedirect('/login/?next={}'.format('/subtract_money/'))
//receiver view
def receive_money(request, username, amount):
add_amount = amount
wallet = Wallet.objects.get(username=username)
wallet.add_money(add_amount)
wallet.save()
return redirect('user_profile.html', {'user': request.user,'userprofile': Userprofile.objects.get(user=request.user), 'wallet': wallet})
Since you are expecting 2 arguments it should be
url(r'^receive/(?P<username>[a-zA-Z]+)/(?P<amount>[0-9]+)/$', receive_money)
try something with the following url, but I don't think its a good idea to construct a url like this.
urlpatterns = [
#
url(r'^receive/(?P<username>[a-zA-Z]+)/(?P<amount>[0-9]+)/$', receive_money)
]