Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble deciding schema of an SQL database in Django
I am building a database which has in it a bunch of molecules and a bunch of different attributes ( e.g. ionization energy levels ). Each attribute may have one or many values and I'm not sure what the best way to represent this is. I am very new to relational databases so I'm having trouble figuring out the best ACID compliant way of storing it. I am also very new to Django, though I have worked through the tutorial and some of the documentation. I should mention as well that currently I'm using sqlite as my RDBMS, as the website will be read only. My current conception is to have two models. One for describing the molecule, right now this is just its name, but it may end up including other descriptors as well. The second model would be for the attributes, its effectively just attribute name, molecule name, and a single value that the attribute holds. They have a one to many relationship from the molecule name to the attribute values. But this means that the attribute name and molecule name will be repeated a lot. Is this ok? Is there a better method? Eventually I'd like users … -
How can I render unlimited nested replies (Reddit-style) in a single Django template?
I’m building a Reddit-style comment system with Django, and need users to be able to reply not only to a post but also to any comment, indefinitely deep. My goal in here is when a user replies to a reply, that reply should itself be commentable, forming a true tree—not just two levels. With below code: Top-level comments display fine, direct replies to a top-level comment show up, but replies to those replies never appear even though they’re saved correctly in the database. I’d love to keep it clean and avoid infinite {% for %} nesting. Is there a recommended Django-template pattern (perhaps a recursive template tag or custom inclusion tag) that works without breaking CSRF for the reply forms? My model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="comments" ) up_vote = models.BigIntegerField(blank=True, null=True) down_vote = models.BigIntegerField(blank=True, null=True) parent = models.ForeignKey( "self", null=True, blank=True, on_delete=models.CASCADE, related_name="replies" ) body = models.TextField() created_at = models.DateTimeField(default=timezone.now) class Meta: ordering = ["created_at"] def __str__(self): return f"Comment by {self.author} on {self.post}" my views: @login_required def post_details(request, slug): post = get_object_or_404(Post, slug=slug) community = post.community # Handle comment or reply POST if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): … -
TypeError: string indices must be integers when using Google login with django-allauth
I'm encountering the following error when attempting to implement Google login using django-allauth in my Django project: social_login = adapter.complete_login(request, app, token, response=response) File "/.venv/lib/python3.8/site-packages/allauth/socialaccount/providers/google/views.py", line 43, in complete_login response["id_token"], TypeError: string indices must be integers Right now im using django-allauth version 0.54.0 and django 2.2.28 I have the following GoogleLogin class set up for handling Google OAuth2 authentication: class GoogleLogin(SocialLoginView): authentication_classes = [] permission_classes = [] adapter_class = GoogleOAuth2Adapter client_class = OAuth2Client callback_url = "https://developers.google.com/oauthplayground" Frontend sends me just the access_token In the GoogleOAuth2Adapter, the complete_login method is implemented to decode the id_token from the Google response: class GoogleOAuth2Adapter(OAuth2Adapter): provider_id = GoogleProvider.id access_token_url = ACCESS_TOKEN_URL authorize_url = AUTHORIZE_URL id_token_issuer = ID_TOKEN_ISSUER def complete_login(self, request, app, token, response, **kwargs): try: print(response) identity_data = jwt.decode( response["id_token"], # Since the token was received by direct communication # protected by TLS between this library and Google, we # are allowed to skip checking the token signature # according to the OpenID Connect Core 1.0 # specification. # https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation options={ "verify_signature": False, "verify_iss": True, "verify_aud": True, "verify_exp": True, }, issuer=self.id_token_issuer, audience=app.client_id, ) except jwt.PyJWTError as e: raise OAuth2Error("Invalid id_token") from e login = self.get_provider().sociallogin_from_response(request, identity_data) return login oauth2_login = OAuth2LoginView.adapter_view(GoogleOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(GoogleOAuth2Adapter) -
Count distinct values of Subquery
I've got these models: class Component(models.Model) name = models.CharField(max_length=50) class ComponentAttribute(models.Model) component = models.ForeignKey(Component) context = models.ForeignKey(Context) subcategory = models.ForeignKey(SubCategory) material = models.ForeignKey(Material) measurement = models.ForeignKey(Measurement) value = models.FloatField() I want to annotate the count of unique attributes to each component in a QuerySet. A attribue is unique when it has a unique combination of context, subcategory and material for a given component. Based on other posts here and the Django documentation I craftet a Query based on a subquery. # Create a subquery that counts the distinct combinations float_attributes_count = Subquery( ComponentAttributeFloat.objects .filter(component=OuterRef('pk')) .order_by( 'subcategory_id', 'context_id', 'material_id') .distinct( 'subcategory_id', 'context_id', 'material_id') .values("component__id") .annotate(count=Count('id')) .values('count')) components = Component.objects.annotate( unique_attributes=float_attributes_count ) When I now try to equate that query with this basic loop to print my result. for component in components: print(f'{component}: {component.unique_attributes}') I get hit with this error: NotImplementedError: annotate() + distinct(fields) is not implemented. It looks like the combination of requirements I have lead to an query that is unexecutable and I can't find examples that check all the boxes for me. Can anyone help me with a working query using an other path? (For refrence I use a PostgreSQL database which should support this distinct statement see: https://docs.djangoproject.com/en/5.2/ref/models/querysets/#django.db.models.query.QuerySet.distinct) -
ModuleNotFoundError: No module named 'captcha'
guys, I'm trying to add a Google Captcha to a Django form, but I still keep getting the following error even when everything has been successfully configured. ** Is there a better way to make it work?** Here are my code configuration and I installed the pip install django-recaptcha. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contact', 'captcha', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] from django import forms from django_recaptcha.fields import ReCaptchaField from django_recaptcha.widgets import ReCaptchaV2Checkbox class ContactForm(forms.Form): email = forms.EmailField() feedback = forms.CharField(widget=forms.Textarea) captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) -
StreamingHttpResponse being buffered when using uvicorn/gunicorn/daphne in Django
I have a very simple view that Streams a repsonse. When using python manage.py runserverthe stream works as expected. But, when we use uvicorn app.asgi:application or daphne app.asgi:application or gunicorn app.asgi:application the stream is buffered in the UI and the response arrives completed instead of by chunks. result = core_services.generate_ai_v3_response( prompt=prompt, previous_response_id=previous_response_id, broker_id=broker_id, ) response = StreamingHttpResponse(result, content_type="text/event-stream") # Add proper streaming headers # Add aggressive streaming headers response["Cache-Control"] = "no-cache" response["X-Accel-Buffering"] = "no" return response -
What's the difference between blank=True and null=True in Django model fields?
I'm learning Django and trying to understand the difference between blank=True and null=True when defining model fields. I created a model with both null=True and blank=True, and then tried submitting a form with the field left empty. I expected it to save NULL in the database and not throw a validation error. It worked, but I'm not sure why both options are needed — that's what I'm trying to understand clearly. -
django-vite static assets being served but not loading on an Nginx deployment
I'm deploying a simple Django project on a local Ubuntu server VM running Docker (3 containers, Postgres, nginx and Django). The project uses a lot of HTMX and DaisyUI. On my dev environment they worked well while being served by a Bun dev server and using django-vite, but now on prod everything works perfectly fine, except for the static assets generated by django-vite. The strangest part is that the files are being delivered to the clients but not loading correctly (the app renders but only the static assets collected by Django, like icons, are being displayed. If I check the network tab on my devtools, I can see the django-vite files are being served). Any idea what could be causing this? Here is my vite.config.mjs import { defineConfig } from "vite"; import { resolve } from "path"; import tailwindcss from "@tailwindcss/vite"; export default defineConfig({ base: "/static/", build: { manifest: "manifest.json", outDir: resolve("./src/staticfiles"), emptyOutDir: false, write: true, rollupOptions: { input: { main: "./src/static/js/main.js", }, output: { entryFileNames: "js/[name].[hash].js", chunkFileNames: "js/chunks/[name].[hash].js", assetFileNames: "assets/[name].[hash][extname]", }, }, }, plugins: [tailwindcss()], }); Here is my nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; # sendfile on; # tcp_nopush on; … -
Django migration successfully applied, but the database is not modified
I need to use a secondary SQLite database in a new Django project. This database is on the local filesystem but outside the Django folder. Its path is specified in a .env file at the root of the Django project. I want Django to be able to manage migrations on that database, but I already have data in it, which I don't want to loose. I was able to integrate the database into the Django project, and I see no error at any point. I can fetch data from the database via the Django shell. However, when I try to apply migrations, nothing happens: the database is not modified, but Django doesn't give me any error (in fact it says the migration has been applied). Here's what I did: created an "archiver" app within Django within this app, created a routers.py file with the following code: class ArchiverDbRouter: def db_for_read(self, model, **hints): if model._meta.app_label in ['archiver']: return 'archiver' return None def db_for_write(self, model, **hints): if model._meta.app_label in ['archiver']: return 'archiver' return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in ['archiver']: return db == 'archiver' return None configured settings.py to use two databases. The idea is to keep the … -
How do you deal with permission management when using Elasticsearch indexes?
I am using django-guardian for per-object permission management and django-elasticsearch-dsl for quicker queries across our data. It's pretty straightforward for public lists, but I am having difficulties designing a scalable permission management, so that the filtered list would show only those items that the current user request.user has access to view and change. Some solutions suggested by AI: Get a list of uuids that the user has access to, and then filter items in elasticsearch by those uuids (not very scalable). Post-process the public results with django-guardian API functions - however that takes too long for entries with tens of thousands of results (there is a possibility to skip pagination and process only the first page, but that's not preferable). Add a list of user ids and group ids who can view, edit, and delete items to the item index and check the current user's id and group ids against those fields. Create an index for the User model with all viewable, editable, and deletable items by their uuids and then do terms_lookup in that index to filter list of items in question by the uuids the user can access. All those approaches are questionable to me, when I am … -
"Internal Server Error" when sending email via Django using DigitalOcean
When trying to send an email from a Django production setup (using gunicorn) on a Digitalocean droplet, I get "Internal Server Error" on the browser, and gunicorn logs this error: … File "/usr/lib/python3.13/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) ~~~~~~~~~~~~^^^^^^^^^^^^ File "/usr/lib/python3.13/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^ self.source_address) ^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/socket.py", line 849, in create_connection sock.connect(sa) ~~~~~~~~~~~~^^^^ File "/usr/lib/python3.13/site-packages/gunicorn/workers/base.py", line 204, in handle_abort sys.exit(1) ~~~~~~~~^^^ SystemExit: 1 This used to work without issues last year. -
How to use DRF serializer fields as django-filter filter fields?
I’m working with Django REST Framework and django-filter to implement API filtering. I created custom serializer fields (for example, a JalaliDateField that converts between Jalali and Gregorian dates, and applies Django’s timezone settings). I expected that I could just pass these serializer fields into a django_filters.Filter by setting field_class, but it turns out Filter.field_class is only compatible with django.forms.Field, even when using django_filters.rest_framework. So my question is: Is there a clean way to make django-filters work directly with DRF serializer fields? What I tried Naively plugging in DRF serializer fields: class JalaliDateFilter(django_filters.Filter): field_class = MyCustomJalaliDateSerializerField This fails, since django-filters expects a forms.Field, not a DRF serializers.Field. Proposed solution #1: Write a wrapper that adapts DRF fields into Django form fields Here’s a minimal sketch: from django import forms from rest_framework import serializers class DRFFieldFormWrapper(forms.Field): """ Wrap a DRF serializer field so it can behave like a Django form field. """ def __init__(self, drf_field: serializers.Field, *args, **kwargs): self.drf_field = drf_field kwargs.setdefault("required", drf_field.required) kwargs.setdefault("label", getattr(drf_field, "label", None)) super().__init__(*args, **kwargs) def to_python(self, value): if value in self.empty_values: return None return self.drf_field.run_validation(value) def prepare_value(self, value): return self.drf_field.to_representation(value) Then, a custom filter: import django_filters class DRFFieldFilter(django_filters.Filter): def __init__(self, *args, drf_field=None, **kwargs): if drf_field is None: … -
SSL Certificate error on SMTP Django DRF App
I have a Django DRF Backend that works just OK when using EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend". But then, switching to SMTP powered by Google as: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config("GMAIL_APP_HOST_USER") EMAIL_HOST_PASSWORD = config("GMAIL_APP_HOST_PASSWORD") DEFAULT_FROM_EMAIL = "TestApp" ACCOUNT_EMAIL_SUBJECT_PREFIX = "" I get a [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Basic Constraints of CA cert not marked critical This is being tested in a Windows 11 PC. Error details with Traceback: Django Version: 5.2.6 Python Version: 3.13.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'allauth', 'allauth.account', 'allauth.headless', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'dj_rest_auth', 'dj_rest_auth.registration', 'corsheaders', 'authentication.apps.AuthenticationConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware'] Traceback (most recent call last): File "C:\dev\myProject\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\views\decorators\csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\views\generic\base.py", line 105, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\utils\decorators.py", line 48, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\django\views\decorators\debug.py", line 143, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\dj_rest_auth\registration\views.py", line 47, in dispatch return super().dispatch(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\dev\myProject\venv\Lib\site-packages\rest_framework\views.py", line 515, … -
Discussion About Architecture: ROS2-Django-Webinterface
I am currently building a cobot/robot arm control interface and workflow planning tool. I am currently contemplating all my architecture choices so far, because I feel like the architecture is not scaling well and could fail under large loads. So I need to ask the community... General Architecture Overview The whole architecture is what I would call microservice-based (correct me if I am wrong). I have multiple standalone components (standalone means containerized in this case and also with its own area of functionality. E.g. camera controller, robot controller, gripper controller etc.). All of these components use ROS2 for communication and are implemented in their respective language, mostly C++ and Python. Then there is the Core Application which is a backend for connecting all information and managing the components. This is kind of the brain. This brain also has a UI. For the Core/UI stack I chose Python Django + ReactJS. I chose this stack because: I am fluent in Python and React, fast Prototyping for the first Prototype, Direct ROS2 Integration in Python, Django has a good ORM and supports async operations so that I can connect ROS2 (as a bridge for the UI kind of) and store data through … -
Django WeasyPrint high memory usage with large datasets
I am using WeasyPrint in Django to generate a PDF. However, when processing around 11,000 records, it consumes all available resources allocated to the Kubernetes pod. As a result, the pod restarts, and I never receive the generated PDF via email. Are there: Any lightweight PDF libraries that can handle generating PDFs for thousands of records more efficiently? Any optimization techniques in WeasyPrint (or in general) to reduce resource usage and generate the PDF successfully? -
Django model with FK to learner app model Group is displaying options from user admin Group
I have the following models: learner app class Group(models.Model): short_name = models.CharField(max_length=50) # company acronym slug = models.SlugField(default="prepopulated_do_not_enter_text") contract = models.ForeignKey(Contract, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() notes = models.TextField(blank=True, null=True) class Meta: ordering = ["short_name"] unique_together = ( "short_name", "contract", ) management app I've set up an Invoice model: class Invoice(models.Model): staff = models.ForeignKey(Staff, on_delete=models.RESTRICT) group = models.ForeignKey(Group, on_delete=models.RESTRICT) date = models.DateField() amount = models.DecimalField(max_digits=7, decimal_places=2) note = models.CharField(max_length=500, null=True, blank=True) When I try to add an invoice instead of the learner groups I'm being offered the user admin Group options: Can anyone help with what I'm doing wrong. I have the learner group as a FK in other models without issue. -
Django Unit Test - using factory_boy build() on a Model with Many-To-Many relationship
I’m working on writing unit tests for a DRF project using pytest and factory_boy. I’m running into issues with many-to-many relationships. Specifically, when I try to use .build() in my unit tests, DRF attempts to access the M2M field which requires a saved object, leading to errors. tests_serializers.py def test_serialize_quality_valid_data(self): user = UserFactory.build() quality = QualityFactory.build(created_by=user) serializer = QualitySerializer(quality) data = serializer.data assert data["num"] == quality.num error: FAILED quality/tests/tests_serializers.py::TestQualitySerializer::test_serialize_quality_valid_data - ValueError: "<Quality: Quality object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. model.py class QualityTag(ExportModelOperationsMixin("quality_tag"), models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField() class Quality(ExportModelOperationsMixin("quality"), models.Model): num = models.IntegerField() title = models.CharField(max_length=64) ... tags = models.ManyToManyField(QualityTag, related_name="qualities", blank=True) factories.py class QualityTagFactory(DjangoModelFactory): class Meta: model = QualityTag name = factory.Sequence(lambda n: f"Quality Tag {n}") class QualityFactory(factory.django.DjangoModelFactory): class Meta: model = Quality num = factory.Faker("random_int", min=1, max=999) @factory.post_generation def tags(self, create, extracted, **kwargs): if not create: return if extracted: for tag in extracted: self.tags.add(tag) serializers.py class QualitySerializer(serializers.ModelSerializer): tags = QualityTagDetailSerializer(many=True) created_by = UserProfileSerializer() updated_by = UserProfileSerializer() class Meta: model = Quality fields = "__all__" read_only_fields = ["quality_num", "tags", "created_by", "updated_by"] I’ve been advised to switch to .create() instead of .build(), but I’d prefer to … -
Django HttpOnly cookies not persisted on iOS Safari and WebView, but work on Chrome and Android ITP
I'm using Django to set HttpOnly and Secure cookies for my React web application. These cookies work perfectly on Chrome (both desktop and mobile) and Android devices. However, I'm encountering a major issue on iOS: -iOS Safari: Cookies are not persisted; they are treated like session cookies and are deleted when the browser is closed. -iOS React Native WebView: Similar to Safari, the cookies are not persisted. -İOS Chrome: It works. -Android React Native WebView: It works. MAX_AGE = 60 * 60 * 24 * 360 COMMON = { "httponly": True, "secure": True, "samesite": "None", "path": "/", "domain": ".kashik.net", "max_age": MAX_AGE, } def set_auth_cookies(response, access_token: str, refresh_token: str): response.set_cookie("refresh_token", refresh_token, **COMMON) response.set_cookie("access_token", access_token, **COMMON) return response I have confirmed that the max_age is set to a long duration, so it's not a session cookie by design. This issue seems to be specific to the iOS ecosystem. What could be causing this behavior on iOS Safari and WebView, and how can I ensure these cookies are properly persisted? <WebView ref={webRef} source={{ uri: WEB_URL }} style={styles.full} /* COOKIE PERSIST */ sharedCookiesEnabled thirdPartyCookiesEnabled incognito={false} /* FIX */ javaScriptEnabled domStorageEnabled allowsInlineMediaPlayback allowsFullscreenVideo mediaCapturePermissionGrantType="grant" startInLoadingState cacheEnabled={false} injectedJavaScriptBeforeContentLoaded={INJECT_BEFORE} injectedJavaScriptBeforeContentLoadedForMainFrameOnly={false} onMessage={handleWebViewMessage} onLoadEnd={() => { setLoadedOnce(true); lastLoadEndAt.current = … -
How to set up an in-project PostgreSQL database for a Django trading app?
I’m working on a Django-based trading platform project. Currently, my setup connects to a hosted PostgreSQL instance (Render). My client has now requested an “in-project PostgreSQL database”. From my understanding, this means they want the database to run locally within the project environment (rather than relying on an external hosted DB). Question: What is the best practice for including PostgreSQL directly with the project? Should I: Use Docker/Docker Compose to spin up PostgreSQL alongside the Django app, Include migrations and a seed dump in the repo so the DB can be created on any machine, or Is there another recommended approach? I want the project to be portable so the client (or other developers) can run it without needing to separately set up PostgreSQL. -
Deployment errors
When I try to deploy my web app built with Windsurf in Heroku, I get the following errors: Error: Unable to generate Django static files. ! ! The 'python manage.py collectstatic --noinput' Django ! management command to generate static files failed. ! ! See the traceback above for details. ! ! You may need to update application code to resolve this error. ! Or, you can disable collectstatic for this application: ! ! $ heroku config:set DISABLE_COLLECTSTATIC=1 ! ! https://devcenter.heroku.com/articles/django-assets Please help fix it. -
How can I set filter by month of folium map(Django project)
I am using folium and I can see in front folium map with markers, I use checkbox, but because of I have two month, I want to add radio button and selecting only one month. I want to have filters by months and also by statuses, but with different labels. I used chatgpt but it doesn't help me. I have also tried many things. What do you suggest as an alternative? I tried this but it is not working: GroupedLayerControl( groups={'groups1': [fg1, fg2]}, collapsed=False, ).add_to(m) My code: def site_location(request): qs = buffer.objects.filter( meter="Yes", ext_operators="No", ).exclude( # hostid="No" ).values('n', 'name', 'village_city', 'region_2', 'rural_urban', 'hostid', 'latitude', 'longitude', 'site_type', 'meter', 'ext_operators', 'air_cond', 'kw_meter', 'kw_month_noc', 'buffer', 'count_records', 'fix_generator', 'record_date', 'id', 'date_meter' ) data = list(qs) if not data: return render(request, "Energy/siteslocation.html", {"my_map": None}) m = folium.Map(location=[42.285649704648866, 43.82418523761071], zoom_start=8) critical = folium.FeatureGroup(name="Critical %(100-..)") warning = folium.FeatureGroup(name="Warning %(70-100)") moderate = folium.FeatureGroup(name="Moderate %(30-70)") positive = folium.FeatureGroup(name="Positive %(0-30)") negative = folium.FeatureGroup(name="Negative %(<0)") check_noc = folium.FeatureGroup(name="Check_noc") check_noc_2 = folium.FeatureGroup(name="Check_noc_2") for row in data: comments_qs = SiteComment.objects.filter(site_id=row["id"]).order_by('-created_at')[ :5] if comments_qs.exists(): comments_html = "" for c in comments_qs: comments_html += ( f"<br><span style='font-size:12px; color:black'>" f"{c.ip_address} - {c.created_at.strftime('%Y-%m-%d %H:%M')}: {c.comment}</span>" ) else: comments_html = "<br><span style='font-size:13px; color:black'>....</span>" html = ( f"<a target='_blank' … -
Django python manage.py runserver problem
When I make this command: python manage.py runserver I receive this response: {"error":"You have to pass token to access this app."} I ran my django app previously without any problems but this time it gives this error Do you have any suggestions to correct it best I am using the correct localhost and the port suggested by the Django app and it previously worked without problems and now I have this issue -
Multiple Data Entry in Django ORM
I have been trying to create a way that my Django database will store data for 7 consecutive days because I want to use it to plot a weekly graph but the problem now is that Django doesn't have a datetime field that does that. '''My Code''' #Model to save seven consecutive days class SevenDayData(models.Model): '''Stores the date of the latest click and stores the value linked to that date in this case our clicks''' day1_date= models.DateField(default=None) day1_value= models.CharField(max_length=20) day2_date= models.DateField(default=None) day2_value= models.CharField(max_length=20) day3_date= models.DateField(default=None) day3_value= models.CharField(max_length=20) day4_date= models.DateField(default=None) day4_value= models.CharField(max_length=20) day5_date= models.DateField(default=None) day5_value= models.CharField(max_length=20) day6_date= models.DateField(default=None) day6_value= models.CharField(max_length=20) day7_date= models.DateField(default=None) day7_value= models.CharField(max_length=20) #updating the model each time the row is saved updated_at= models.DateTimeField(auto_now= True) #function that handles all the saving and switching of the 7 days def shift_days(self, new_value): #getting todays date today= date.today() #shifting every data out from day_7 each time a date is added i.e the 7th day is deleted from the db once the time is due self.day7_date, self.day7_value = self.day6_date, self.day6_value #Overwriting each date with the next one self.day6_date, self.day6_value = self.day5_date, self.day5_value self.day5_date, self.day5_value = self.day4_date, self.day4_value self.day4_date, self.day4_value = self.day3_date, self.day3_value self.day3_date, self.day3_value = self.day2_date, self.day2_value self.day2_date, self.day2_value = self.day1_date, self.day1_value #writing todays … -
session.get not getting corrected file on remote server/local server
I have this piece of code that works complete fine on a single python script. When I try to test it out on local server it returns a html page saying link is not vaild. (I am expecting a PDF downloaded). Both localserver and python script returns a 200. url is the download link of a pdf file on the website. def get_file(url): headers = { 'User-Agent': user_agent, 'Cookie': cookie, } session = requests.Session() try: response = session.get(url, headers=headers, verify=False) filename = response.headers['Content-Disposition'].split('"')[-2] with open(filename, 'wb') as f: f.write(response.content) fileFullPath = os.path.abspath(filename) print(fileFullPath) except requests.exceptions.HTTPError as err: print("file download fail err {}".format(err.response.status_code)) -
Failed to create subscription: LinkedIn Developer API real-time notification error
I’m working on enabling real-time notifications from LinkedIn. I can successfully retrieve access tokens, but when I try to create a real-time notification subscription, the API returns the following error. Could someone please help me understand what might be causing this issue? Error Message { "message": "Failed to create subscription. RestException{_response=RestResponse[headers={Content-Length=13373, content-type=application/x-protobuf2; symbol-table="https://ltx1-app150250.prod.linkedin.com:3778/partner-entities-manager/resources|partner-entities-manager-war--60418946", x-restli-error-response=true, x-restli-protocol-version=2.0.0},cookies=[],status=400,entityLength=13373]}", "status": 400 } My code is below def linkedinCallBack(request): """Handle LinkedIn OAuth callback.""" code = request.GET.get('code') state = request.GET.get('state') if not code or not state: return handle_redirect(request, message_key='missing_params') try: error, state_data = parse_state_json(state) if error: return handle_redirect(request, message_key='missing_params') error, platform = get_social_platform(state_data['platform_id']) if error: return handle_redirect(request, message=error) redirect_uri = request.build_absolute_uri( reverse('social:linkedin_callback')) # Exchange code for access token token_url = 'https://www.linkedin.com/oauth/v2/accessToken' data = { 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': redirect_uri, 'client_id': os.environ.get('LINKEDIN_APP_ID'), 'client_secret': os.environ.get('LINKEDIN_APP_SECRET'), } headers = {'Content-Type': 'application/x-www-form-urlencoded'} response = requests.post(token_url, data=data, headers=headers) if response.status_code != 200: return handle_redirect(request, message_key='token_failed') token_data = response.json() access_token = token_data.get('access_token', None) refresh_token = token_data.get('refresh_token', None) refresh_token_expires_in = token_data.get( 'refresh_token_expires_in', None) expires_in = token_data.get('expires_in', 3600) if not access_token: return handle_redirect(request, message_key='token_failed') LINKEDIN_API_VERSION = os.environ.get('LINKEDIN_API_VERSION') org_url = "https://api.linkedin.com/v2/organizationalEntityAcls" params = { 'q': 'roleAssignee', 'role': 'ADMINISTRATOR', 'state': 'APPROVED', 'projection': '(elements*(*,organizationalTarget~(id,localizedName)))' } headers = { 'Authorization': f'Bearer {access_token}', 'X-Restli-Protocol-Version': '2.0.0', 'LinkedIn-Version': LINKEDIN_API_VERSION } …