Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Left joint existing Django QuerySet
I am trying to left join two query in Django. Is there any way to do that? I tried to combine the result in python but I realized that I have to edit the result more times in my templates so that would be more comfortable me to use left join my queries. Also In my future work would be very useful If I know the method of this. Thank you in advance for your help. My first query (1) and result is: Query (1) query:1=Table.objects.all() .filter(time_stamp__range=(before_now_week, now)). .filter(field__gt=0.01) .filter(field__lte=0.03) .annotate(day=TruncDay('time_stamp')) .values('day') .annotate(time=Count('time_stamp')) .annotate(field_count_1=Count('field')) .values('day','field_count_1') .order_by('-day') Result (1): day field_count_1 -------------------------|----------- 2018-01-17 00:00:00+01:00| 49 2018-01-16 00:00:00+01:00| 139 2018-01-15 00:00:00+01:00| 144 2018-01-14 00:00:00+01:00| 142 2018-01-13 00:00:00+01:00| 141 2018-01-12 00:00:00+01:00| 144 2018-01-11 00:00:00+01:00| 145 2018-01-10 00:00:00+01:00| 95 My first query (2) and result is: Query (2) query=Table.objects.all() .filter(time_stamp__range=(before_now_week, now)). .filter(field__gte=0.03) .annotate(day=TruncDay('time_stamp')) .values('day') .annotate(time=Count('time_stamp')) .annotate(field_count_2=Count('field')) .values('day','field_count_2') .order_by('-day') Result(2) day field_count_2 -------------------------|----------- 2018-01-17 00:00:00+01:00| 2 2018-01-16 00:00:00+01:00| 6 2018-01-14 00:00:00+01:00| 2 2018-01-13 00:00:00+01:00| 4 Desired result: day field_count_2 field_count_1 -------------------------|---------------|-------- 2018-01-17 00:00:00+01:00| 49 | 2 2018-01-16 00:00:00+01:00| 139 | 6 2018-01-15 00:00:00+01:00| 144 | 0 2018-01-14 00:00:00+01:00| 142 | 2 2018-01-13 00:00:00+01:00| 141 | 4 2018-01-12 00:00:00+01:00| 144 | 0 2018-01-11 00:00:00+01:00| 145 | … -
How to mock logging in Django Rest Framework unittest?
I have a unit test that tests whether an unauthorized user can GET a certain url. I want to use unittest.mock to mock the logging in the request. How can I point the decorator to use the correct logger ? My test looks like: @patch(what goes here???) def test_response_list_not_authenticated(self, mock_logging): url = django.core.urlresolvers.reverse("project-api:response-list", args=[6]) response = self.client.get(url, format="json") self.assertEqual(response.status_code, rest_framework.status.HTTP_401_UNAUTHORIZED) self.assertEqual(mock_logging.error.called, True) -
Django: Custom Default manytomany manager with a parameter
Following model allows me to handle translations in the database without adjusting code in order to add a language. class NameString(models.Model) en = models.CharField(max_length=55) de = models.CharField(max_length=55) Example use in model called Item: class Item(models.Model): name = models.ForeignKey(NameString) I use a ReadOnlyModelViewSet to view through an api. Which returns the following json: "results": [ { "id": 1, "name": 3, } ] I would like to replace the id value in name field of the json with the actual name in a given language. This is possible by annotating the queryset as for example: name_field = 'name__{}'.format(self.language()) queryset = Item.objects.annotate(name_value=F(name_field)) If I use a serializer with a value name_value, I get the following json: "results": [ { "id": 1, "name_value": 'cucumber', } ] My question is how do I use following model: class ItemList(models.Model): items = models.ManyToManyField(Item) So that I get a following json: "results": [ { "id": 1, "name": "item_list_1", "items" [ { "id": 1, "name_value": "cucumber" }, { "id": 2, "name_value": "apple" } ], } ] Can I somehow change the way the ItemList model handles the Item ManyToMany field? Some kind of custom default manager, that would handle the field response and add the annotation every time the … -
initiating an imagefield in django forms
I have this requirement that I need to initiate the django image field with an image. Here is the thing, 1 - the image with which I want to initiate is stored in s3. 2 - the image_url should be passed in the URL. 3 - that image_url(from the url) should be passed in the django forms, so that we can get the image in the ImageField, and initiate with that. I want to know, 1 - how can we pass url parameter to forms. 2 - How to initiate the form with image. How can it be done? -
Query a Dynamic Django Model based on Content Type
I would like to know if Django has an option to specify dynamic models from which objects need to be filtered when we write a class which would do some generic operations. To understand my requirement better, below is an example. Lets suppose I have the below models. models.py class AttendanceLog(models.Model) content_type = models.ForeignKey(ContentType, related_name="content_ty.....") object_id = models.PositiveIntegerField(default=0) content_object = GenericForeignKey('content_type', 'object_id') half_day = models.BooleanField(default=False) class Teacher(models.Model): user = models.ForeignKey(User) subject = models.CharField(max_length=100) class Staff(models.Model): user = models.ForeignKey(User) designation = models.CharField(max_length=100) class Student(models.Model): user = models.ForeignKey(User) start_date = models.DateTimeField(blank=True, null=True) And below is a class which would have a function that would let us know if a user has taken a half day off. attendance.py class Attendance(object): def __init__(self, request, content_type): self.user = request.POST.get('user', None) self.content_type = content_type def is_half_day(self): user_half_day = False if self.user: try: user = User.objects.get(id=self.user.id) except Exception: user = None if user: try: check_user = <model_name_can_be_Teacher_Staff_Student>.objects.get(user=user) except <model>.DoesNotExist: check_user = None if check_user: half_day_user = AttendanceLog.objects.filter( content_object=check_user, content_type=self.content_type, half_day=True) if user_half_day: user_half_day = True return user_half_day From the view, all I would need to pass would be the request and the content type of the model. The class method will decide which model to query and … -
Django: what is the difference between "overriding save()" and "using save signal"?
I think that anything that can be done with signal also can be done by overriding save() method in Model. If so, why do we need a signal? I can not find when to use the signal. Thanks -
JSON data parsing in Django AJAX POST Request
I'm getting below error whenever I send a JSON object via AJAX post request in Django. json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Code in html: $("#submit").click(function(){ var finalData{}; finalData.name = $('#name').val(); finalData.email = $('#email').val(); finalData.password = $('#password').val(); finalData.website = $('#website').val(); $.ajax({ url: window.location.pathname, type: "POST", data :finalData, success: function(){ }, error: function(){ } }); }); }); Code in Python: def signup(request): if request.method == 'POST': body = request.body response_json = body.decode('utf-8') x = json.loads(response_json) print(x) return render(request, 'signup.html', {}) else: return render(request, 'signup.html', {}) I'm able to print the response using below command in Python print(request.body) Sample JSON Data Object: { name: test, email: test@gmail.com, password: test, website: www.test.com } What exactly am I missing here? -
Django why is QuerySet iteration so slow?
I'm trying to create an accurate and efficient searching algorithm for the system. I installed Postgresql to utilize its trigram similarity query, and this is how i searched for objects: objects_found = Question.objects.extra(where=["CHAR_LENGTH(answer) > 300"])).filter(question__trigram_similar=message This was incredibly quick, It took it less than a 0.5s to perform most of the queries. All the objects of objects_found queryset are similar to query text, but i needed to find out the most similar one. I know two algorithms that are really good in this case, first one is Cosine Similarity, and the second one is Ratcliff/Obershelp pattern recognition (which has built-in implementation in Python). I tried making an iteration, testing each of them out, Cosine Similarity was around 1.5x times faster in majority of cases (as expected, considering that vectors are measured much more quickly), but SequenceMatcher would give more accurate results. Therefore i still chose SequenceMatcher. Please note that this iteration took a really long time. Finally, I tried implementing SequenceMatcher in the code: objects_found = (Question.objects.extra(where=["CHAR_LENGTH(answer) > 300"])).filter(question__trigram_similar=message).iterator() zsim = ("", 0) for i in objects_found: rsim = _search.ratcliff_obershelp(querytext, i.question) if zsim[1] < rsim: zsim = (i.answer, rsim) if rsim > 0.75: # works in most of the cases … -
django encountered with ConnectionResetError: [WinError 10054]
I am new to django and would like to write a simple log in web page frontend: html, css, javascript(using bootstrap and jquery) After filling the username and password and clicking the sign in button, it is supposed to jump to the home page. Here is my code: html: <form id="sign-form" role="form"> {% csrf_token %} <div class="form-group"> <label for="name" class="sr-only"> username </label> <input id="name" type="text" class="form-control" placeholder="Username..."> </div> <div class="form-group"> <label for="password" class="sr-only"> password </label> <input id="password" type="password" class="form-control" placeholder="Password..."> </div> <div class="form-group"> <button class="btn btn-block" id="sign-in-button"> Sign in </button> </div> <div class="form-group"> <button class="btn btn-block" id="sign-up-button"> Sign up </button> </div> </form> js: $("#sign-in-button").click(function () { var name=$("#name").val(); var word=$("#password").val(); $.post("/login/", { 'username': name, 'password': word }, function (result) { alert(result); } ); }); urls: urlpatterns = [ path('admin/', admin.site.urls), path(r'landing/', views.landing_page), path(r'login/', views.login), path(r'homepage/', views.home_page), ] views: def landing_page(request): return render(request, "landingPage.html") def login(request): print("here log in") if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = auth.authenticate(username=username, password=password) print(username+" out") if user is not None: auth.login(request, user) print(username) return render(request, "homePage.html", {'username': username}) return render(request, "homePage.html") return render(request, "homePage.html") But I encountered this problem(please have a look at the pictures): The remote host forced the closure … -
Django - annotate against a prefetch QuerySet?
is it possible to annotate/count against a prefetched query? my initial query below, is based on circuits, then I realised that if a site does not have any circuits I won't have a 'None' Category which would show a site as Down. conn_data = Circuits.objects.all() \ .values('circuit_type__circuit_type') \ .exclude(active_link=False) \ .annotate(total=Count('circuit_type__circuit_type')) \ .order_by('circuit_type__monitor_priority') So I changed to querying sites and using prefetch, which now has an empty circuits_set for any site that does not have an active link. is there a Django way of creating the new totals against that circuits_set within conn_data? I was going to loop through all the sites manually and add the totals that way but wanted to know if there was a way to do this within the QuerySet instead? my end result should have a something like: [ {'circuit_type__circuit_type': 'Fibre', 'total': 63}, {'circuit_type__circuit_type': 'DSL', 'total': 29}, {'circuit_type__circuit_type': 'None', 'total': 2} ] prefetch query: conn_data = SiteData.objects.prefetch_related( Prefetch( 'circuits_set', queryset=Circuits.objects.exclude(active_link=False).select_related('circuit_type'), ) ) -
Django request.POST get data from input
In HTML <form method='post'> {% csrf_token %} {{form.name}} {{form.email}} <textarea name='message'>{{form.message}}</textarea> <button type='submit'>Send</button> </form> How I can get the message data from my textarea in my view? Or the right way is put {{form.as_p}} in form? Please help -
Django (1.11) ORM using postgresql query is not able to compare date
Django (1.11) ORM using postgresql query is not able to compare date. I need data in between of leave_date_from and leave_date_to. I'm expecting one record. My model is as follows: class EmployeeLeaveApp(models.Model): user = models.ForeignKey(User, models.DO_NOTHING, on_delete=models.CASCADE) leave_date_from = models.DateField(blank=True, null=True) leave_date_to = models.DateField(blank=True, null=True) My View query is : inputdate = '2018-03-05' duplicateleave = crm_models.EmployeeLeaveApp.objects.filter( leave_date_from__gte=inputdate, leave_date_to__lte=inputdate, user=user) My table data is like below: leave_date_from | leave_date_to | user 2018-03-01 | 2018-03-10 | 1 2018-03-07 | 2018-03-22 | 1 So far, I tried many solutions but no luck. -
Django: create a model with fields derived from pandas dataframe
I have a pandas DataFrame from which I want to create a model whose fields are the df columns (and sets the right "Field" type for django). Googled around but could only find bulk_create() tips, which, for my understanding, creates different Models. My knowledge level: Django tutorial done, trying to exercise by creating this model from a big dataframe (many columns). -
Cannot plot matplotlib bar plot on HTML page - Runtime Error: main thread is not in main loop
I'm using Django to make a web page. I try to make a bar plot appear on my web page but receive the following error message: Traceback: File "C:\Python3.6\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Python3.6\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Python3.6\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\JNPou\Desktop\Den bæredygtige back-up\kogebog\opskriftssoegning\views.py" in Opskriftsside 132. bar_plot = make_bar_plot() File "C:\Users\JNPou\Desktop\Den bæredygtige back-up\kogebog\opskriftssoegning\plots.py" in make_bar_plot 46. fig = plt.figure() File "C:\Users\JNPou\AppData\Roaming\Python\Python36\site-packages\matplotlib\pyplot.py" in figure 539. **kwargs) File "C:\Users\JNPou\AppData\Roaming\Python\Python36\site-packages\matplotlib\backend_bases.py" in new_figure_manager 171. return cls.new_figure_manager_given_figure(num, fig) File "C:\Users\JNPou\AppData\Roaming\Python\Python36\site-packages\matplotlib\backends\backend_tkagg.py" in new_figure_manager_given_figure 1058. icon_img = Tk.PhotoImage(file=icon_fname) File "C:\Python3.6\lib\tkinter\__init__.py" in __init__ 3539. Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Python3.6\lib\tkinter\__init__.py" in __init__ 3495. self.tk.call(('image', 'create', imgtype, name,) + options) Exception Type: RuntimeError at /opskriftssoegning/carrot-dogs/ Exception Value: main thread is not in main loop Here is my Python code for creating the plot: import json import numpy as np import matplotlib.pyplot as plt, mpld3 import pandas as pd [...] def make_bar_plot(): height = [1, 2, 3, 3.33, 3.67, 4, 4.33, 4.67, 5, 6, 7, 8, 9, 10, 11, 11.33, 11.67, 12, 12.33, 12.67, 13, 14, 15] bars = ('1','2','3','4','5','6','7','8','9','10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23') … -
What's wrong i do? Django python. Displaing fields in template
Here is my model: class Child(models.Model): first_name = models.CharField(max_length=50) second_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) My view: def group_detail(request, group_name): if request.method == 'GET': group = Group.objects.name = group_name children = Child.objects.all() count_of_children = children.count() return render(request, 'group_detail.html', {'group': group, 'count_of_children': count_of_children, 'children': children}) else: return render(request, 'index.html') And I what to display in link like mysite/group/group_name details of selected group. Here I whant to display some fields, like this {{ group.group_name }} And my urls path('/group/<'group_name>', views.group_detail, name='group_detail') -
How to use autoescape off AND static variables inside django template
I am using auto generated HTML which has been saved to a file and then read in again to use as part of a page in a django template. In order to do this I have used: {% autoescape off %} {{ my_html }} {% endautoescape %} However, in the 'my_html' variable, I have some static content. This comes in the form of something like this: <img src="{% static "img/tree_report.png" %}" width="12px" height="12px"/> My issue is that the static content is not displayed. I get: http://127.0.0.1:8000/%7B%%20static 404 in the browser error report. I read something about get_static_prefix in another question but that doesn't solve my problem because I just get this instead: GET http://127.0.0.1:8000/%7B%%20get_static_prefix%20%%7Dimg/tree_report.png 404 (Not Found) I also tried endautoscape turning on and off periodically in my_html in the saved HTML variable. That also didn't work. Should I be autogenerating the development and production static files paths for my_html or is there a more elegant solution to this problem? Any suggestions are most welcome. Thanks. -
Celery + Django REST API + Redis: Trying to offload POST requests to Celery
I'm trying to offload POST request calls to our API to Celery, as we're going to be sending up to 10 requests per second to our API soon, each of which will have over 100 objects to create in our DB. I figured I'd add them to a queue and let Redis + Celery handle that then work from there. I'm running into a few issues though. First, my celery settings: ########## CELERY import djcelery djcelery.setup_loader() INSTALLED_APPS += ['expert.taskapp.celery.CeleryConfig'] CELERY_ACCEPT_CONTENT = ['json', 'pickle'] CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' BROKER_URL = 'redis://127.0.0.1:6379' CELERY_BROKER_URL = env('CELERY_BROKER_URL', default='redis://127.0.0.1:6379') if CELERY_BROKER_URL == 'django://': CELERY_RESULT_BACKEND = 'redis://' else: CELERY_RESULT_BACKEND = CELERY_BROKER_URL ########## END CELERY Using class basec views for my Django REST Framework, this is my view so far: from celery import shared_task from celery.decorators import task from .tasks import create class DataCreateAPIView(CreateAPIView): def create(self, request, *args, **kwargs): create.delay(request) So the idea is to let the create view handle everythng up until I get to the create portion of the process, where I immediately offload the create task to Celery. In my tasks.py file I then have this: from celery import shared_task from celery.decorators import task from expert.models import Chamber, Parameter, Sensor, Data @task(name='POST … -
Django Database query works on local machine, but not on server
This is the query: comment = AdditionalComment.objects.get(form = form, student = students[student]) and works perfectly on my local machine. Ive deployed the project to a DO VPS and whenever I try access the view i get this error even though I can see the AdditionalComment in the admin panel: File "/home/smartsurvey/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/smartsurvey/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/smartsurvey/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/smartsurvey/venv/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/smartsurvey/smart-survey/forms/views.py", line 195, in view_replies comment = AdditionalComment.objects.get(form = form, student = students[student]) File "/home/smartsurvey/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/smartsurvey/venv/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name forms.models.DoesNotExist: AdditionalComment matching query does not exist.` Any idea what it could be? let me know if you need anymore info -
Django + Angular 5 CSRF cross domain
I use Angular 5 for my UI and serve it using Apache. For the REST APIs I use Django and Apache. The Angular app is served on domain www.example.com and the REST API on api.example.com. Everything is served on HTTPS How do I get the 'csrftoken' cookie from Django when the Angular app loads and then send the cookie on subsequent interaction with the REST API? Right now my current approach is to hit an API (https://api.example.com/users/get_csrf_cookie/) with a service and then use Angular's HttpClientXsrfModule to send the cookie in subsequent AJAX requests. Even though I get the cookie, it is not set as seen in Chrome's Cookies in use and hence I'm not able to see it in Angular. -
Add custom data in Response() of django rest framework while GET?
I am using Django rest framework, I have to add my custom data in the Response() object. rsp = Response() rsp['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(file) rsp['X-Accel-Redirect'] = '/export/%s' % file I want to add custome dict in the data part of this Response() Hence I tried this, data = {'length': 10} rsp = Response(data) and data = {'length': 10} rsp = Response() rsp['data'] = data But I was getting error as 'error:{'data'}' Help me to understand why this behaviour occurred and How to add custom data in Response() -
How to return a django queryset in ajax httpresponse
I've been trying to retrieve a Django queryset and store it in a Javascript variable through Ajax. I'm currently trying to use the code below but I keep on receiving the "Queryset is not JSON Serializable. I'm quite new to both django and json formats. How do I workaround this? html/javascript page $.ajax({url: "http://127.0.0.1:8000/getPorts, success: function(result){ var res = JSON.parse(result); } }); views.py def getPorts(request): JSONer = {} ports = Port.objects.all() JSONer['ports'] = ports return HttpResponse(json.dumps(JSONer)) Also, if anyone would like to suggest a better way to use ajax to send/retrieve data to/from views, I am open to advice. Thank you -
How to integrate Vue.js with Django
I have a classic Django web project. Django renders also my templates. I wanted to implement Vue.js for some frontend functionalities (actually a search field) in the project. There is already a basic working version with separated files under my assets directory: assets/ css/ search.css js/ search.js How can I write a component-oriented structure for my project? -
run Serlizier's validation only in creating new post
hi i have 2 view that one of them use create and another one use RetrieveUpdateDestroyAPIView both use same Serlizier class i want have title validation only in create a post not on update a post ... this time i have title validation error when im updating some post with "PUT" request .. how can i fix this? class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = ProductSerializer def get_queryset(self): qs = Product.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) ).distinct() return qs def perform_create(self, serializer): serializer.save(author=self.request.user) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class StoreRucView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'pk' serializer_class = ProductSerializer permission_classes = [IsOwnerOrReadOnly] def get_queryset(self): return Product.objects.all() this is serlizer class full code: class ProductSerializer(ModelSerializer): product_ratings = ProductRatingSerializer(many=True,read_only=True) product_badges_set = ProductBadgesSerializer(many=True,read_only=True) author = serializers.SerializerMethodField() category = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name+' '+obj.author.last_name def get_category(self, obj): return obj.category.title class Meta: model = Product fields = [ 'product_id', 'author', 'category', 'title', 'description', 'price', 'level', 'video_length', 'created_date', 'updated_date', 'product_ratings', 'product_badges_set', ] read_only_fields = ['product_id', 'created_date', 'updated_date', 'author'] def validate_title(self, value): qs = Product.objects.filter(title__iexact=value) if self.instance: qs.exclude(pk=self.instance.pk) if qs.exists(): raise serializers.ValidationError("this title is already used") return value -
Django on AWS EC2 and RDS
I am trying to deploy django app on AWS by using EC2 and RDS services. I have created EC2 and RDS containers. Here is how i try to connect to my database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db name', 'USER': 'my user', 'PASSWORD': 'my password', 'HOST': 'awshost', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', }, } } For name, user, password, host, port I provide details from my RDS instance running. When I do: python manage.py migrate, It says there is no migration to apply. If I try to makemigrations, It says no changes detected. If I connect to database directly from terminal and list tables: I see one table django_migrations, which is empty. How should I migrate my db? I know this explanation is quite broad, I will try narrow it down, accordingly. For now I dont't know what else is important to this issue. -
'WSGIRequest' object has no attribute 'get' when executing form.is_valid()
I'm using Django 2.0.1 with Python 3.5.2 I'm getting this Error when doing form.is_valid() AttributeError: 'WSGIRequest' object has no attribute 'get' view.py: @method_decorator(login_required, name='dispatch') class CourseSelectionView(View): def get(self, request): form = CourseSelectionForm(request) selected_course = SelectedCourse.objects.filter(user=request.user) return render(request, 'profile/CourseSelection.html', context={ 'form': form, 'selected_course': selected_course, }) def post(self, request): form = CourseSelectionForm(request) if form.is_valid(): if not request.user.profile.can_select_this(int(self.request.POST.get('course_id'))): form.errors['course_id'] = "شما قادر به اضافه کردن درس دیگری نیستید." return render(request, 'profile/CourseSelection.html', context={ 'form': form }) request.user.profile.remaining_units = \ request.user.profile.remaining_units - int(self.request.POST.get('course_id')) return redirect(reverse_lazy('course_selection')) forms.py: class CourseSelectionForm(ModelForm): course_id = forms.IntegerField( max_value=10000000 ) class Meta: model = SelectedCourse fields = ('course_id',) def clean_course_id(self): course_id = self.cleaned_data.get('course_id') try: int(str(course_id)) except ValueError: raise ValidationError("Please enter a valid course") return course_id traceback: Internal Server Error: /profile/course_selection Traceback (most recent call last): File "/home/heh/Projects/PycharmProjects/acsrv2/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/heh/Projects/PycharmProjects/acsrv2/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/heh/Projects/PycharmProjects/acsrv2/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/heh/Projects/PycharmProjects/acsrv2/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/heh/Projects/PycharmProjects/acsrv2/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 62, in _wrapper return bound_func(*args, **kwargs) File "/home/heh/Projects/PycharmProjects/acsrv2/venv/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/heh/Projects/PycharmProjects/acsrv2/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 58, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/heh/Projects/PycharmProjects/acsrv2/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, …