Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Alternative for storing Image in Database Django
I am creating a simple e-commerce app using django, I need to store images but i realized that using database is a bad idea. I need detailed help on what i could do. -
Ajax function not working for next element played by 'for' in django template
I meet difficulties as below : I have a blog page. In blog ,i create 'comment' function to comment post. And comments has 'like' function. For this ,i create two view function ,one of them simple function ,second is api function. And create jquery ajax for to call api function. After api calling ,it update data in db. Problem is : If i create two comment ,ajax function works only for first comment for to like comment. It looks like ,for first comment CommentLikeAPIToggle works ,for next comments CommentLikeToggle works. Here is my codes : views.py class CommentLikeToggle(RedirectView): def get_redirect_url( self, *args, **kwargs): id = self.kwargs.get('id') obj = get_object_or_404(Comment,id=id) url_ = obj.content_object.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) return url_ from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions class CommentLikeAPIToggle(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request,id=None, format=None): obj = get_object_or_404(Comment,id=id) url_ = obj.get_absolute_url() user = self.request.user updated = False liked = False if user.is_authenticated(): if user in obj.likes.all(): liked = False obj.likes.remove(user) else: liked = True obj.likes.add(user) updated = True data = { 'updated':updated, 'liked':liked } return Response(data) Ajax function : function updateComLike (newCount,btn,verb){ btn.text(" "+newCount+ … -
python construct json string from dictionary
There is dictionary called myDict myDict = {"setA":[], "setB":[], "setC":"My string"} dictArrayA =[{"name":"kranthi"}, {"place":"kranthi"}] dictArrayB = [{"number":1}] myDict["setA"]=dictArrayA myDict["setB"]=dictArrayB which is converted into json string as follows strmyDict = json.dumps(myDict, ensure_ascii=True, indent=1) strmyDict is responded as http response in a django function views.py function as follows return Response(strmyDict) current output is as follows "{\n \"setA\": [\n {\n \"name\": \"kranthi\"\n }, \n {\n \"place\": \"kranthi\"\n }\n ], \n \"setB\": [\n {\n \"number\": 1\n }\n ], \n \"setC\": \"My string\"\n}" required output is a follows required = "{\n \"setA\": [{\n \"name\": \"kranthi\",\n \"place\": \"kranthi\"}],\n \"setB\": [{\n \"number\": \1,}],\n \"setC\": \"\My string"\n}" -
django replace html href and src to a {% static %} tag
how I can django replace html href and src to a static tag in Pycharm? For example: <link rel="stylesheet" href="libs/owlcarousel/assets/owl.carousel.min.css"> <a href="/"><img src="img/logo.png" alt=""></a> into <link rel="stylesheet" href="{% static 'landing/libs/owlcarousel/assets/owl.carousel.min.css' %}"> <a href="/"><img src="{% static "landing/img/logo.png" %}" alt=""></a> thx! -
Django link two apps
im currently facing the problem that i want to call a view from another app (accounts app which holds the user model) within my main app (a blog app). this is the error i get: django.core.exceptions.FieldError: Unknown field(s) (username) specified for User urls.py ... from quickblog import views as core_views from accounts import views as views_accounts ... url(r'^myaccount/$', views_accounts.view_profile, name='myaccount'), This is my first django app, is there maybe anything i need to know about linking two apps within one project? thanks -
Django-filter filter by related fields
I have two tables. class Writer(models.Model) name = model.CharField() ... class Article(models.Model) name = model.CharField() writer = model.ForeignKey('Writer', related_name="relationship") ... I wanted to build some API endpoints getting the parent, but this should be filterable by Article id. I am using django-filter. So: class WriterViewSet(viewsets.ReadOnlyModelViewSet): filter_backend = [filters.djangoFilterBackend], filter_class = WriterFilter class WriteFilter(django_filters.rest_framework.FilterSet): .... So my concern is, how can I define WriteFilter to filter Writer by the article? -
Django throws 'Cannot force an update in save() with no primary key.' error when user tries to log in
I am trying to log a user in order to display a webpage.I created my own login and signup forms and handle my own authentication for log in.I am using django's login() method. Now I know because I am not using django login and authentication, so I need to create an additional field called last_login which I did.Here is my django model class SignUp(models.Model): password = models.CharField(null=False, max_length=50) username = models.EmailField(null=False) last_login = models.DateTimeField(auto_now=True, blank=True) This signs up the user when the user hits /signup url.Below is the postgres table for the model. Column | Type | Modifiers ------------+--------------------------+----------- id | integer | username | character varying(100) | password | character varying(50) | last_login | timestamp with time zone | But when the user tries to log in with their username and password (after visiting /login url), I get the below error ERROR 2018-07-22 22:38:18,625 django.request Internal Server Error: /login Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view … -
What is the main difference between clean and full_clean function in Django model form?
What is the main difference between clean and full_clean function in Django model ? -
what technology I can use track user interaction on a Django web application?
I am currently building a Django web application that I want to track user interactions such as mouse movements, clicking a button, search results item they viewed,etc. -
How Can i Build a Django based web application which takes as input from user the below 3 parameters
How can I Build a Django based web application which takes as input from user the below 3 parameters: • IP address and Port • Username • Password Once SSH connection is established, the app should periodically (configurable parameter from front-end) collect metrics like • CPU utilization • Memory utilization • Running processes • Network Sent/Received -
Make Django model property writable in Django Rest Framework
A the title says, I have to make Django model property writable in DRF. Here's my models.py file, in which I have an 'index' field, which is taking the value of model id by default: class PhotoManager(models.Model): id = models.AutoField(primary_key=True) _index = models.PositiveIntegerField(null=True, default=None, blank=True) @property def index(self): if self._index is not None: return self._index return self.id However, 'index' value would be updated by a user after saving model instance, by calling PATCH method and DRF submit form doesn't have 'index input. So, I have to make it writable in Django Rest Framework or manage to save the value to the model field using a different approach. So I figured out, that I have to override some methods in serializers, like this, but can't find any decent examples on how to actually do it. Serializers.py: class IndexField(serializers.Field): def to_representation(self, obj): return /// def to_internal_value(self, data): return /// class PhotoSerializer(serializers.ModelSerializer): index = IndexField() def create(self, data): return ///// class Meta: model = PhotoManager fields = '__all__' Also I've tried to just set 'index' as serializers.IntegerField, but it doesn't change the situation and in overall DRF still asks for overriding class PhotoSerializer(serializers.ModelSerializer): index = serializers.IntegerField() Any help is appreciated -
Forbidden (CSRF token missing or incorrect.): /u/submit
views.py def form(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): form.save() return HttpResponse('done') else: form = StudentForm() return render(request,'submit.html',{'form':form}) urls.py urlpatterns = [ path('submit',views.form, name = 'submit') ] templates/html <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script src="{% static 'js/ajax2.js' %}" type="text/javascript"></script> </head> <body> <form class="form_ajax" method="post" data-url="/submit" > {% csrf_token %} {{ form }} <button id="btn" type="submit">Submit</button> </form> </body> ajax2.js $(document).ready(function(){ $('#btn').click(function(event){ event.preventDefault() var name = $('#id_name').val(); var marks = $('#id_marks').val(); var year = $('#id_year').val(); csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() $.ajax({ url :'/u/submit', type: 'POST', data :{'name':name,'marks':marks,'year':year}, success : function(data){ console.log(data); alert('created:',data); }, }); }); }); It shows Forbidden (CSRF token missing or incorrect.): /u/submit . therefore i tried to do js in different method $(document).ready(function(){ $('#btn').click(function(event){ event.preventDefault() var myForm = $('.ajax_form'); var formData = myForm.serialize(); var thisUrl = myForm.attr('data-url') || window.location.href; $.ajax({ url :thisUrl, type: 'POST', data :formData, success : function(data){ console.log(data); alert('created:',data); }, }); }); }); But it is sowing same 403 error, but as you can see i have given csrf_token in html form.But still its giving error.Even providing csrf middleware token in ajax its still now working.. What am i doing wrong? -
Django NoReverseMatch Exception error
I have 2 views which after a post was made with the 1st view, I redirect it to the 2nd view with some parameters but I get this error, NoReverseMatch def View1(request): if request.method == 'POST': #some back end codes here return redirect(View2, param1, param2) else: return render(request, 'View1.html') def View2(request, param1, param2): if request.method == 'POST': return render(request, 'View2.html') else: return render(request, 'View2.html') -
Django wrong current path in post request
When I try to login to admin page, after inserting credentials, I get this error: Page not found (404) Request Method: POST Request URL: http://****/admin/login/?next=/admin/ Raised by: django.contrib.admin.sites.login Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: ^$ [name='home'] ^admin/ pdf/<slug:id> report/<slug:id> The current path, login/, didn't match any of these As you can see, the current path Django is trying to match with pattern is "login" and not "admin/login" When I try to load admin login page I'm not getting any error, so with a GET request it matches the right URL, so I think there is a problem with the current path in POST requests. I'm hosting my website on A2hosting. I never had this problem running in local. -
When i take python manage.py makemigrations and then happening issues like below. Anyone have idea to pass them. Thanks
File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 327, in execute self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/nvs/services/sbox4net/urls.py", line 21, in from agents.monitor.views import SecurityEventsListView, SecurityEventsDetailsView, NetworkSecurityAlertDetailsView, File "/home/nvs/services/agents/monitor/views.py", line 14, in from django_filters.rest_framework import DjangoFilterBackend File "/usr/local/lib/python2.7/dist-packages/django_filters/init.py", line 4, in strong text from .filterset import FilterSet File "/usr/local/lib/python2.7/dist-packages/django_filters/filterset.py", line 184 def init(self, data=None, queryset=None, *, request=None, prefix=None): ^ -
Django2 AttributeError in urls.py
I'm getting started with Django but I'm stuck with an error while trying to execute python3 manage.py runserver . fmlg-backend/fmlg/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from core import views as coreviews urlpatterns = ['', url(r'^$', coreviews.home), path('admin/', admin.site.urls) ] fmlg-backend/core/views/views.py from django.shortcuts import render def home(request): return render(request, 'core/home.html') python3 manage.py runserver outputs : File "/home/florian/Workspace/project/fmlg-backend/fmlg/urls.py", line 22, in <module> url(r'^$', coreviews.home), AttributeError: module 'core.views' has no attribute 'home' What am I missing here ? -
why my sql 5.5 is not configuring?
i am using python and django. for that database connection, i need mysql, i have successfully installed the mysql 5.5 version and i am trying to configure the data base from django it is showing this error "ModuleNotFoundError: No module named 'django.contrib.staticfilesmodelpro1". i have downloaded the relevant packages by using, pip install pymysql. or pip install mysqlclient. whenever i am trying to install the packages related to mysqlclient, i was unable to download it. but i already installed the pymysql packages, is it fine or do i need to download the packages related to mysqlclient as well. Please help on this, because it is not configuring i am unable to move to the next part of the execution. -
Django Heroku Deploy: OSError: [Errno 2] No Such file or directory: '/app/{appname}/assets'
I've found similar questions but they were from years ago and the solutions haven't worked so far. Here's the traceback: (devtm) λ heroku run python manage.py collectstatic Running python manage.py collectstatic on ⬢ {appname}... up, run.1335 (Free) Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 112, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 397, in listdir for entry in os.listdir(path): OSError: [Errno 2] No such file or directory: '/app/{appname+"site"}/assets' Here's my settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, '../{appname+"site"}/assets'), os.path.join(BASE_DIR, '../{appname+"site"}/assets/css'), os.path.join(BASE_DIR, '../{appname+"site"}/assets/images'), os.path.join(BASE_DIR, '../{appname+"site"}/assets/js'), os.path.join(BASE_DIR, '../{appname+"site"}/assets/venue_images') ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' I've tried adding a directory (with blank file for git) named staticfiles to my root (so next to the manage.py file). I've tried adding a folder/file named assets in … -
Django table relation manytomany with two fields reference
I have a question related to database relation in Django. There are in total three tables, see below. The relation between KbMeta and Tdb is successfully established through Foreignkey method. However I dont know how to manage the relation between Posd and Tdb. The position 'hg' and 'pos' are unique in the Posd table but they are not unique in Tdb table. However when I compare the fields HG, and POS I should get the right reference. The following method doesn't work in Tdb table: posd = models.ManyToManyField(Posd, through='Posd', through_fields=('hg','pos')) # This is wrong, doesn't work Thanks in advance for any help. TABLE Posd class Posd(models.Model): #This class is just repsresenting the cost position in KBSUMME hg = models.IntegerField() pos = models.IntegerField() description = models.CharField(max_length=200) hours = models.CharField(max_length=5) cost = models.CharField(max_length=5) class Meta: unique_together = (('hg', 'pos'),) TABLE KbMeta class KbMeta(models.Model): #This class is representing the meta data for one project. One row per project only. pid = models.IntegerField(primary_key=True) klaversion = models.CharField(max_length=50, blank=True) calcbase = models.CharField(max_length=10, blank=True) contractbase = models.CharField(max_length=10, blank=True) quotno = models.CharField(max_length=50) filename = models.CharField(max_length=100) datecalc = models.DateField(default='1999-09-09') dateupload = models.DateTimeField(default='1999-09-09') projname = models.CharField(max_length=100, blank=True) customer = models.CharField(max_length=100, blank=True) endcustomer = models.CharField(max_length=100, blank=True) phase = models.CharField(max_length=50, blank=True) TABLE … -
Server error (500) Django deployment on heroku
I turned debug to False in my settings.py file (note that before I turned it to false, everything was workign perfectly) and when I ran git push heroku master and went to my website, the home page was working but that wasn't the case for all of my pages: on some, I got an error saying Server Error (500) Here is my settings.py code : DEBUG = False ALLOWED_HOSTS = ["hacka-labs.herokuapp.com"] Please help me if you know the answer -
NotImplementedError: Wrong number or type of arguments for overloaded function 'CoordinateTransformation_TransformPoint'
while I upload an created image to create a .KML File through django I got an error and I am not able to solve the ERROR on my web page : Wrong number or type of arguments for overloaded function 'CoordinateTransformation_TransformPoint'. Possible C/C++ prototypes are: OSRCoordinateTransformationShadow::TransformPoint(double [3]) OSRCoordinateTransformationShadow::TransformPoint(double [3],double,double,double) and this error on the terminal : Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vikuman/Downloads/portal/iiserupdated/DjangoWebProject1/app/views.py", line 136, in home image_data, name_id, thresh, scale, len_dang_arcs, interval_distance, filter_value, value) File "/home/vikuman/Downloads/portal/iiserupdated/DjangoWebProject1/functions/PythonApplication1.py", line 350, in main tiff_to_kml(name_id + "stream_points_tiff_coordinates.csv",name_id + "stream_points.kml",name_of_file,name_id,save_path) File "/home/vikuman/Downloads/portal/iiserupdated/DjangoWebProject1/functions/PythonApplication1.py", line 159, in tiff_to_kml latlong = transform.TransformPoint(float(j.replace("]","").replace("[","").split(",")[0]),float(j.replace("]","").replace("[","").split(",")[1])) File "/usr/lib/python3/dist-packages/osgeo/osr.py", line 927, in TransformPoint return _osr.CoordinateTransformation_TransformPoint(self, *args) NotImplementedError: Wrong number or type of arguments for overloaded function 'CoordinateTransformation_TransformPoint'. Possible C/C++ prototypes are: OSRCoordinateTransformationShadow::TransformPoint(double [3]) OSRCoordinateTransformationShadow::TransformPoint(double [3],double,double,double) First I thought this problem as Gdal problem(as mentioned in https://lists.osgeo.org/pipermail/gdal-dev/2015-February/041051.html) but upgrading Gdal didn't helped me. Please help me in sorting this problem. -
How to test url when primary key variable is in the middle
I use TestCase to test my django project. And when I want to test the URL for a book's detail I will visit the URL /books/<int:pk>/ I will test the url in my test file by self.client.get('/books/', kwargs={'pk':self.book.pk}) The PROBLEM is: If the url of book details lies at /mathbranch/<int:pk>/books/ How can I write a test for this url? Thank you! -
Save model field value as default for another field
Here's a relevant code from my models.py file class PhotoManager(models.Model): id = models.AutoField(primary_key=True) def model_instance_id(self): return self.id index = models.PositiveIntegerField(default = model_instance_id, blank=True, unique = False) What I'm trying to do is to save model id field value into index field (to safely edit it later with AJAX calls to Django Rest Framework). As I understand, the only correct option to save model field value to another field is setting default value as a function. When I save model instance I get an error: TypeError: model_instance_id() missing 1 required positional argument: 'self' Anyway, I can't figure out, how to reference ID field in mentioned function. I tried todo it with save method, but it just does nothing def save(self, *args, **kwargs): if not self.index: self.index = self.id super().save(*args, **kwargs) -
Django Ajax communication, Django doesn't recognize as being Ajax (using request.is_ajax() )
I'm using Ajax with Django. The data is transmitted further but is not recognize as being Ajax. Browser Chrome/Firefox; To check if the request is done trough ajax, I use: `request.is_ajax()` method, but this fails, not true, so I checked this method how is working and: def is_ajax(self): return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' I verified META.get('HTTP_X_REQUESTED_WITH') and I get None; I'm think is something with ContentType or I need to set another header. But How ?. My JavaScript is set this way : xhr.open('post', event.target.action, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(data)); -
Django creating multiple objects in same model
So i have a model called curricula info class CurriculaInfo(models.Model): curricula_info_id = models.AutoField(primary_key=True) curricula = models.ForeignKey(Curricula, on_delete=models.CASCADE) classes = models.ForeignKey(Classes, on_delete=models.CASCADE) designation = models.ForeignKey(Designations, on_delete=models.SET_NULL, null=True, blank=True, related_name="designation") class Meta: db_table = "arc_curricula_info" verbose_name_plural = "Curricula Information" unique_together = ('curricula', 'classes', 'designation') ordering = ['curricula_info_id'] def __str__(self): return 'Course: %s, Module: %s, Class: %s, Instructor: %s (AY: %s, Sem: %s)' % ( self.curricula.course_period.course.course_abbreviation, self.curricula.module_period.module.module_abbreviation, self.classes.class_name, self.designation.staff.staff_full_name, self.curricula.course_period.period.academic_year, self.curricula.course_period.period.semester)`enter code here` heres my forms.py class AssignClassForm(forms.ModelForm): designation = forms.ModelChoiceField(queryset=Designations.objects.filter(role__role_name='Instructor'), required=False) curricula = forms.ModelChoiceField(queryset=Curricula.objects.all(), widget=forms.HiddenInput) class Meta(object): model = CurriculaInfo fields = ['curricula', 'classes', 'designation'] heres my views.py class CurriculumClasses(CreateView): model = CurriculaInfo form_class = AssignClassForm template_name = 'architect/assignclasses.html' success_url = '/create-success/' def get_initial(self): course = self.kwargs.get('course_abbr') year = self.kwargs.get('year') semester = self.kwargs.get('semester') module = self.kwargs.get('module_abbr') curricula = get_object_or_404(Curricula, course_period__course__course_abbreviation=course, module_period__module__module_abbreviation=module, course_period__period__academic_year=year, course_period__period__semester=semester) return { 'curricula': curricula } def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['classes'] = Classes.objects.all() return context The get_initial method takes in values from the url to return the value curricula to the forms.py field, while the get_context_data sends classes values to the template <form method="post" action="{% url 'curriculum_classes' course_abbr module_abbr year semester %}"> {% csrf_token %} {{ form.non_field_errors }} {{ form.curricula }} <div class="fieldWrapper"> {% for class in classes …