Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Python/Plotly Icon level
I am working on a dashboard and I would like to use "icon rating" (is there a name for this?). I mean having a range of icons and see if they are full/empty/coloured in a scale of 1 to 4/5 or whatever number of icons. The most usual case is done with stars in many reviews but I would like to do it with other icons related to my dashboard topic. What's the best way to do it? I am using Django/Python/Plotly for this dashboard so tools related to these would be best. -
Django Rest Framework unique field constraint on array
So, I'm trying to make an endpoint where I insert a list of objects. My issue is the behavior and response when inserting duplicates. What I want to accomplish is to: Send the duplicate lead external_id(s) in the error response Insert any other non duplicated object I'm pretty sure this logic (for the response and behavior) could be accomplished in the modifying the serializer.is_valid() method... but before doing that, I wanted to know if anyone had experience with this kind of request.. Maybe there is a "clean" way to do this while keeping the unique validation in the model. Data on OK response: [ { "external_id": "1", "phone_number": "1234567890" } ] Data for a FAIL request (1 is dup, but 2 should be inserted. Expecting a response like "external_id" : "id 1 is duplicated"): [ { "external_id": "1", "phone_number": "1234567890" }, { "external_id": "2", "phone_number": "2234567890" } ] models.py class Lead(models.Model): external_id = models.CharField(max_length=20, unique=True) phone_number = models.CharField(max_length=50) serializers.py class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' def create(self, validated_data): lead = Lead.objects.create(**validated_data) log.info(f"Lead created: {lead.import_queue_id}") return lead views.py class LeadView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @extend_schema(description="Insert campaign data", request=LeadSerializer(many=True), responses=None, tags=["Leads"]) def post(self, request): serializer = … -
Iterator should return strings, not bytes (the file should be opened in text mode)
this is my code.. def import_excel(request): if request.method == 'POST': person_resource = PersonResource() dataset = Dataset() new_person = request.FILES['myfile'] if not new_person.name.endswith('csv'): messages.info(request,'Wrong format') return render(request,'upload.html') imported_data = dataset.load(new_person.read(),format='csv') for data in imported_data: value = Person( data[0], data[1], data[2] ) value.save() return render(request,'upload.html') while importing the csv file to the database getting the error: iterator should return strings, not bytes (the file should be opened in text mode) like this -
Python django Failed to create a virtualenv
I was trying to create a virtual env with python3. But it failed to create new. But the existing virtual env are working fine. Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 82, in _get result = get_wheel( File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\acquire.py", line 23, in get_wheel wheel = from_bundle(distribution, version, for_py_version, search_dirs, app_data, do_periodic_update, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\bundle.py", line 17, in from_bundle wheel = periodic_update(distribution, of_version, for_py_version, wheel, search_dirs, app_data, per, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 35, in periodic_update handle_auto_update(distribution, for_py_version, wheel, search_dirs, app_data, env) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 69, in handle_auto_update embed_update_log.write(u_log.to_dict()) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\virtualenv\app_data\via_disk_folder.py", line 154, in write self.file.write_text(json.dumps(content, sort_keys=True, indent=2)) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\pathlib.py", line 1154, in write_text with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f: File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\pathlib.py", line 1119, in open return self._accessor.open(self, mode, buffering, encoding, errors, PermissionError: [Errno 13] Permission denied: 'C:\\Users\\DELL\\AppData\\Local\\pypa\\virtualenv\\wheel\\3.10\\embed\\3\\pip.json' fail -
Can we import the modules/functions from stand alone python code to DJango framework?
I have a parent directory under which we have multiple directories where standalone Python codes are developed and these py files are executed with parameters(ex - python --env=prod file_name.py) and in the same parent directory I have the directory of DJango code and the DJango code are importing the modules from standalone python modules. When I try to start the Django server using the command - "python manage.y runserver" I get the message - "manage.py: error: unrecognized arguments: runserver". Can you please help if importing of standalone python modules are allowed or not into the Django and if allowed then how we can achieve it. -
Why docker compose dosent create container with container_name
i create Dockerfile and docker-compose.yml. i build image with tag "django-image" Dockerfile: `FROM python:3 WORKDIR /code-django COPY . /code-django RUN pip3 install -r requirements.txt` docker-compose.yml: services: db: image: postgres container_name: db-money volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: image: django-image container_name: money volumes: - .:/code-django ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db in docker compose i have 2 services,"db" and "web". docker compose creates "db" with "container_name: db-money" and starts it. but compose dosent create anothe container with "container_name: money". why the second "container_name" dosent work?? enter image description here -
unable to install backports.zoneinfo
when i execute 'pip install -r requirements.txt ' this is displayed and i can't download backports.zoneinfo . `(venv) ##########@Air-de-#### ###### % pip install -r requirements.txt ... lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found #include "Python.h" ^~~~~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Successfully built PyYAML Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects (venv) ######@Air-de-###### ####### % pip install backports.zoneinfo ... lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found #include "Python.h" ^~~~~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects` -
Django Sitemap Generates https:// Twice in Development
The example.com/sitemap.xml is returning loc with double https:// making the generated sitemap to be incorrect/unacceptable. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://https://example.com</loc> <changefreq>monthly</changefreq> <priority>1.0</priority> </url> I've tried changing the protocol in the sitemaps.py file from https to http but that only appends http:// in front of the https://example.com/. Any ideas? -
Django 1.11.29. When sending long string on subject, Django inserts \t and extra space after comma
Django 1.11.29. When sending long string on subject, Django inserts \t and extra space after comma. I tried sending emails setting to QP, 8bit. But Django if subject length is more than 70 chars, it inserts extra space and tabulation From nobody Fri Jan 20 13:25:04 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Subject: Earth - Earth population is 4, 652, 123 people and digest is d3ea33dbe135a35fdde8984d1d920b8e6149526ed1fb5c9c656e8834d85d3a4e From: me@me.com To: me1@me.com Date: Fri, 20 Jan 2023 13:25:04 -0000 Message-ID: <20230120132504.88256.54199@medet-Lenovo-ideapad-330-15IKB> Content-Transfer-Encoding: quoted printable Subject: Earth - Earth population is 4, 652, 123 people and digest is d3ea33dbe135a35fdde8984d1d920b8e6149526ed1fb5c9c656e8834d85d3a4e Content-Type: text/html; charset=UTF-8 MIME-Version: 1.0 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tem= por incididunt ut labore et dolore magna aliqua. Suscipit tellus mauris a d= iam maecenas sed enim ut. In vitae turpis massa sed. Dictum varius duis at = consectetur lorem. At volutpat diam ut venenatis tellus in metus vulputate = eu. Vel quam elementum pulvinar etiam non quam lacus suspendisse. Lacus lao= i've tested and tried a lot of things, but i dont know how to resolve to sending long subjects. I also checked and its not helps https://code.djangoproject.com/ticket/7747 i've tested and tried a lot … -
I can't loop trough a dictionnary in my Django Template
I'm trying to loop trough a dictionnary to create a simple table with the keys in a column and the values in the other. So in my view I create the dictionnary vegetables_dict. I loop trhough the "items" of a "cartitem". If the item doesn't alrady exists I created a key with the name of a ForignKey of "item" and a value with its attribute quantity. Otherwise I increment the already existing key with the corresponding quantity def dashboard_view(request): carts = Cart.objects.filter(cart_user__isnull = False) cartitems = CartItem.objects.all() vegetables_dict = {} for item in cartitems: if item.stock_item.product_stockitem.name in vegetables_dict: vegetables_dict[item.stock_item.product_stockitem.name] += item.quantity else : vegetables_dict[item.stock_item.product_stockitem.name] = item.quantity context = { 'carts' : carts, 'cartitems' : cartitems, 'items' : vegetables_dict } return render(request, "maraicher/dashboard.html", context) In the template i Tried : <table> <thead> <tr> <th colspan="2"> Récapitulatif de récole</th> </tr> </thead> <tbody> <th>Produit</th> <th>Quantité</th> <div>{{items}}</div> {% for key, value in items.item %} <tr> <td>{{key}}</td> <td>{{value}}</td> </tr> {% endfor %} </tbody> </table> {{items}} render the dictionnary but the table is empty. Any idea what is happening? I aslo tried {% for item in items %} <tr> <td>{{item}}</td> <td>{{item.item}}</td> </tr> {% endfor %} -
What is the main difference between making a query using Manager.raw() method and connection.cursor() method?
I need to know which one is faster and why, and I also need to know the cases for each one. I try them both but I can't find the difference. -
What is the best experinces to structure a Django project for scale?
Django is great. But as we add new features, as our dev team grows, the software needs to be stable on production, things can get quite messy. We are going to want some common patterns, derived from experience, on how to structure your Django project for scale and longevity. What is your suggestion? Indeed, there are many models and patterns for development, but we want to know your experiences. -
session based django social
I'm using social-auth-app-django for authenticate with google. The process working fine and the user is register in the DataBase. The problem begins when I'm trying to login the users automatically when they register with Google. The users keeps to be unauthenticated in the session. Here is my current configurations using social-auth-app-django and djoser: settings.py: AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend' ) DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True, 'SEND_CONFIRMATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'CREATE_SESSION_ON_LOGIN': True, 'SOCIAL_AUTH_TOKEN_STRATEGY': 'members.social_token.TokenStrategy', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [ 'http://localhost:3000/google' ], 'SERIALIZERS': { 'current_user': 'members.serializers.UserCreateSerializer', } I think the most relevant part is the SOCIAL_AUTH_TOKEN_STRATEGY. Where the members.social_token.TokenStrategy is: from django.contrib.auth import login from django.http import HttpRequest from django.conf import settings from importlib import import_module class TokenStrategy: @classmethod def obtain(cls, user): from rest_framework_simplejwt.tokens import RefreshToken from six import text_type refresh = RefreshToken.for_user(user) request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) session_key = None request.session = engine.SessionStore(session_key) login( user=user, request=request, ) user.is_active = True return { "access": text_type(refresh.access_token), "refresh": text_type(refresh), "user": user, } I can see that the sessionid and the csrftoken is been saved in the browser cookies and in the TokenStrategy the request.user.is_authenticated equals to true. My problem is that for all the following requests the value of the request.user.is_authenticated keeps … -
Overriding django admin get_queryset()
I have two models which is one of them proxy model. In admin I registered both and overrided get_queryset() method but it is not working as expected. admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(language='en') @admin.register(ProxyCategory) class ProxyCategoryAdmin(CategoryAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(language='zh') In admin page ProxyCateegoryAdmin not showing objects, if I remove get_queryset() from CategoryAdmin, it works but wanted filter both of them. Thanks in advance -
Django ViewSet, get data from model without foreign key
My Models def ModelA(models.Model): id = models.CharField(primary_key=True, max_length=50) val_a = models.CharField(db_index=True, max_length=100) val_b = models.CharField(db_index=True, max_length=100) modelB = models.ForeignKey(modelB, on_delete=models.CASCADE, db_constraint=False) def ModelB(models.Model): id = models.CharField(primary_key=True, max_length=50) val_c = models.CharField(db_index=True, max_length=100) val_d = models.CharField(db_index=True, max_length=100) def ModelC(models.Model): id = models.CharField(primary_key=True, max_length=50) val_e = models.CharField(db_index=True, max_length=100) modelB = models.OneToOneField(ModelB, on_delete=models.CASCADE, null=False, blank=False) My ViewSet class ModelAViewSet(ListDataResponseMixin, APIKeyViewSet): endpoint_permissions = [APILicenseKeyPermission.Codes.A] queryset = ModelA.objects.all() serializer_class = ModelASerializer filterset_class = ModelAFilter filter_backends = [DjangoFilterBackend] My Serializer class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = ( "id", "val_a", "val_b" ) When querying ModelA I would like to get val_e from ModelC. I am learning django, and previously when I needed to do something like this, I would use select_related, however, since there is no clear path from ModelA -> ModelC using foreign keys, I am not sure how to proceed. (My base models cannot change). How would I modify my ViewSet to include the needed ModelC data in my queryset? And then for my ModelASerializer I would like to just be able to add in val_e. -
How to get all the observed Elements as we scroll down using the intersection Observer?
Ok, so i am getting Only 6 divs as i load my webpage, and when i scroll down, the other 6 get loaded (Lazy load), but my Observer does not catch it whatsoever, What could be the Problem here ? I have tried the Intersection Observer and load them at the end when all the body Is loaded. My JS Code Using Intersection Observer: var targets = [...document.getElementsByName('item-id')]; const options = { }; let clickedId_test; const observer = new IntersectionObserver(function(entries, observer){ entries.forEach(entry => { if (!entry.isIntersecting) { return; } clickedId_test = entry.target console.log(clickedId_test) }); }, options); targets.forEach(like_button => { observer.observe(like_button); }) My Images Getting 1st 6 ids Even after scrolling only get 1st 6 ids -
1062, "Duplicate entry 'admin1' for key 'username'"
models.py class CustomUser(AbstractUser): user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student")) user_type=models.CharField(default=1,choices=user_type_data,max_length=10) class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() username = models.CharField(max_length=30) email = models.EmailField(max_length=100) password = models.CharField(max_length=100) fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) forms.py class palForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model=palabout fields =['username','password','email','fname','lname','dob','gender','profileImage'] views.py from .forms import palForm def add_form(request): form = palForm(request.POST, request.FILES) username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") if request.method == "POST": form = palForm(request.POST , request.FILES) user=CustomUser.objects.create_user(username=username,password=password,email=email,user_type=1) if form.is_valid() : try: form.save() messages.success(request,"Successfully Added") return render(request,"home.html") except: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html") else: form=palForm() return render (request,"home/pal-form.html",context={"form":form}) Error: Traceback (most recent call last): File "C:\Users\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Desktop\myschool\views.py", line 19, in polabout CustomUser.objects.create_user(username=username,password=password,email=email,user_type=3) File "C:\Users\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 161, in create_user return self._create_user(username, email, password, **extra_fields) File "C:\Users\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 155, in _create_user user.save(using=self._db) File "C:\Users\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 68, in save super().save(*args, **kwargs) File "C:\Users\Anaconda3\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "C:\Users\Anaconda3\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "C:\Users\Anaconda3\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "C:\Users\Anaconda3\lib\site-packages\django\db\models\base.py", line 1047, in _do_insert return manager._insert( File "C:\Users\Anaconda3\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, … -
DRF: Which if better to create custom structure of response in Serializer/ModelSerializer?
I am currently making a simple CRUD application on Django Rest Framework. I need to return a response to the client for any request in a specific structure. For example, if a client makes a POST request to create a new record and it was executed successfully, then API needs to return such structure: { "data": [ { "id": 1, "email": "bobmarley@gmail.com", } ], "error": {} } Let's say the problem is related to the model field. In this case, the API should return such a structure: { "data": [], "error": { "email": [ "This field is required." ] } } If the problem is not related to the model field, then it is necessary to return to the client such a structure where there would be a description of the error: { "data": [], "error": { "non_field_errors": [ "Description of the error." ] } } My current code returns an incorrect structure. Should I configure all this at the serialization level? { "data": [], "error": { "non_field_errors": [ "{'email': [ErrorDetail(string='person with this email already exists.', code='unique')]}" ] } } models.py: class Client(models.Model): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) class Meta: db_table = "clients" def __str__(self): return self.email serializers.py: class … -
The view Kespaweb.views.contact didn't return an HttpResponse object. It returned None instead
hey guys am trying to make a code on sending mails from contact page and am stuck somehow tried sending mails from contact pageenter image description here -
Is CCAvenue payment gateway integration possible in REACT and Django
I'm trying to integrate CCAvennue to my website which has tech stack REACT and DJANGO, but I'm confused with documentation shared by CCAvenue. Please can someone simplify the implementation? -
Box Developer Account JWT Auth Related query
I am using BoxSDK for python. There I am using JWT authentication. I have created an app on Developer account for testing which uses authentication as OAuth 2.0 with JSON Web Tokens (Server Authentication). After creating this TestApp in developer account I am using it in some APIs to do some basic operations in Box. I also got an Service Account ID. related to my test app. All good till here. But I am facing issue when I am uploading a folder in my box account through browser and then try accessing that folder contents via Box API, its not accessible. The same is accessible when I am adding the service account ID as a collaborator in that folder. So I want to know if there is any option using which I dont need to do the above part i.e. adding service account ID as a collaborator in every folder that I want to access through API. Please suggest. Is this behavior only for test account? If I take Enterprise edition of Box, will this issue be solved? I need that whatever folder I upload in Box through website, it should be accessible vis API where I am using JWT … -
Deploying Django & React app in Azure failing to load
I have built an app with an Django back-end, a React front-end and a Postgres database, and I am in the process of deploying them to Azure for the first time. Key actions I have taken: used django-webpack-loader and webpack-bundle-tracker, so my front and back-end code can be deployed as one app set up Django app in Azure using the App service migrated my postgres database into Azure using the Azure Database for PostgreSQL flexible server Current outputs: deployed code successfully using github continuous deployment set my database, allowed_hosts, secreet_key and port values in application settings successfully migrated my django folders into the Azure environment using the Web SSH in the Azure portal when I run manage.py runserver 9000 in the Web SSH, I am able to connect My issue: When I visit my url, the page times out, with 'Application Error'. I'm troubleshooting the error in the logs, which return the output below. I have noted the error - TypeError: expected str, bytes or os.PathLike object, not PosixPath, but I'm stuck after this. Can anyone offer any suggestions? Azure Error logs: /home/LogFiles/2023_01_20_lw0sdlwk0000X9_default_docker.log (https://wittle-test.scm.azurewebsites.net/api/vfs/LogFiles/2023_01_20_lw0sdlwk0000X9_default_docker.log) 2023-01-20T10:10:15.109452667Z File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2023-01-20T10:10:15.109456467Z File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed … -
django-(1062, "Duplicate entry 'admin1' for key 'username'") [closed]
models.py class CustomUser(AbstractUser): user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student")) user_type=models.CharField(default=1,choices=user_type_data,max_length=10) class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() username = models.CharField(max_length=30) email = models.EmailField(max_length=100) password = models.CharField(max_length=100) fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) forms.py class palForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model=palabout fields =['username','password','email','fname','lname','dob','gender','profileImage'] views.py from .forms import palForm def add_form(request): form = palForm(request.POST, request.FILES) username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") if request.method == "POST": form = palForm(request.POST , request.FILES) user=CustomUser.objects.create_user(username=username,password=password,email=email,user_type=1) if form.is_valid() : try: form.save() messages.success(request,"Successfully Added") return render(request,"home.html") except: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html") else: form=palForm() return render (request,"home/pal-form.html",context={"form":form}) I have got saved Custom User but Don't saving in palform but why is not showing database palform page. what was the problem? Can anyone help me? -
How can I annotate django-polymorphic models that have GenericRelations to other models with GenericForeignKeys?
I have a parent model named Content that inherits from Django polymorphic. This is a simplified example, but I have a Post model that inherits from Content. On the Content model, notice that I have a GenericRelation(Note) named notes. What I'm trying to do is annotate all Content objects with a count of the number of notes. It's the exact same result you would get in the below for loop. for content in Content.objects.all(): print(content.notes.count()) Below is a fully reproducible and simplified example. To recreate the problem Setup new Django project, create superuser, add django-polymorphic to the project, and copy/paste the models. Make migrations and migrate. My app was called myapp. Open manage.py shell, import Post model, and run Post.make_entries(n=30) Run Post.notes_count_answer() and it will return a list of numbers. These numbers are what the annotated Content PolymorphicQuerySet should show. Example: Post.notes_count_answer() [3, 2, 3, 1, 3, 1, 3, 1, 2, 1, 2, 2, 3, 3, 3, 1, 3, 3, 2, 3, 2, 3, 2, 1, 2, 1, 1, 1, 1, 2] The first number 3 in the list means the first Post has 3 notes. What have I tried (simplest to complex) basic >>> Content.objects.all().annotate(notes_count=Count('notes')).values('notes_count') <PolymorphicQuerySet [{'notes_count': 0}, {'notes_count': … -
local gitlab Auth 2.0 and django
Hello We made our own Gitlab installation on our server. I installed Readthedocs Local in the link below. In order to connect our accounts on gitlab with readthedocs, I was asked to make the following settings from the gitlab section in the readthedocs document. https://readthedocs.org/ https://dev.readthedocs.io/en/latest/install.html But interestingly, even though I set the settings on our own server gitlab.local, by default django goes to gitlab.com when I connect to gitlab via devthedocs.org. However, it should connect to gitlab.local on my server, how can I fix this problem? On page 34 of this document here https://readthedocs.org/projects/django-allauth/downloads/pdf/latest/ "The GitLab provider works by default with https://gitlab.com. It allows you to connect to your private GitLab server and use GitLab as an OAuth2 authentication provider as described in GitLab docs at http://doc.gitlab.com/ ce/integration/oauth_provider.html" I need your support in this matter. Thank you very much. Configure the applications on GitHub, Bitbucket, and GitLab. For each of these, the callback URI is http://devthedocs.org/accounts//login/callback/ where is one of github, gitlab, or bitbucket_oauth2. When setup, you will be given a “Client ID” (also called an “Application ID” or just “Key”) and a “Secret”. Take the “Client ID” and “Secret” for each service and enter it in your local …