Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mocking django exceptions using python mock library
I am working with python 2.7 using mock==2.0.0 library along with django in a unit test. Here's a sample code snippet @patch('models.SampleModel') def test_smaple_mocking(self, mock_model): fake_request = Mock() fake_request.method = 'PUT' fake_request.id = 100011 from some_module import ReqClass from some_django_proj import models exception = models.SampleModel.MultipleObjectsReturned("Multiple records found") mock_model.objects.select_for_update.side_effect = exception resp = ReqClass.get_django_status(fake_request) self.assertEqual(resp.status_code, 200) The get_django_status() method is something like this def get_django_status(req): return [models.SampleModel.objects.select_for_update().filter( request_id=req.id)] While executing, method get_django_status() returns a list of the models.SampleModel.MultipleObjectsReturned() object instead of raising en exception. Any way I can get the models.SampleModel.objects.select_for_update().filter() to raise the exception instead of returning the exception object ? Thanks in advance. -
Extended modelform not saving related table
I've extended a modelform but the related model isn't correctly saving to the database. Below I'm only calling SupplyAddress() rather than creating and saving an instance of it via SupplyAddress.objects.create() However, if I try to do this then the related address (and user) hasn't been created yet to save against. What's the best way to save the user, Address and SupplyAddress? models.py class Address(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) house_name_number = models.CharField(max_length=255, verbose_name="house name or number") street_name = models.CharField(max_length=255) town_city = models.CharField(max_length=255) county = models.CharField(max_length=255) postcode = models.CharField(max_length=8) time_stamp = models.DateField(auto_now=True) class SupplyAddress(models.Model): address = models.OneToOneField(Address) region = models.ForeignKey(Region, null=True) occupied = models.BooleanField() forms.py class SupplyAddressForm(forms.ModelForm): occupied = forms.BooleanField() def save(self, *args, **kwargs): super().save(*args, **kwargs) data = self.cleaned_data supply_address = models.SupplyAddress( occupied=data['occupied'], ) self.instance.supplyaddress = supply_address return self.instance class Meta: model = Address fields = ['house_name_number', 'street_name', 'town_city', 'county', 'same_address', 'move_in_date', 'postcode', ] views.py ..... address = form.save(commit=False) address.user = user address.save() -
Trying to make a django rest api that doesn't look like my models
I'm trying to make an API for an outside group where I define user access. I have a setup in django that makes it easy to administer, but I would like the output to be quite simplistic for the other team. This is the output I'm looking for would be something like: { "user_list": { "user": { "username": "username1", "top_accesses": ["top_access_1", "top_access_2", "top_access_5"], "middle_accesses": ["middle_access_1", "middle_access_2", "middle_access_7"], "lower_accesses": ["lower_access_1", "lower_access_2", "lower_access_22"], }, "user": { "username": "username2", "top_accesses": ["top_access_1", "top_access_2", "top_access_8"], "middle_accesses": ["middle_access_3", "middle_access_5", "middle_access_6"], "lower_accesses": ["lower_access_21", "lower_access_33", "lower_access_36"], } } } However, I'm having trouble using django's built in ORM to come up with these sets from my models. I can think of how to do it in SQL, but this isn't a particularly clean method. I know there must be a better way to do it since using TabularInline shows exactly what I want to see in the admin page Here are my models: class TopAccess(models.Model): name = models.CharField(max_length=100) site_user_access = models.ManyToManyField(User, blank=True) site_group_access = models.ManyToManyField(Group, blank=True) class Meta: verbose_name_plural = "Top Access" def __str__(self): return self.name class MiddleAccess(models.Model): name = models.CharField(max_length=100) site_user_access = models.ManyToManyField(User, blank=True) site_group_access = models.ManyToManyField(Group, blank=True) class Meta: verbose_name_plural = "Middle Access" def __str__(self): return … -
Django sessions set default key usage
So I have a question about session keys, normally when a user visits the site for the first time a session key does not exist yet hence you have to set a default. set_date = request.session.get('set_date', '2017-07-06') I use sessions to store an user given date and use this date in different views. The code below does almost exactly what I want it to do, at least without a default set. When I set a default value for 'set_date', I can't seem to use the date in different views, once I switch views the default is set again. What's the right way to set a default to 'set_date'? views.py """ Check-ins listview """ from .forms import DateSelection class CheckInsListView(generic.ListView, FormMixin): form_class = DateSelection model = Delivery paginate_by = 10 queryset = Delivery.objects.filter(status='AR') template_name = 'check-ins.html' """ Save the user given date in a session key set_date """ def get_context_data(self, *args, **kwargs): context = super(CheckInsListView, self).get_context_data(*args, **kwargs) user_date = self.request.GET.get("date_selection") if user_date: # If user enters date self.request.session['set_date'] = user_date # Save given date in session context ['set_date'] = self.request.session['set_date'] # Sent date to context else: context ['set_date'] = self.request.session['set_date'] # Use date from session return context """ Use the date … -
Django infinite scroll goes through all pages at once without actually loading them
I'm implementing infinite scroll for my Django app using this excellent tutorial. I want the app to load 9 articles then show the "loading..." sign and load 9 more articles. However, what happens is that when the user hits the bottom, it shows the loading sign and nothing happens. On the terminal I can see that it "GET" requested all the pages at once like this: [06/Jul/2017 18:22:26] "GET /?page=2 HTTP/1.1" 200 19124 [06/Jul/2017 18:22:27] "GET /?page=3 HTTP/1.1" 200 18774 [06/Jul/2017 18:22:27] "GET /?page=4 HTTP/1.1" 200 18772 [06/Jul/2017 18:22:28] "GET /?page=5 HTTP/1.1" 200 19031 [06/Jul/2017 18:22:28] "GET /?page=6 HTTP/1.1" 200 18965 [06/Jul/2017 18:22:28] "GET /?page=7 HTTP/1.1" 200 18676 [06/Jul/2017 18:22:28] "GET /?page=8 HTTP/1.1" 200 18866 [06/Jul/2017 18:22:28] "GET /?page=9 HTTP/1.1" 200 19094 [06/Jul/2017 18:22:28] "GET /?page=10 HTTP/1.1" 200 18750 This is the code in views: def context_generator(request, title, category): """made this function because views are very similar""" context_dict={} if(category == "index"): articles_list = Article.objects.order_by('-pub_date') else: articles_list = Article.objects.filter(category=category).order_by('-pub_date') page = request.GET.get('page', 1) paginator = Paginator(articles_list, 9) try: articles = paginator.page(page) except PageNotAnInteger: articles = paginator.page(1) except EmptyPage: articles = paginator.page(paginator.articles_list) context_dict['articles'] = articles context_dict['title'] = title return context_dict def index(request): return render(request, 'app_name/index.html', context_generator(request, "page title", "index")) This is index.html: … -
Django error while creating superuser, AttributeError: 'Manager' object has no attribute 'get_by_natural_key'
I am using Django version 1.11.3 and djangorestframework version 3.6.3. At the stage of creating the superuser with the following command: python manage.py createsuperuser This command was supposed to ask me about my Email and Password, though it does ask me the Email but after entering my Email, I got an error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 121, in handle self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) AttributeError: 'Manager' object has no attribute 'get_by_natural_key' My models.py is this: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(object): """helps django work with our custom user model""" def create_user(self,email,name,password=None): if not email: raise ValueError('User must have email') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,password): """creates and saves a new superuser with given details""" user = self.create_user(email,name,password) user.is_superuser = True user.is_staff = True user.save(using=self._db) class UserProfile(AbstractBaseUser, PermissionsMixin): """docstring for UserProfile""" email = … -
Can you use python-socketio for django?
I've looked around for socketio solutions for Django, and I haven't found anything that says I can use python-socketio for it, but I also haven't found anything that says I can't. It's python, so I would assume it works, but is it bad practice? Will something go wrong? Thank you -
Django mode sorting by children of children
I have simple forum modes like: Forum group -(has many)-> Group Post -(has many)-> Post comments. Now I want to sort forum groups but tricky way: either by post date or by comments date. I.e. top post in template should have most recent comments (or, if there is not comments but post create recently then everything else). I have basic query Group.all() and it is works well. I addings order_by('-grouppost__created_at', '-grouppost__grouppostcomment__created_at') and got a list that contains N copies of single groups. It is caused by weird (for me) data joining - in SQL it converted to double LEFT JOIN with posts and comments: SELECT `forum_group`.`id`, `forum_group`.`site_id`, `forum_group`.`orig_group_id`, `forum_group`.`name`, `forum_group`.`description` FROM `forum_group` LEFT OUTER JOIN `forum_grouppost` ON (`forum_group`.`id` = `forum_grouppost`.`group_id`) LEFT OUTER JOIN `forum_grouppostcomment` ON (`forum_grouppost`.`id` = `forum_grouppostcomment`.`group_post_id`) WHERE `forum_group`.`site_id` = 2 ORDER BY `forum_grouppost`.`created_at` DESC, `forum_grouppostcomment`.`created_at` DESC I know that it is looks obvious - to get all posts for group it must be left joined and the same with comments. But now I am totally stuck how to sort groups desired way. -
Django queries with complex filter
I have the following model: ... from django.contrib.auth.models import User class TaxonomyNode(models.Model): node_id = models.CharField(max_length=20) name = models.CharField(max_length=100) ... class Annotation(models.Model): ... taxonomy_node = models.ForeignKey(TaxonomyNode, blank=True, null=True) class Vote(models.Model): created_by = models.ForeignKey(User, related_name='votes', null=True, on_delete=models.SET_NULL) vote = models.FloatField() annotation = models.ForeignKey(Annotation, related_name='votes') ... In the app, a User can produce Vote for an Annotation instance. A User can vote only once for an Annotation instance. I want to get a query set with the TaxonomyNode which a User can still annotate a least one of its Annotation. For now, I do it that way: def user_can_annotate(node_id, user): if Annotation.objects.filter(node_id=node_id).exclude(votes__created_by=user).count() == 0: return False else: return True def get_categories_to_validate(user): """ Returns a query set with the TaxonomyNode which have Annotation that can be validated by a user """ nodes = TaxonomyNode.objects.all() nodes_to_keep = [node.node_id for node in nodes if self.user_can_annotate(node.node_id, user)] return nodes.filter(node_id__in=nodes_to_keep) categories_to_validate = get_category_to_validate(<user instance>) I guess there is a way to do it in one query, that would speed up the process quite a lot. In brief, I want to exclude from the TaxonomyNode set, all the nodes that have all their annotations already voted once by the user. Any idea of how I could do it? With … -
Django Image Upload Form not valid
For some reason in django the form that I am trying to use is not considered valid. This code is taken almost directly from a site that claims that it works but is still not functional. my code is as follows. VIEWS def display_update_image(request, pk): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): display = Display.objects.get(pk = pk) display.image = form.cleaned_data['image'] display.save() return HttpResponseRedirect(reverse('displays')) else : form = ImageForm() return render(request, 'catalog/update_display_image.html', {'form': form}) TEMPLATE (template name is update_display_image.html) <form method = "post" enctype = "multipart/form-data">{% csrf_token %} <p> <input id = "id" type = "file" class = "" name = "image"> </p> <input type = "submit" value = "Submit" /> MODELS class Display(models.Model): title = models.CharField(max_length = 50,) image = models.ImageField(upload_to = 'images') id = models.UUIDField(primary_key = True, default = uuid.uuid4, unique = True) def __str__(self): return self.title -
empty select field for django filters ModelMultipleChoiceFilter with Materialize
I'm using django filters and I have a ModelMultipleChoiceFilter with choices from a queryset, let's say my_app.MyModel.objects.all(). When rendering the the form <form action="" method="get"> {{ filter.form.as_p }} <div class="right-align"> <input type="submit" class="btn waves-effect"/> </div> </form> I get in the select field on my page the first entry from the queryset, although it is not selected. Looking at the source code I see that I get an <input .. value="FirstEntry"> with value set to the first entry. How can I pass a "None" value to the queryset? Or even better, how can I tell Materialize not to take the first value as a default value (which is not even selected)? -
Assigning image in ImageField through code, django
I am working on a code where model has an ImageField named 'qr'. What i want to achieve is to generate a QR code once certain conditions are met and then assign it to the model's qr ImageField. Can someone suggest how to do this..? Here's the code: qr = pyqrcode.create("Hey") qr.png('test_qr.png', scale=6) #what now? -
Django: get_absolute_url not working
In Django, I want to display a detailed view of model objects by using the get_absolute_url method as described here. The URL structure for each detail is something like this... url.com/company/(?P< company_id >[0-9]+)/people/(?P< slug >[0-9]+)/$ Which returns the NoReverseMatch error like so NoReverseMatch at /company/google/people/ as I put the href='{{ people.get_absolute_url }}' in my template. Does anybody know if using the 'company_id' kwarg in the URL is causing problems rendering the page with the get_absolute_url href for the 'slug' kwarg? I've done this many times before with a hardcoded URL before the kwarg variable which worked; however this does not. Full Error: Reverse for 'people-detail' with arguments '()' and keyword arguments '{u'slug': u'798224891221678'}' not found. 1 pattern(s) tried: ['company/(?P< company_id >[0-9]+)/people/(?P< slug >[0-9]+)/$'] -
passing variable in javascript function using django template
here I am passing {{id}} to hide_show(...) javascript function {% for stock in part_temp.part_stock_set.all %} {% with id="list"|concatenate:stock.id %} <div id="{{ id }}"> {{ stock.entry_date}} </div> <button type="button" onclick="hide_show({{ id }})">edit</button> <br> {{ id }} here above the {% endwith %} {{ id }} is displaying correctly but the hide_show function in not called but it is called when just {{ stock.id }} is passed to it. the concatenate filter just concatenates and returns a string. <script type="text/javascript"> function hide_show(temp) { document.getElementById(temp).style.display='none'; window.alert(temp); } </script> -
Django translation: translating URLs
I'm using Django 1.11 with translations enabled. My URLs start with language code, e.g. "/en/tickets/" or "/cs/tickets/". I need to solve the following problem: I have a URL in some language (could be any of the ones I'm using - the ones in settings.LANGUAGES) and I need to convert it into one particular language. Now Django offers django.urls.translate_url() which should be doing exactly what I want, however it seems that it works only when the original URL is in the current language. Example (Django shell): >>> from django.urls import translate_url >>> from django.utils.translation import activate >>> activate('en') >>> translate_url('/en/tickets/', 'cs') '/cs/tickets/' >>> translate_url('/de/tickets/', 'cs') '/de/tickets/' >>> activate('de') >>> translate_url('/en/tickets/', 'cs') '/en/tickets/' >>> translate_url('/de/tickets/', 'cs') '/cs/tickets/' I need it to be working for all the languages. How do I do that? Thank you. -
How can I combine django-allauth templates with bootstrap modals properly?
I have a django application and I recently installed django-allauth package. 1st step is to make a proper configuration and see the package work (without modals), just simple templates. Done. 2nd step is to use Bootstrap Modals to avoid many page reloads. And here comes the problem: While the Sign Out process works fine, Log In and Sign Up return app/json data and the result is json data in form of html (hope I am expressing it correct) I will first explain the methodology to use bootstrap modal and then my research on the problem: What I do is use a button like this : <a data-toggle="modal" href="{% url 'account_signup' %}" data-target="#logout-modal">Sign Up</a> And then a modal that has its content replaced by the signout.html template, (offered by django-allauth). <div id="logout-modal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> ... </div> </div> </div> Studying the views in the repository of django-allauth I notice that SignupView and LoginView use a AjaxCapableProcessFormViewMixin while LogoutView doesn't. I also see that SignUpView and LoginView return json data. How should I handle this? Sorry for long post, and thanks in advance. -
python -m pip install -U pip Errno 11004
I am trying to update pip but I keep getting the following messages: H:\>python -m pip install -U pip Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.con nection.VerifiedHTTPSConnection object at 0x031AF3B0>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',)': /simple/pip/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.con nection.VerifiedHTTPSConnection object at 0x031AF3D0>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',)': /simple/pip/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.con nection.VerifiedHTTPSConnection object at 0x031AF110>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',)': /simple/pip/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.con nection.VerifiedHTTPSConnection object at 0x031AF0B0>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',)': /simple/pip/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.con nection.VerifiedHTTPSConnection object at 0x031AF170>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',)': /simple/pip/ Requirement already up-to-date: pip in c:\users\a256886\appdata\local\programs\python\python36-32\lib\site-packages I have python 3.6.1 installed and when I run pip --version I see pip 9.0.1. Why I can't update it? Or install any package with pip? What is happening? How can I fix it? -
Dockerization and deploying on Heroku project with Angular 4 frontend with Django backend and postgresql database
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. Besides, I am going to deploy it on Heroku. At this moment my situation looks as shown below. I am note sure if this is done properly? Unfortunately it doesn't work. When i try docker-compose up I get: MacBook-Pro:~ myUser$ docker-compose up Building angular Step 1/7 : FROM node:8.1.2-onbuild as builder # Executing 5 build triggers... Step 1/1 : ARG NODE_ENV ---> Using cache Step 1/1 : ENV NODE_ENV $NODE_ENV ---> Using cache Step 1/1 : COPY package.json /usr/src/app/ ---> Using cache Step 1/1 : RUN npm install && npm cache clean --force ---> Using cache Step 1/1 : COPY . /usr/src/app ---> Using cache ---> 4ba35205484c Step 2/7 : ARG TARGET=production ---> Using cache ---> 20f3f25f3d45 Step 3/7 : RUN npm install @angular/cli ---> Using cache ---> 005a5afcef88 Step 4/7 : RUN node_modules/.bin/ng build -aot --target ${TARGET} ---> Running in 09e5752964f6 Hash: 0c91b5245d9f2f1b899d Time: 12174ms chunk {0} polyfills.51d1b984c6d09b6245cd.bundle.js (polyfills) 232 kB {4} [initial] [rendered] chunk {1} main.466ececd219a11fbf397.bundle.js (main) 1.04 kB {3} [initial] [rendered] chunk {2} styles.4d1993091a9939c0785a.bundle.css (styles) 69 bytes {4} [initial] [rendered] chunk {3} vendor.927d5207264169ec1f8c.bundle.js (vendor) 836 kB [initial] [rendered] chunk {4} inline.e6088d403421d3b3ae62.bundle.js (inline) 0 … -
CanvasJS chart not updating with AJAX callback values
I have a Django app that calculates the CPU usage %, memory usage, and some other stats in a view. In another view, I have a huge function that takes some minutes to complete. I want to chart the changing CPU statistics as the function is executing, i.e., as the function is executing, I'm making periodic AJAX calls to the CPU statistics view, and updating CanvasJS datapoints with the new CPU statistics parameters to update the chart. Here's the JavaScript for the chart drawing - var dataPoints = []; var cpu = 0; var mem = 0; var mem_info = 0; var chart = new CanvasJS.Chart("chartContainer", { title: { text: "Machine Stats" }, data: [{ type: "column", dataPoints: dataPoints }] }); function callCharts() { $.ajax({ url: 'charting/', success: function(data, textStatus, jqXHR) { cpu = data.cpu; mem = data.mem; mem_info = data.mem_info; dps = [{x: 10, y: cpu, label: "CPU %"}, {x: 20, y: mem, label: "Memory %"}, {x: 30, y: mem_info, label: "Memory in MB"}, //{x: 40, y: } ]; dataPoints.push(dps); chart.render(); } }); } $('#chartbutton').on("click", function(event) { $.ajax({ url: 'aftercharting/', success: function(data, textStatus, jqXHR) { clearInterval(intervalID); } }); var intervalID = setInterval(function() {callCharts();}, 1000); }); cpu stores the CPU … -
How am I to use Django and Django Rest Framework in building mobile applications such as SnapChat and Instagram?
I am delving into the field of mobile applications. I am currently part of a project that consist of buidling an app that will span over different platforms (Desktop, mobile: iOS, Android). What part will my knowledge on Django and Django RF play in building this app for iOS and Android mobiles ? So far I only used Django for building websites. -
'Settings' object has no attribute 'RECAPTCHA_SECRET_KEY'
I got this Error when user want to register: AttributeError at /accounts/register/' 'Settings' object has no attribute 'RECAPTCHA_SECRET_KEY' Request Method: POST Request URL: http://127.0.0.1:8009/accounts/register/ Django Version: 1.11.3 Exception Type: AttributeError Exception Value: 'Settings' object has no attribute 'RECAPTCHA_SECRET_KEY' Exception Location: /home/ali/bestoon/.venv/local/lib/python2.7/site-packages/django/conf/init.py in getattr, line 57 Python Executable: /home/ali/bestoon/.venv/bin/python Python Version: 2.7.12 Python Path: ['/home/ali/bestoon/bestoon', '/home/ali/bestoon/.venv/lib/python2.7', '/home/ali/bestoon/.venv/lib/python2.7/plat-x86_64-linux-gnu', '/home/ali/bestoon/.venv/lib/python2.7/lib-tk', '/home/ali/bestoon/.venv/lib/python2.7/lib-old', '/home/ali/bestoon/.venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/ali/bestoon/.venv/local/lib/python2.7/site-packages', '/home/ali/bestoon/.venv/lib/python2.7/site-packages'] -
Number of children explodes after filtering on child value
I have a model (Track) with children (Rank). That can be described (simplified) as: class Track(models.Model): id = models.CharField('Unique ID', max_length=100, primary_key=True) title = models.CharField('Track title', max_length=100) artist = models.CharField('Artist name', max_length=100) class Rank(models.Model): id = models.AutoField(primary_key=True) trackid = models.ForeignKey(Track, related_name='rank') cdate = models.DateField("Date", blank=True, null=True) When doing this: track_list = Track.objects.filter(Q(artist__icontains=query) | Q(title__icontains=query)) \ .annotate(children=Count('rank')) for track in track_list: print(track.children) The number of children per track are all close to 100 (e.g 65,78,95) and that is correct. But when I narrow the queryset further down by applying another filter and a needed annotation: track_list = track_list.distinct() \ .filter(rank__cdate__year=filterquery) \ .annotate(entrydate=Min('rank__cdate')) \ .annotate(children=Count('rank')) for track in track_list: print(track.children) The number of children explodes to several thousands per track. Any ideas? -
“maximum recursion depth exceeded”when I use staticfiles
when I use this it error, but I must use staticfiles, here are my setting ,I am new enter image description hereenter image description here -
Django REST Framework + Django REST Swagger
Having a hard time configuring Swagger UI Here are the very explanatory docs in - https://django-rest-swagger.readthedocs.io/en/latest/. My settings.py looks like this. urls.py looks like this. But the swagger web page isn't loading properly. and the console log is as follows. What might be the problem here? -
convert python object to protocol buffer object
I have a django app up and running. We have to support serialisation via protobuf. For achieving the same we want to do minimum changes to our codebase and hence what we are doing is keeping the code as is which creates a python object returns json. We have created a .proto file with the same expected format and and compiled the same. Now at the time of returning the response, i want to convert the python object into protobuf object. I am trying to do this via code: response = proto_object(**result) This results in following error: ValueError: Field name must be a string Can somebody tell us what is wrong with above initialisation of protobuf and also the right way of achieving this. I will share the .proto file if that is of any use.