Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent XSS attacks with HTML/Javascript?
I want to know that how can I prevent script code and HTML attributes to stop from execution in editor of my website? If someone add script tags with external link of code or call a function of jQuery in some attribute of HTML tag.I am using markdown editor and django framework. For example: '>"> '>">https://samengmg.xss.ht> {{7*7}}{7*7} -
How to add search bar in django admin home
I have different apps in django as: First APP: First APP model1 First APP model2 SECOND APP: SECOND APP model1 SECOND APP model2 Actually there are a lot of apps and a lot of models, I was wondering if I could somehow use search_fields in the http://localhost:8000/admin/ URL i.e. at the home of the Django admin site. As each app its own admin file, where I register them. So in this case where do I place related_field? -
Django - creating permission for allow selected user view content
For about 2 days i have problem with giving permission to selected user. I've tried doing it with standard Django, guardian and rolepermissions. Problem is when i add it - user still dont have permission to see the content. I've chacked that permission exist. I don't have any errors in code - still cant give permission. Here is the code which not working: class GiveBetaPermission(LoginRequiredMixin, AccountTypeRequiredMixin, RedirectView): model=BetaSoftware account_type_required = ['admin', ] url = reverse_lazy('accounts:client-list') success_message = _("Permission granted.") def get(self,request, *args, **kwargs): user = get_object_or_404(Client, pk=kwargs.get('pk')) get = super(GiveBetaPermission, self).get(request, *args, **kwargs) user.has_perm('softwares.view_beta') content_type = ContentType.objects.get_for_model(BetaSoftware) permission = Permission.objects.get( codename='view_beta', content_type=content_type, ) user.user_permissions.add(permission) user.has_perm('softwares.view_beta') user = get_object_or_404(Client, pk=kwargs.get('pk')) user.has_perm('softwares.view_beta') return get Thanks for any help! -
ElasticSearch_ModelFieldNotMappedError
Currently I'm getting this kind of error in Django ElasticSearch ! django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError: Cannot convert model field price to an Elasticsearch field! Elasticsearch version : 6.1.0 Can anyone help me with this ? here's the documents.py from django_elasticsearch_dsl import DocType, Index from crudapp.models import Product product=Index('products') @product.doc_type class ProductDocument(DocType): class Meta: model = Product fields = ['description', 'price', 'quantity'] -
ValueError when attempting to create Model object based on username for logged in User
AIM I am attempting to create an Alarm object with the user field set as the username for the logged in User. The issue identical to another question I asked recently. However, I restructured models.py and user=self.request.user.username is now returning the error stated below. Despite the fact that I am now using Django's default User model, is the reason why self.request.user.username isn't working is because I haven't set up AUTH_USER_MODEL? ERROR ValueError: Cannot assign "'sam_jones'": "Alarm.user" must be a "User" instance. CODE Models.py class Alarm(models.Model): """ Model representing each Alarm """ alarm_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) timezone = models.CharField(max_length=30) city = models.CharField(max_length=30) country = models.CharField(max_length=30) time = models.DateTimeField() temp_conditional = models.BooleanField() surf_conditional = models.BooleanField() temp_max = models.FloatField(blank=True, null=True) temp_min = models.FloatField(blank=True, null=True) surf_max = models.FloatField(blank=True, null=True) surf_min = models.FloatField(blank=True, null=True) def __str__(self): return str(self.alarm_id) Views.py class AlarmCreateView(LoginRequiredMixin, CreateView): """ CreateView for User to create the Alarm object """ model = Alarm ... def form_valid(self, form): self.get_user_location(request, form) return super().form_valid(form) def get_user_location(self, request, form): """ Function to get Profile's location from IP and create Alarm object """ ... alarm_object = Alarm.objects.create( alarm_id=uuid.uuid4(), user=self.request.user.username, ... ) alarm_object.save() -
Removing the "Authorize" step
I would like to assume that every person who is using the website I'm developing will click in "Authorize" to get the tokens and interact. I can easily do this by modifying the template (clicking on the button automatically using Javascript) but since I'm using Heroku I cannot edit those files because they will go back to normal as it's an external library. The only thing I could do (as far as I know) is to edit the settings.py, and I tried to set DEFAULT_SCOPES to [] but I still get to the page "Authorize". Is there any way I could avoid this step without directly modifying the library or even any way I could get that to work in Heroku? -
Unexpected outcome from model inheritance in Django
I've built a custom user model called "Administrator" for superuser purpose, and the other model called "Customer" for normal user purpose. I intended to separate them into two different tables, it partly worked but not perfectly. The problem is that when I created an instance for Customer, the instance will be automatically added into the Administrators table, this isn't what I want. Administrator model on Django admin site Customer model on Django admin site Administrator model shown below: class Administrator(PermissionsMixin, AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) join_date = models.DateField(auto_now_add=True, editable=False) objects = AdministratorManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.get_full_name() @property def is_staff(self): return self.is_admin def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True Customer model shown below: class Customer(Administrator): first_name = models.CharField(max_length=255, default='', blank=False) last_name = models.CharField(max_length=255, default='', blank=False) DOB = models.DateField() security_question1 = models.CharField(max_length=500, default='', blank=False) security_question2 = models.CharField(max_length=500, default='', blank=False) security_question_answer1 = models.CharField(max_length=500, default='', blank=False) security_question_answer2 = models.CharField(max_length=500, default='', blank=False) # REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'DOB', 'security_question1', 'security_question2'] is_active = True is_admin = False -
How do I query count of 2 fields occurences in Django?
I've got a PlayTrack model like this, each time a user plays a track, it means 1 record in PlayTrack class PlayTrack(models.Model): track = models.ForeignKey(Track, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) token = models.CharField(max_length=255, default='default_token') So, how do I query the play count of each user ? I've tried PlayTrack.objects.annotate(Count('user'), Count('track')).values('user', 'track__count'), but it gives me something like <QuerySet [{'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, {'user': 2, 'track__count': 1}, '...(remaining elements truncated)...']> What I need is something like {'user': 2, 'track__count': 3},{'user': 3, 'track__count': 5},{'user': 4, 'track__count': 10}, -
Heroku & Django: Storing a single jpg asset
With Heroku's ephemeral filesystem, it's obvious we can't host user-uploaded images or dynamically changing ones in the app's filesystem because these won't be available to other dynos. However, I'm looking for a solution to store a SINGLE image, used as sort of a logo, in a Django URLField() - this image's URL will be sort of a fallback if an image at a remote location (external service) is not available( Hence the URLField and not ImageField) picture_url = models.URLField(null=True) For me, setting-up and using services like Amazon S3 seems like an overkill. Using services like imgur/Photobucket seems unreliable. Any workarounds? -
Nested serializer "Through model" in Django Rest Framework
I am having difficulty serializing an intermediary "pivot" model and attach to each item in an Many-to-many relation in Django Rest Framework. Example: models.py: class Member(models.Model): name = models.CharField(max_length = 20) groups = models.ManyToManyField('Group', through='Membership') class Group(models.Model): name = models.CharField(max_length = 20) class Membership(models.Model): member = models.ForeignKey('Member') group = models.ForeignKey('Group') join_date = models.DateTimeField() serializers.py: class MemberSerializer(ModelSerializer): class Meta: model = Member class GroupSerializer(ModelSerializer): class Meta: model = Group class MembershipSerializer(ModelSerializer): class Meta: model = Membership I tried to follow the answers: Include intermediary (through model) in responses in Django Rest Framework But it's not exactly what I need I need to generate the following output { "id": 1, "name": "Paul McCartney", "groups": [ { "id": 3, "name": "Beatles", "membership": { "id": 2, "member_id": 1, "group_id": 3, "join_date": "2018-08-08T13:43:45-0300" } } ] } In this output I'm returning the related "Through Model" for each item in groups. How can I generate serialize models in this way? -
How to display a histogram from a queryset in django
AIM In general, the application displays location data for specific Twitter hashtags. For instance, if the User enters "python". The application searches Twitter for recent tweets containing the hashtag "python" and, where possible, displays location data for those tweets. Currently, the location data is displayed as a dict, which is achieved through the def display_locations(self) function in Models.py. Now, I am attempting to display that data on a histogram. I have written the draw_histogram() function in Views.py below but I get the error stated below. I suspect that an effective solution may be to call the method: Hashtag.display_locations in the function: draw_histogram(), but I am not sure. I have two, alternate, questions: In draw_histogram() in Views.py, how to set country_list to achieve the aim? Perhaps it is more appropriate to include the draw_histogram() function as a method in the class SearchResultsView(generic.ListView)? If so, how do I do so? ERROR Exception Type: TypeError Exception Value: draw_histogram() missing 1 required positional argument: 'self' CODE Models.py class Hashtag(models.Model): """ Model representing a specific Hashtag serch by user """ search_text = models.CharField(max_length=140, primary_key=True) locations = models.ManyToManyField(Location, blank=True) def __str__(self): """ String for representing the Model object (search_text) """ return self.search_text def display_locations(self): """ Creates … -
Django: Give date field default value of one month from today
In Djanog, you can have a date field and set the default value to today. start_date = models.DateField(default=timezone.now, blank=True, null=True) How do you set the default date to 1 month from today? -
Elastic Beanstalk Django deployment, psycopg2 not loading
I am trying to deploy a Django website to Elastic Beanstalk. I am using Python 3.5 on my system, but Elastic Beanstalk only lets you pick 3.4 or 3.6 so I picked 3.4, not sure if that's part of the issue. Also I SSH'ed in to my EC2 and did "pip install psycopg2" but that did not work either. Here is a snippet of my error messages. It always states that psycopg2 is not loading and that WSGI cannot be loaded as target module. ------------------------------------- /var/log/httpd/error_log ------------------------------------- raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' mod_wsgi (pid=3251): Target WSGI script '/opt/python/current/app/omnibus/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=3251): Exception occurred processing WSGI script '/opt/python/current/app/omnibus/wsgi.py'. Traceback (most recent call last): File "/opt/python/current/app/omnibus/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) Here is my python.config: -------------- python.config -------------- option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "omnibus.settings" PYTHONPATH: "./omnibus" "aws:elasticbeanstalk:container:python": WSGIPath: "omnibus/wsgi.py" StaticFiles: "/static/=www/static/" packages: yum: postgresql95-devel: [] container_commands: 01_migrate: command: "python manage.py migrate" leader_only: true 02_collectstatic: command: "python manage.py collectstatic --noinput" Here is a snippet from my settings.py: # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
Command object has no attribute meta, Django management commands
I am trying to run a one time management command to pre-populate a db. Here is the model: class ZipCode(models.Model): zip_code = models.CharField(max_length=7) latitude = models.DecimalField(decimal_places=6, max_digits =12) longitude = models.DecimalField(decimal_places=6, max_digits =12) and here is the management command: from django.core.management.base import BaseCommand from core.models import ZipCode class Command(BaseCommand): def populate_db(self): zip_code_object = ZipCode(zip_code='10566', latitude = 10.2, longitude= 43.4) #test data to see if I could get it working ZipCode.save(self) def handle(self, *args, **options): self.populate_db() But when I run python3.6 manage.py populate_zip_code_db it returns File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save for field in self._meta.concrete_fields: AttributeError: 'Command' object has no attribute '_meta' Does anyone know how to get this working? I just discovered management commands so I am clueless. -
Password reset not redirecting to the template in Django
I'm trying to override the default email to reset a password in Django rest-auth with an html template. I'm trying to use: from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^password/reset/', auth_views.password_reset, { 'html_email_template_name':'registration/password_reset_email_html.html', }, name="password_reset"), url('^', include('django.contrib.auth.urls')), ] The email is successfully sent, but with the default template. I can override this by adding a custom template file registration/password_reset_email.html, but then the email is only sent as plain text. What am I doing wrong here? -
ImportError: No module named applicationform.wsgi Deployment AWS Django Python 2.7
I'm deploying an app in AWS, when I ran Gunicorn in Virtual Env to test if ran correctly. I'm getting the below error: (venv) ubuntu@ip-172-31-14-232:~/applicationform/newProject$ gunicorn --bind 0.0.0.0:8000 applicationform.wsgi:application [2018-08-09 00:52:20 +0000] [22973] [INFO] Starting gunicorn 19.9.0 [2018-08-09 00:52:20 +0000] [22973] [INFO] Listening at: http://0.0.0.0:8000 (22973) [2018-08-09 00:52:20 +0000] [22973] [INFO] Using worker: sync [2018-08-09 00:52:20 +0000] [22977] [INFO] Booting worker with pid: 22977 [2018-08-09 00:52:20 +0000] [22977] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) ImportError: No module named applicationform.wsgi [2018-08-09 00:52:20 +0000] [22977] [INFO] Worker exiting (pid: 22977) [2018-08-09 00:52:20 +0000] [22973] [INFO] Shutting down: Master [2018-08-09 00:52:20 +0000] [22973] [INFO] Reason: Worker failed to boot. Testing the app on AWS I also get the internal server error. The code is on Github https://github.com/sannicko/applicationform Thank you in advance for your help. Cheers. -
Django rest query
Excuse me, how can I navigate in a list in django with% s, since with a single value it works fine for me, but I want to pass two parameters to my query. class PruebaSQL(ListAPIView): serializer_class = CountSerealizer def get_queryset(self): num = self.kwargs['num'] date = self.kwargs['date'] result = (num, date) queryset = Sale.objects.raw("SELECT 1 id, id_customer_id, count(DISTINCT id_customer_id) FROM sales_sale where datesale > %s group by id_customer_id having count(id_customer_id) > %s", [result]) return queryset How can I put the positions? or there is another way to pass the data -
HTML Form Submission with JQuery in a Django Application
I use the following pieces of HTML and JQuery code to navigate pages in a website (I am also using Django; hence, the double curly braces). My code works fine only in Safari, but not in Firefox, Chrome, and Opera, even though it seems logically and syntactically correct. Any ideas why it doesn't work? Thank you for your help in advance. Some more information: I am using the Django development server for now. My OS is macOS High Sierra (10.13.6). <form id="myform" action="..." method="get"> <a class="pg-nav" data-nav-value="-1" href="">Previous</a> <span id="pg-cur">{{ pageNumber }} / {{ totalNumPages }}</span> <a class="pg-nav" data-nav-value="1" href="">Next</a> <input id="pg" type="hidden" name="pg" value="0"> </form> $('.pg-nav').click(function() { var curPage = parseInt($('#pg-cur').text()); var navVal = parseInt($(this).data('nav-value')); var newVal = curPage + navVal; $('#pg').val(newVal); $('#myform').submit(); }); -
Djano 2.0: Foreign Key Constraint
I keep getting a Foreign Key Constraint when I am trying to create a new instance of a model. I can do this in the admin just fine, but it isn't working on the code side of things. I did at one point take the this Thing model and remove to other foreign keys and put these two foreign keys in, but I don't know if that has anything to do with this error. Do you know what's creating this Foreign Key Error? class ThingManager(models.Manager): def new(self,thing_a=None,thing_b=None): return self.model.objects.create(thing_a=thing_a, thing_b=thing_b) class Thing(models.Model): thing_a= models.ForeignKey(BillingProfile, blank=False, related_name='thinga+', default=False, on_delete=models.CASCADE) thing_b= models.ForeignKey(BillingProfile, blank=False, related_name='thingb+',default=False, on_delete=models.CASCADE) thing_c = models.ForeignKey(BillingProfile, blank=True, related_name='thingc+',default=False, on_delete=models.CASCADE,null=True) thing_id = models.CharField(max_length=120, blank=True) def __str__(self): return self.thing_id objects = ThingManager() BillingPorfile is just an extension of the User Profile class BillingProfile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) email = models.EmailField() code creating the error: bp1 = BillingProfile.objects.filter(user__email='a@gmail.com') bp2 = BillingProfile.objects.filter(user__email='b@yahoo.com') qs = Thing.objects.new(thing_a=bp1.first(),thing_b=bp2.first()) error message: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:myapp\src\thing\models.py", line 38, in new return self.model.objects.create(thing_a=thing_a, thing_b=thing_b) File "C:myapp\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:myapp\lib\site-packages\django\db\models\query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "C:myapp\lib\site-packages\django\db\models\base.py", line 729, in save force_update=force_update, … -
Mongoengine RF's DynamicDocumentSerializer creates a document inside another one
I'm struggling to solve the following problem. I define a simple model and its corresponding serializer as follows: models.py class Device(mongoengine.DynamicDocument): data = mongoengine.fields.DictField() meta = { 'queryset_class': DeviceQuerySet, 'ordering': ['-data.date'] } serializers.py from rest_framework_mongoengine import serializers as mongoserializers class DeviceSerializer(mongoserializers.DynamicDocumentSerializer): with open(SCHEMA_PATH, 'r') as fschema: schema_data = fschema.read() schema = json.loads(schema_data) def validate(self, data): jsonschema.validate(data, self.schema) return data def create(self, validated_data): return TestResult.objects.create(**validated_data) class Meta: model = Device fields = '__all__' I want my document to be expandable , that's, so that I could add some new fields to it when necessary, the same regards the data field on the model, but on the other hand I need to check if certain fundamental fields in the data dict are present. That's the reason for the validation part. My controller (aka view) looks like so: views.py class DeviceView(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = DeviceSerializer def create(self, request): serializer = self.serializer_class(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save(data=request.data) except djongo.sql2mongo.SQLDecodeError: return Response( {"Error": "Database is unreachable"}, status=status.HTTP_503_SERVICE_UNAVAILABLE ) except jsonschema.ValidationError as err: return Response( {"Error": str(err)}, status=status.HTTP_403_FORBIDDEN ) return Response( status=status.HTTP_200_OK ) The problem with it is that the json (document) written in the DB (MongoDB) looks as follows: { "_id": ObjectId("5b6afd49540d1c2233b9e775") "field1": "value1", "field2": … -
Testing Django API on a VPS with curl
I'm trying to access on my Django API using curl from my local terminal to a VSP curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ So, I tried many things like, replace admin:password to my actual vps root@password replace admin:password to my actual database admin@password replace http://127.0.0.1:8000 to my vps url replace the port 8000 by 22, or 80, 8080 And by the way, I don't know is I have to change /users/ by /root/ or anything else. I have tried many mix and nothing works. Here what I'm testing : http://www.django-rest-framework.org/tutorial/quickstart/#testing-our-api If important, my vps machine is Debian 9 (Stretch) Think you for your help -
Deploying a frozen Python application over IIS
I am attempting to freeze and then deploy a Python Django application over IIS, but cannot configure it to run without a local version of Python. Right now I can... run my non-frozen Django project over IIS just fine by writing a web.config file that points to the local installation of Python and wFastCgi.py (as this tutorial and this tutorial say to do). freeze my Django project just fine by using PyInstaller (as I have questioned here and answered here before) and run it using the built-in development server. However, I cannot bridge the gap between these two steps. When the application is frozen, the web.config file cannot point to Python.exe or wFastCgi.py because they just don't exist, they have been replaced by my singular appName.exe file. Mostly just to see what would happen, I tried to kind of go behind the issue's back and point my web.config file to my local installation of Python and wFastCgi.py, even though they shouldn't be required when the app is frozen. When I did that, I got the error message shown below. The WSGI Handler that is required to run a Django app over IIS apparently fails when the app is packaged. Overall, … -
Django celery daemon gives 'supervisor FATAL can't find command', but path is correct
Overview: I'm trying to run celery as a daemon for tasks to send emails. It worked fine in development, but not in production. I have my website up now, and every function works fine (no django errors), but the tasks aren't going through because the daemon isn't set up properly, and I get this error in ubuntu 16.04: project_celery FATAL can't find command '/home/djangodeply/myvenv/bin/celery' Installed programs / hardware, and what I've done so far: I'm using Django 2.0.5, python 3.5, ubuntu 16.04, rabbitmq, and celery all on a VPS. Im using a venv for it all. I've installed supervisor too, and it's running when I check with sudo service --status-all because it has a + next to it. Erlang is also installed, and when I check with top, rabbitmq is running. Using sudo service rabbitmq-server status shows rabbitmq is active too. Originally, I followed the directions at the celery website, but they were very confusing and I couldn't get it to work after ~40 hours of testing/reading/watching other people's solutions. Feeling very aggravated and defeated, I chose the directions here to get the daemon set up and hope I get somewhere, and I have got further, but I get the … -
Django/Nginx - Server sending one specific page slowly
Can't seem to figure this one out. Running Django 1.10 with Nginx and I have one page that is loading much more slowly than all my others. Looking at the network tab on Chrome, the HTML file that is being returned is only 61 KB but is taking over 3 seconds to be sent from the server! All the rest of my pages are similar or slightly smaller in size and are returned in less than a second. Is there some way I can track down why this specific page is taking so long to be returned? -
Django 2.0 url parameters in get_queryset
I would like to filter subcategories based on the category id from the url For a constant value it works without a problem return Subcategory.objects.filter(category = 1) views.py class SubcategoriesListView(ListView): model = Subcategory template_name = 'app/categories/index.html' def get_queryset(self): return Subcategory.objects.filter(category = category_id) urls.py path('categories/<int:category_id>/', app.views.SubcategoriesListView.as_view(), name='subcategories'), models.py class Subcategory(models.Model): title = models.CharField(max_length=30) category = models.ForeignKey(Category, on_delete=models.CASCADE) Traceback NameError at /categories/1/ name 'category_id' is not defined views.py in get_queryset return Subcategory.objects.filter(category = category_id)