Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i used django on python 3.13?
am trying to install Django on Python 3.13 but am getting this problem (action) PS C:\Users\HP\desktop\AVP> python -m django --version Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\__main__.py", line 7, in <module> from django.core import management File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\management\__init__.py", line 19, in <module> from django.core.management.base import ( ...<4 lines>... ) File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\management\base.py", line 14, in <module> from django.core import checks File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\checks\__init__.py", line 18, in <module> import django.core.checks.caches # NOQA isort:skip ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\checks\caches.py", line 4, in <module> from django.core.cache import DEFAULT_CACHE_ALIAS, caches File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\core\cache\__init__.py", line 67, in <module> signals.request_finished.connect(close_caches) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\dispatch\dispatcher.py", line 87, in connect if settings.configured and settings.DEBUG: ^^^^^^^^^^^^^^ File "C:\Users\HP\desktop\AVP\action\Lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ val = getattr(_wrapped, name) ~~~~~~~^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'DEBUG' i tried uninstalling the existing Django the installing it again but all in vail -
How to store a `.shp` file to gisModel.GeometryField in model?
I have an example shp file and a model as follow class PolygonShape(models.Model): ... geometry = gisModel.GeometryField(null=False, srid=25832) ... def __str__(self): return self.name I want to upload the shp file and store it at GeometryField of the model. However, i dont know how to do it -
Polars Dataframe via Django Query
I am exploring a change from Pandas to Polar. I like what I see. Currently it is simple to get the data into Pandas. cf = Cashflow.objects.filter(acct=acct).values() df = pd.DataFrame(cf) So I figured it would be a simple change - but this will not work for me. df = pl.DataFrame(cf) What is the difference between using a Django query and putting the data inside Polars? Thank you. -
Django celery Revoke not terminating the task
i have a django celery on on my project and i have set everything and working well but i want to be able too terminate a tasks after it start processing.eg i backup my database through backend tasks and any time i can decide to cancel the tasks so it can terminate the process but when i use from project.celery import app res = app.control.terminate(task_id=task_id this is just returning None without teminating the task. the task still keep running. i have also use revoke which is still the same i am using this doc celery is there anyway to terminate it or i am missing so setting? -
Free hosting web site Django
Please any one know free web site for host deploy my Django small project with postgres db Naginex gunicorn Https domain My last use is digital Ocean but was 6 dollars for registration. Without visa you cant rigster Ok thanks for anyone share -
'charmap' codec can't encode characters in position 18-37: character maps to <undefined> error
I am trying to connect a ml model using django. In here I have loaded the model and necessary encoders. import joblib import os #from keras.model import load_model from keras.src.saving.saving_api import load_model from django.conf import settings import numpy as np def load_keras_model(): # Define the path to the model file model_path = os.path.join(settings.BASE_DIR, 'Ml_Models', 'football_prediction_model.h5') print("Keras model path:", model_path) try: # Load the model model1 = load_model(model_path) # Verify model loading by printing its summary print("Model successfully loaded.") print("Model Summary:") model1.summary() return model1 except Exception as e: # Handle exceptions and print error messages print(f"Error loading model: {str(e)}") return None def load_encoder(filename): encoder_path = os.path.join(settings.BASE_DIR, 'Ml_Models', filename) print(f"{filename} path:", encoder_path) # Debug path return joblib.load(encoder_path) # Load all necessary models and encoders model = load_keras_model() team_label_encoder = load_encoder('team_label_encoder.pkl') outcome_label_encoder = load_encoder('outcome_label_encoder.pkl') scaler = load_encoder('scaler.pkl') def predict_outcome(home_team, away_team, year, month, day, temperature): try: print(f"Home Team: {home_team}") print(f"Away Team: {away_team}") print(f"Year: {year}, Month: {month}, Day: {day}, Temperature: {temperature}") # Encode and scale the input data home_team_encoded = team_label_encoder.transform([home_team])[0] away_team_encoded = team_label_encoder.transform([away_team])[0] temperature_scaled = scaler.transform([[temperature]])[0][0] print(f"Encoded Home Team: {home_team_encoded}") print(f"Encoded Away Team: {away_team_encoded}") print(f"Scaled Temperature: {temperature_scaled}") # Prepare the input for the model input_data = np.array([[home_team_encoded, away_team_encoded, year, month, day, temperature_scaled]]) print(f"input date: … -
Email Verification tokens are not being properly verified
My code to verify users via their email after registering has a problem I can't pinpoint. Once successfully registered, a user receives an email with a link and a token attached. The token is then meant to be verified as valid, or flagged as invalid or expired. The emails are sent successfully. However, both expired and new tokens are also being flagged as invalid. What am I doing wrong? This is the user model in my models.py file: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = UserManager() def __str__(self): return self.email This is my serializers.py file: from rest_framework import serializers from .models import User class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=68, min_length=8, write_only=True) class Meta: model = User fields = ["email", "username", "password"] def validate(self, attrs): email = attrs.get("email", "") username = attrs.get("username", "") if not username.isalnum(): raise serializers.ValidationError( "The username should only contain alphanumeric characters" ) return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) class VerifyEmailSerializer(serializers.ModelSerializer): token = serializers.CharField(max_length=555) class Meta: model = User fields = ["token"] views.py import jwt from django.conf import settings … -
NoReverseMatch at /admin/ Reverse for 'app_list' with keyword arguments '{'app_label': 'admin_index'}' not found
i setup a custom admin page , where added link to page i want , the code worked fine until itried to utilize dajngo_admin_index leading to app_list not being detected , The project has only 1 app named myapp this my admin.py : # Customizing the Admin Interface class CustomAdminSite(admin.AdminSite): def get_urls(self): urls = super().get_urls() custom_urls = [ path('analytics/', self.admin_view(analytics_view), name='custom_analytics'), ] return custom_urls + urls custom_admin_site = CustomAdminSite(name='custom_admin') this my urls.py for admin : from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from myapp.admin import custom_admin_site urlpatterns = [ path('admin/', custom_admin_site.urls), # Register custom admin URLs path('', include('myapp.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this new admin template base_site.html : {% extends "admin/base.html" %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">SDM Administration</a></h1> {% endblock %} {% block user-tools %} <ul class="user-tools"> <li><a href="#">Test Link</a></li> <li><a href="{% url 'admin:password_change' %}">Change password</a></li> <li><a href="{% url 'logout' %}">Log out</a></li> </ul> {% endblock %} {% block nav-global %} <ul class="nav-global"> <li> <a href="{% url 'admin:custom_analytics' %}" class="reports-link">Reports and Analytics</a> </li> </ul> <style> /* Styling for nav-global and reports-link */ .nav-global { display: inline-block; margin-left: 30px; margin-top: 10px; /* Move the button down by 3px … -
How to do multiple users models authentication in django using jwt tokens?
I need a way to authenticate both models of my system with jwt tokens. One of the models is the User model, django built-in, and another is the a Ong model, which has a one-to-one relationship with User. My first approach is a endpoint which verify if the user passed has a ONG linked to it, if yes, return True, otherwise, return False, but im not sure if its secure or something "good" to do. I tried this way because i have no idea of how do this using JWT tokens for both models. My ong model: class ONG(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ong_name = models.CharField(max_length=40) custom_url = models.CharField(max_length=20, default=str(ong_name).replace(' ', ''), blank=True) ong_address = models.CharField(max_length=200, validators=[validate_address]) ong_cnpj = models.CharField(blank=True, validators=[validate_cnpj]) ong_phone_number = models.CharField(max_length=12) ong_email = models.CharField(validators=[EmailValidator]) class Meta: permissions = [("pet_creation", "can create pets")] def __str__(self): return f'ONG: {self.ong_name}' serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "username", "password"] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class ONGSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) class Meta: model = ONG fields = ['user', 'ong_name', 'custom_url', 'ong_address', 'ong_cnpj', 'ong_phone_number', 'ong_email'] def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(username=user_data['username'], password=user_data['password']) ong = ONG.objects.create(user=user, ong_name = … -
How to Configure django-admin-tools for Multiple Admin Sites Without Affecting the Default Admin
I'm using django-admin-tools in my Django project to create a dashboard-like custom admin site. I've successfully set up django-admin-tools following the official documentation. My goal is to create a custom admin site and configure django-admin-tools to work exclusively for this site, without affecting the default Django admin site. Below is a simplified version of my code: # Custom Admin Site class AdminSiteDashboard(AdminSite): site_header = 'Dashboard' site_title = 'Dashboard Portal' index_title = 'Welcome to My Dashboard' admin_site_dashboard = AdminSiteDashboard(name='admin_dashboard') # url patterns urlpatterns = [ path('admin_tools/', include('admin_tools.urls')), path('admin/', admin.site.urls), path('dashboard/', admin_site_dashboard.urls), ... ] # settings ADMIN_TOOLS_MENU = { 'base.admin_site.admin_site_dashboard': 'base.admin_tools.base_admin_menu.CustomMenu', } ADMIN_TOOLS_INDEX_DASHBOARD = { 'base.admin_site.admin_site_dashboard': 'base.admin_tools.base_admin_dashboard.CustomIndexDashboard', } ADMIN_TOOLS_APP_INDEX_DASHBOARD = { 'base.admin_site.admin_site_dashboard': 'base.admin_tools.base_admin_dashboard.CustomAppIndexDashboard', } I expected that by configuring django-admin-tools only for admin_site_dashboard, the default admin site would remain unaffected. However, after setting it up as shown above, I can access the dashboard at dashboard/, but I encounter an error when trying to access the default admin site at admin/. The error is: ValueError at /admin/ Dashboard menu matching "{'base.admin_site.admin_site_dashboard': 'base.admin_tools.base_admin_menu.CustomMenu'}" not found,{% if user.is_active and user.is_staff and not is_popup %}{% admin_tools_render_menu_css %}{% endif %} Is there a way to configure django-admin-tools so that it only applies to the custom admin site … -
Can't able to get the id of the model instance in django when i connect the project to MongoDB
I am doing the simple CRUD in djnago project ,first i was working with sqlite that is by default in djnago ,every thing was working properly,but when i configure it with MongoDB ,now create and read operations are working properly ,but for update and delete ,i can't able to get the id of the instance to send it to url with request, getting the error ,, ValueError at /employe/update/None when i try this '<form action="{% url 'update' i.id %}" method="POST">' and when i try to use <form action="{% url 'update' i._id %}" method="POST"Field 'id' expected a number but got 'None'.> _id as it is identifier in mongoDB ,then the syntax arrive comes that attribute can't start with '_',, ValueError at /employe/update/None when i try this '<form action="{% url 'update' i.id %}" method="POST">' and when i try to use <form action="{% url 'update' i._id %}" method="POST"Field 'id' expected a number but got 'None'.> _id as it is identifier in mongoDB ,then the syntax arrive comes that attribute can't start with '_',, -
How to export to Excel Django object where every ForeignKey object a new column with import-export lib?
I have a model represents some item on stock: (Code has been simplified) class StockItem(models.Model): name = models.CharField() category = models.Charfield() stock = models.ForeignKey(Stock) # <- Here is few stocks quantity = models.IntegerField(default=0) So every StockItem may exist on different stocks but with different q-ty remained. Is there a way to create ModelResource to export quantity remained for every stock? Table example: +----+--------+----------+---------+---------+ | ID | Name | Category | Stock A | Stock B | +----+--------+----------+---------+---------+ | 1 | Item 1 | Cat 1 | 1 | 1 | | 2 | Item 2 | Cat 2 | 10 | 8 | | 3 | Item 3 | Cat 3 | 14 | 32 | +----+--------+----------+---------+---------+ My ModelResource: class StockItemsRemainingsResource(resources.ModelResource): class Meta: model = models.StockItem fields = ('name', 'category') def __init__(self): super().__init__() for item in self.get_queryset(): stock_name = item.stock.name self.fields[f"quantity_{stock_name}"] = fields.Field( attribute="quantity", column_name=stock_name, widget=widgets.ForeignKeyWidget( models.Stock, "pk" ) ) I was trying to override the __init__ method but probably did it wrong. -
How to Display an Image in a Django Form Instead of Showing Its URL
I have a Django application where I want to display the current image in a form when editing an existing product. Currently, It's showing the image URL in the form, but I would like to display the actual image itself instead of URL. If that is not possible then remove that currently URL. I tried by my self but didn't worked -
In Django rest-framework , is it possible to bundle original callback like def copy?
I have a Django framework bundle it works for model. For example, class DrawingViewSet(viewsets.ModelViewSet) def list(self, request): def destroy(self, request, *args, **kwargs): def update(self,request,*args,**kwargs): And each function is called by POST DELETE PATCH GET For example: /api/drawing/13 Then now I want to make the function named copy, such as by calling: /api/drawing/copy/13 Then, with this query: class DrawingViewSet(viewsets.ModelViewSet) def copy(self, request, *args, **kwargs): // do some action. Is it possible to set the original call back on viewsets.ModelViewSet? -
Problem with Django and Python (the current path api/ did not match of these)
I am trying to setup a school journal based on Django and Python, but I can't do it because of a 404 page with problem in title. Python part is backend and Node + Yarn + HTML is consumer (client) part. my views.py from itertools import chain from rest_framework import viewsets, mixins from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from core.models import ( StudyYear, Subject, Mark, StudentClass, Student, School, ) from journal import serializers class BaseJournalAttrViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin,): """Base viewset for journal attributes""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) class StudyYearViewSet(BaseJournalAttrViewSet): """Manage study year in the database""" queryset = StudyYear.objects.all() serializer_class = serializers.StudyYearSerializer class SubjectViewSet(BaseJournalAttrViewSet): """Manage subjects in the database""" queryset = Subject.objects.all() serializer_class = serializers.SubjectSerializer class MarkViewSet(BaseJournalAttrViewSet, mixins.CreateModelMixin, mixins.UpdateModelMixin): """Manage marks in the database""" queryset = Mark.objects.all() serializer_class = serializers.MarkSerializer def get_queryset(self): """Retrieve all marks by student and subject""" queryset = self.queryset student = self.request.query_params.get('student') subject = self.request.query_params.get('subject') if student: queryset = queryset.filter(student__id=student) if subject: queryset = queryset.filter(subject__id=subject) return queryset class StudentClassViewSet(BaseJournalAttrViewSet): """Manage classes in the database""" queryset = StudentClass.objects.all() serializer_class = serializers.StudentClassSerializer class StudentViewSet(BaseJournalAttrViewSet): """Manage students in the database""" queryset = Student.objects.all() serializer_class = serializers.StudentSerializer def get_queryset(self): """Retrieve students for authenticated user by class""" student_class = self.request.query_params.get('student_class', … -
Tailwind-Django not working in Docker Container
I'm trying to deploy a django application on https://render.com/ using Docker. Unfortunately, the Tailwind classes don't work. In development, they work perfectly. Dockerfile: FROM python:3.12 # Set environment variables ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 # Set the working directory WORKDIR /app # Install Node.js and npm RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \ apt-get install -y nodejs # Install Poetry RUN pip install poetry # Copy pyproject.toml and poetry.lock COPY pyproject.toml poetry.lock /app/ # Configure Poetry to not use virtualenvs RUN poetry config virtualenvs.create false # Install Python dependencies RUN poetry install --no-dev # Copy the entire project COPY . /app/ # Install Tailwind CSS (requires Node.js and npm) RUN python manage.py tailwind install --no-input # Build Tailwind CSS RUN python manage.py tailwind build --no-input # Collect static files RUN python manage.py collectstatic --no-input # Expose port 8000 EXPOSE 8000 # Start the application with Gunicorn CMD ["gunicorn", "--bind", "0.0.0.0:8000", "config.wsgi:application"] I tried changing the order of the manage.py commands and clearing the cache. But that didn't help. -
How to count model objects in pytest-django?
While I'm perfectly able to get the objects count in python manage.py shell, somehow the test returns always 0. What am I missing? #myapp/test_.py import pytest from .models import Organization @pytest.mark.django_db def test_organization(): assert Organization.objects.count() == 10 $ pytest: E assert 0 == 10 E + where 0 = count() E + where count = <django.db.models.manager.Manager object at 0x734e379b0790>.count E + where <django.db.models.manager.Manager object at 0x734e379b0790> = Organization.objects -
Why is my youtube transcripts API only working in non-prod, but not in prod?
In my non-production environment, I am able to use the transcript youtube API to obtain transcript. In my production environment, after much debugging and logging, I am unable to do this. Here are the logs: 2024-08-20T07:41:29.989747260Z [ANONYMIZED_IP] - - [20/Aug/2024:07:41:29 +0000] "GET /generate/youtubeSummary/ HTTP/1.1" 200 30723 "https://[ANONYMIZED_DOMAIN]/dashboard/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0" 2024-08-20T07:41:45.777775814Z Custom form options: {} 2024-08-20T07:41:45.778110014Z Form data debug: {'grade_level': '', 'video_url': 'https://www.youtube.com/watch?v=[ANONYMIZED_VIDEO_ID]', 'summary_length': None} 2024-08-20T07:41:45.778131714Z INFO 2024-08-20 07:41:45,777 views Generating summary for video URL: https://www.youtube.com/watch?v=[ANONYMIZED_VIDEO_ID] 2024-08-20T07:41:45.781101714Z INFO 2024-08-20 07:41:45,780 views YouTube IP address: [ANONYMIZED_IP] 2024-08-20T07:41:45.979793308Z INFO 2024-08-20 07:41:45,979 views YouTube connection status: 200 2024-08-20T07:41:45.980433708Z INFO 2024-08-20 07:41:45,980 views Attempting to connect to: www.youtube.com 2024-08-20T07:41:45.980820208Z INFO 2024-08-20 07:41:45,980 views Extracted video ID: [ANONYMIZED_VIDEO_ID] 2024-08-20T07:41:46.463787194Z INFO 2024-08-20 07:41:46,463 _universal Request URL: 'https://[ANONYMIZED_DOMAIN]/v2.1/track' 2024-08-20T07:41:46.463807494Z Request method: 'POST' 2024-08-20T07:41:46.463815194Z Request headers: 2024-08-20T07:41:46.463822194Z 'Content-Type': 'application/json' 2024-08-20T07:41:46.463830194Z 'Content-Length': '2373' 2024-08-20T07:41:46.463840094Z 'Accept': 'application/json' 2024-08-20T07:41:46.463847194Z 'x-ms-client-request-id': '[ANONYMIZED_REQUEST_ID]' 2024-08-20T07:41:46.463853694Z 'User-Agent': 'azsdk-python-azuremonitorclient/unknown Python/3.9.19 (Linux-5.15.158.2-1.cm2-x86_64-with-glibc2.28)' 2024-08-20T07:41:46.463863894Z A body is sent with the request 2024-08-20T07:41:46.485539393Z INFO 2024-08-20 07:41:46,485 _universal Response status: 200 2024-08-20T07:41:46.485558093Z Response headers: 2024-08-20T07:41:46.485565793Z 'Transfer-Encoding': 'chunked' 2024-08-20T07:41:46.485600593Z 'Content-Type': 'application/json; charset=utf-8' 2024-08-20T07:41:46.485609693Z 'Server': 'Microsoft-HTTPAPI/2.0' 2024-08-20T07:41:46.485616293Z 'Strict-Transport-Security': 'REDACTED' 2024-08-20T07:41:46.485622793Z 'X-Content-Type-Options': 'REDACTED' 2024-08-20T07:41:46.485629293Z 'Date': 'Tue, 20 Aug 2024 07:41:45 GMT' 2024-08-20T07:41:46.486316593Z INFO 2024-08-20 07:41:46,485 _base Transmission … -
Is it necessary to specify the device type (Android or iOS) when sending push notifications from a Django server through Firebase in a Flutter app?
I am trying to send notifications and I am receiving on Android but on iOS I also uploaded the APNS key also on firebase, when send notifications there is success message on server and no error. I was expecting to find information on whether specifying the device type is necessary for proper notification delivery and if it impacts the notification payload. Specifically, I want to know if failing to specify the device type could result in notifications not being delivered correctly or if Firebase handles this automatically. -
Method GET not allowed [closed]
I am trying to use the second url with the get method and it gives me the error Method "GET" not allowed in Django app. urlpatterns = [ path('book/', include([ path("<str:user_uuid>/<str:image_uuid>", BookView.as_view({"post": "post"}, http_method_names=["post"]), name=ApiName.BOOK_POST.value), path("<str:user_uuid>/<str:book_uuid>", BookView.as_view({"get": "get"}, http_method_names=["get"]), name=ApiName.BOOK_GET.value), path("edit/<str:user_uuid>/<str:book_uuid>", BookView.as_view({"post": "edit"}, http_method_names=["post"]), name=ApiName.BOOK_EDIT.value), path("export/<str:user_uuid>/<str:book_uuid>", BookView.as_view({"post": "export"}, http_method_names=["post"]), name=ApiName.BOOK_EXPORT.value), path("/images/<str:user_uuid>/<str:folder_uuid>", BookView.as_view({"post": "post_images"}, http_method_names=["post"]), name=ApiName.BOOK_IMAGES_POST.value), path("<str:user_uuid>/<str:template_uuid>", BookView.as_view({"get": "get_template"}, http_method_names=["get"]), name=ApiName.BOOK_GET.value), ])), ] Below is my view class BookView(CustomViewSet): parser_classes = [JSONParser, DrfNestedParser] authentication_classes = [BaseApiAuthentication] # permission_classes = [IsAuthenticated, FilePermission] permission_classes = [IsAuthenticated] @method_decorator(logging()) def post(self, request, user_uuid:str, image_uuid:str): return api_response_success() @method_decorator(logging()) def get(self, request, user_uuid:str, book_uuid:str): return api_response_success() -
One to Many relationships in DJANGO - how to generate a row of uniqueness based on 2 compound keys
I am trying to create a relationship based on a compound key based on 2 fields for uniqueness. From my understanding Django uses foreign keys to define one to many relationships? This is my scenario: I have 2 tables Table1 Table2 I want to write code to generate rows for Table3 records which iterate through Table 2 and generate the list below and generate the compound key combination: I want to create this relationship using models.py, however, every time I save a record the ID in table 2 increments see example of Table 2 How can I force this behaviour? This is the code I have used Table1 is Parish i derive the value for parish.id Table2 is CheckList.object.all() Table3 is All_Inpection def form_valid(self, form): form.instance.author = self.request.user parish = form.save(commit=False) parish.user_id = self.request.user.id parish.save() entry = Company.objects.get(pk=parish.id) Checklists = Checklist.objects.all() for rec in Checklists: new_rec=All_Inspection(str_status=rec.str_status, str_comment='',company_id=entry) new_rec.save() return super().form_valid(form) -
Cannot Install Django-Q on Django 5
We have problem install Django-Q on DJango 5 when run python manage.py migrate it was error as message below pip install django-q INSTALLED_APPS = [ ... 'django_q', ] python manage.py migrate Q_CLUSTER = { 'name': 'Django Q', 'workers': 16, 'recycle': 500, 'timeout': 1200, 'compress': True, 'save_limit': 250, 'queue_limit': 1000, 'cpu_affinity': 1, 'label': 'Django Q', } Error message: File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django_q/apps.py", line 3, in <module> from django_q.conf import Conf File "/Users/imac/Desktop/Project/Test/myenv/lib/python3.12/site-packages/django_q/conf.py", line 8, in <module> import pkg_resources ModuleNotFoundError: No module named 'pkg_resources' How to Fix the issue ? -
Django Q (scheduler) is not properly working in python 3
Django Q (scheduler) is not properly working in python 3. it is alway stop one time a week but it is working fine on python 2. no error log found in python 3. How to fix that issue ? https://django-q.readthedocs.io/en/latest/ Q_CLUSTER = { 'name': 'Django Q', 'workers': 16, 'recycle': 500, 'timeout': 1200, 'compress': True, 'save_limit': 250, 'queue_limit': 1000, 'cpu_affinity': 1, 'label': 'Django Q', } getting the solution and track error log -
Input fields not displaying- Django inlineformsets
I am using an inline formset so the user can upload multiple images and also I can receive related information together e.g. the ingredient, quantity and unit. This was previously working but my input fields have disappeared- the titles still appear but I can't actually input the textfields so then the form won't save properly. Here is my forms.py class ImageForm(forms.ModelForm): class Meta: model = Image fields = '__all__' class VariantIngredientForm(forms.ModelForm): class Meta: model = VariantIngredient fields = '__all__' widgets = { 'ingredient': forms.TextInput( attrs={ 'class': 'form-control' } ), 'quantity': forms.NumberInput( attrs={ 'class': 'form-control' } ), 'unit': forms.MultipleChoiceField( choices = UNIT_CHOICES ), } This is my models.py class Image(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, null=True ) image = models.ImageField(blank=True, upload_to='images') def __str__(self): return self.recipe.title if self.recipe else "No Recipe" class VariantIngredient(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE ) ingredient = models.CharField(max_length=100) quantity = models.PositiveIntegerField(default=1) unit = models.CharField(max_length=10, choices=unit_choice, default='g') def __str__(self): return self.recipe.title if self.recipe else "No Recipe" This is the relevant section of my template: <!-- inline form for Images Start--> {% with named_formsets.images as formset %} {{ formset.management_form|crispy }} <script type="text/html" id="images-template"> // id="inlineformsetname-template" <tr id="images-__prefix__" class= hide_all> // id="inlineformsetname-__prefix__" {% for fields in formset.empty_form.hidden_fields %} {{ fields }} … -
CSRF Token doesn't work in production environment
My environment: Django backend deployed on Elastic Beanstalk behind a application load balancer that terminates ssl. The flow is: my website is served on S3 and cloudfront on domain: https://www.test.app.mydomain.com/. This sends request to backend which has domain: https://api.test.mydomain.com/. The request grabs the csrftoken in browser cookies and includes it in the headers. CSRF tokens work locally, but it doesn't work in my production environment. Most importantly, there is no csrftoken in the browser cookies in the production environment. These are my settings that are relevant: MIDDLEWARE = [ # keep on top 'corsheaders.middleware.CorsMiddleware', # rest of the 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", ] SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_COOKIE_AGE = 7200 # 2 hours SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['http://localhost:3000', 'https://www.test.app.mydomain.com', 'https://test.app.mydomain.com'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True CORS_ALLOWED_ORIGINS = ['http://localhost:3000', 'https://www.test.app.mydomain.com', 'https://test.app.mydomain.com'] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = list(default_headers) + [ 'Tab-ID', ]