Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module of _ffi found when create superuser
Python manage.py createsuperuser in django project in virtuelenv, reporting error: No module of _ffi found. Error Image 1 Error image 2 I got some clue from google. for example update cffi and argon2, run python from different locations. But nothing works. Thanks in advance! -
How to sort object by number of orders that is obtained by `get_queryset` field
Here in code below I can get all the number of orders that are assigned to business. But here is the question, how can I edit this code so that I can sort users by which business that has most orders? class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='ordersauthor') profile = models.ForeignKey(User, on_delete=models.CASCADE,related_name='orderscheck') article = models.ForeignKey(Article, null=True, blank=True, on_delete=models.CASCADE,related_name='ordersarticle') timestamp = models.DateTimeField(auto_now_add=True) --------- class PublicUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all().order_by('#HIGHEST NUMBER OF ORDERS') serializer_class = UserSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] pagination_class = StandardResultsSetPagination def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .annotate( num_orders=Count( 'orderscheck', orders__timestamp__range=Q( orderscheck__timestamp__range=(date.today(), date.today() + timedelta(days=7)) ), ) ) ) ---------- class UserSerializer(serializers.ModelSerializer): orders = serializers.IntegerField(read_only=True, source='num_orders') -
hugchat is not remembering my name, integrated with django
def ChatBotCreateCookie(husername=husername, hsecret=hsecret): sign = Login(husername, hsecret) cookies = sign.login() cookie_path_dir = "./" sign.saveCookiesToDir(cookie_path_dir) return cookies def ChatBotVerifyCookie(husername=husername): if os.path.exists(f"{husername}.json"): cookie = f"{husername}.json" else: ChatBotCreateCookie() cookie = f"{husername}.json" return cookie def ChatBotLogin(): cookie = ChatBotVerifyCookie() chatbot = hugchat.ChatBot(cookie_path=cookie) return chatbot def LandingFunction(request): return render(request, 'index.html') def ChattingRequest(request): ChatRequestString = request.GET['ReqText'] ChatConn = ChatBotLogin() ChatResponse = ChatConn.chat(ChatRequestString) print("Request="+ChatRequestString+"\nResponse="+str(ChatResponse)) return HttpResponse(str(ChatResponse)) This is my view, i have logged in using cookie but maybe hugchat is not creating a session for my requests.(I have done it with core python using while and it worked fine, how can i do the same here) -
Django session - recently viewed not showing in html
im working on a project using django framework. Im having issues in showing on the html the recently viewed items where the user (logged in) clicked before. This is my index.html that shows the recently_viewed items <div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl"> <h2 class="mb-12 text-2xl text-center">Recently Viewed Items</h2> <div class="grid grid-cols-3 gap-3"> {% if recently_viewed_qs %} {% for item in recently_viewed_qs %} <div> <a href="{% url 'item:detail' item.id %}"> <div> <img src="{{ item.image.url }}" class="rounded-t-xl"> </div> <div class="p-6 bg-white rounded-b-xl"> <h2 class="text-2xl">{{ item.name }}</h2> </div> </a> </div> {% endfor %} {% else %} <p>No recently viewed items.</p> {% endif %} </div> </div> What im getting is the response NO recently viewed items, so i guess is not entering in the for loop This is my views.py (not all views but the fundamental ones to understand the problem) def items(request): query = request.GET.get('query', '') category_id = request.GET.get('category', 0) categories = Category.objects.all() items = Item.objects.filter() if category_id: items = items.filter(category_id=category_id) if query: items = items.filter(Q(name__icontains=query) | Q(description__icontains=query)) print(f'Session Data: {request.session.get("recently_viewed", [])}') return render(request, 'item/items.html', { 'items': items, 'query': query, 'categories': categories, 'category_id': int(category_id) }) def recently_viewed( request, pk ): print('Entered in the recently_viewed') if not "recently_viewed" in request.session: request.session["recently_viewed"] = [] request.session["recently_viewed"].append(pk) … -
How to add tokens to the Django rest framework?
in my case i create login api ,when user enter thier details at that time token not generating.so give me a solutions. in my case i create login api ,when user enter thier details at that time token not generating.so give me a solutions. I create token , in behalf generaing token any user can access api -
Nginx and Gunicorn Static files not being found in my docker-compose django project even if logs show '125 static files copied to '/app/static''
I have set up my nginx folder, DOckerfile, .env, docker-compose.yml and entrypoint.sh files, and everything is running okay and im able to see pages as it should be. But the only problem is I cant load staticfiles. The Gunicorn container logs are showing "Not Found" and the nginx container is showing failed (2: No such file or directory). These are my configuration files: docker-compose.yml version: '3' services: marathon_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8010:8000" nginx: build: ./nginx volumes: - static:/static ports: - "8012:80" depends_on: - marathon_gunicorn db: image: postgres:15 container_name: postgres_db restart: always environment: POSTGRES_DB: xxx POSTGRES_USER: xxx POSTGRES_PASSWORD: xxx volumes: - pg_data:/var/lib/postgresql/data volumes: static: pg_data:` entrypoint.sh #!/bin/sh # Apply database migrations python manage.py migrate --no-input # Collect static files python manage.py collectstatic --no-input # Start Gunicorn server gunicorn absamarathon.wsgi:application --bind 0.0.0.0:8000 # Django Dockerfile FROM python:3.8 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./absamarathon /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT [ "sh", "/entrypoint.sh" ]``` nginx/default.conf upstream django { server marathon_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } # location /media/ { # alias /app/media/; # … -
Wagtail rich text block better revision diffing
Its possible to override how Wagtail compare page changes? Now its converting html to flat text but I want a better view when diffing. This is how wagtail do the diffing between texts: class RichTextFieldComparison(TextFieldComparison): def htmldiff(self): return diff_text( text_from_html(self.val_a), text_from_html(self.val_b) ).to_html() register_comparison_class(RichTextField, comparison_class=RichTextFieldComparison) -
Removing django admin panel content
algorithm: pbkdf2_sha256 iterations: 216000 salt: 7WW1Fr****** hash: dqMnCG************************************** Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form. how can i remove this portion or hide this i couldn't get the solution from any where -
django.db.utils.OperationalError: (2005, "Unknown server host 'db' (11001)")
Im trying to create a superuser for my django app using python manage.py createsuperuser but i keep getting an error message. Im using docker for my app alongside a pipenv and a connection is established whenever i run docker compose up -d --build for both the app and the db. settings.py is also properly configured and uses the db service as the HOST. However this is the error im getting when im running python manage.py createsuperuser after running the previous command: PS C:\Users\nawar\Desktop\uni\Uni\Modules\UWE_Modules\Y3\DESD\CW2\mlaas-g7> python manage.py createsuperuser Traceback (most recent call last): File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\db\backends\base\base.py", line 263, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\db\backends\mysql\base.py", line 247, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\MySQLdb\__init__.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2005, "Unknown server host 'db' (11001)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\nawar\Desktop\uni\Uni\Modules\UWE_Modules\Y3\DESD\CW2\mlaas-g7\manage.py", line 22, in <module> main() File "C:\Users\nawar\Desktop\uni\Uni\Modules\UWE_Modules\Y3\DESD\CW2\mlaas-g7\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\core\management\__init__.py", line 440, in … -
how to remove super admin from dropdown if user is login
Please help me. I have to remove the super user from form showing in frontend. Means when I am creating todo and I also choosing user, so super admin is also display in dropdwn so I didn't try anything because i dont know how to do it and i am using built user model -
Django Autocomplete Light, forward widget is not working
I have the following code: forms.py from dal import autocomplete, forward class AnalysisForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Analysis fields = ['method', 'database'] method_type = forms.ChoiceField(choices=[('', ' -- select an option -- ', 'A', 'B')], required=True)) database = forms.ModelChoiceField(queryset=Database.objects.all(), required=True, widget=autocomplete.ModelSelect2(url='database-autocomplete', forward=("method_type", ), attrs={'data-placeholder': 'Database ...', 'data-minimum-input-length': 1., }, ) ) views.py class DatabaseAutocomplete(autocomplete.Select2QuerySetView): # url: database-autocomplete def get_queryset(self): qs = Database.objects.all() print(self.forwarded) script_type = self.forwarded.get('method_type') print("SCRIPT CHOICE") print(script_type) if script_type is None: qs = Database.objects.none() What this code is doing is is that the form takes a value for method_type and database (which uses autocomplete). I would like database to access the value of method_type when running the autocomplete function but it is not being sent (notice how I am printing self.forwarded, but it is always empty). I have also produced some variations on the above method for example: forward=(forward.Field("method_type"), ) which did not work. I also used: forward=(forward.Const(42, "b"), ) to try and send anything which also failed. Am I missing anything? I would appreciate some help. -
How to serve a Svelte app frontend build in Django backend static?
The svelte app is normal svelte (not kit) with some routing. Build by npm run build into: /dist: /assets/index.js, /assets/index.css, index.html. I tried to follow this tutorial for React and expect it to have the same results. When accessed the serving path, it returns error In the project folder: views.py `from django.shortcuts import render def index(request): return render(request, 'frontend/index.html')` `urls.py` `urlpatterns = [ # path("authors/", include("authors.urls")), path("admin/", admin.site.urls), path("", include("api.urls")), # path('static/', serve, {'document_root': settings.STATIC_ROOT, 'path': 'frontend/index.html'}), path('index/', views.index, name='index'), ]` `settings.py` `STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/frontend/assets')]` -
Disable add of related record in Django admin
I would like to customize a Django 5+ admin view page. The model looks like this class Person tutor = models.ForeignKey("Person", on_delete=models.SET_NULL, null=True, blank=True) and consequently the edit page for Person has a drop down box to select from a list of already added persons to the database, and add and delete buttons. Is there a way to remove (or disable) these add and delete buttons so that only Persons added before can be selected used? But I do not want to disable adding Persons in general, I just want that it cannot be done through this button. -
Trying to require password on django allauth social login with google workspace
The basic question is how to go about requiring a user to put in their password when using google SSO. We have a few users who use the same device and don't want them to all be able to log in as each other. If I could require a password after a unit of time that would be okay, but I think I have set in workspace to require login after 12 hours already. Otherwise logging in with google works fine. It's just requiring some kind of re-authentication periodically that we need. Here is the basic setup on django SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } Have tried updating the login link to use action-reauthenticate {% provider_login_url 'google' action="reauthenticate" %} This forces the user to select their account but doesn't require a password. -
'ProgrammingError: column does not exist' in Django
I've been moving development of my website over to using Docker. I replaced sqlite as my database with postgresql then ran the command docker-compose exec web python manage.py migrate in my Docker environment. I also updated MEDIA ROOT and MEDIA settings in my settings.py file and updated mysite/urls.py. When I go to 127.0.0.1:8000/admin to the look at stored/uploaded files I get an error: Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (column human_requirementschat.alias does not exist LINE 1: SELECT "human_requirementschat"."id", "human_requirementscha... ^ ) was the direct cause of the following exception: File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/options.py", line 2065, in changelist_view "selection_note": _("0 of %(cnt)s … -
Django form.is_valid() is incorrectly returning false for a missing field
When I submit a form to update a task in my project, the is_valid function returns false, and on the page it says: Error! Please correct the following errors: Description: This field is required. But when I print the POST request into the console, the description field isn't required, and it does have data. this is the views.py function: def task_edit(request, task_id, slug): """ Display an individual task for editing. """ # Retrieve the task instance task = get_object_or_404(Task, pk=task_id) # Retrieve the job instance job = get_object_or_404(Job, slug=slug) if request.method == "POST": # Print out the request.POST dictionary to inspect the data print(request.POST) # Initialize form with task instance and data from request add_task_form = AddTaskForm(data=request.POST, instance=task) if add_task_form.is_valid(): # Save the form data to the task instance task = add_task_form.save(commit=False) task.job = job task.save() messages.success(request, 'Task Updated!') return HttpResponseRedirect(reverse('job_detail', args=[slug])) else: messages.error(request, 'Error updating task!') else: # Initialize form with task instance add_task_form = AddTaskForm(instance=task) and this is the JS function: // Handle click event for edit button $(".edit-button").on("click", function() { console.log("Edit Task button clicked"); var taskId = $(this).data("task_id"); var description = $(this).data("description"); var tradesRequired = $(this).data("trades-required"); var tradesmanAssigned = $(this).data("tradesman-assigned"); var timeRequired = $(this).data("time-required"); var isCompleted = … -
Django querying tables without id - Multi-Database
In this example I have created (https://github.com/axilaris/docker-django-react-celery-redis/), I have implemented multi-database accessing a Postgresdb table that does not have "id" column. (you can find out in the project code /backend/simple/models.py Referring to my gist (https://gist.github.com/axilaris/123516cdc9023dc02ebac3cba6644dd7), when accessing the model, it prints the error: django.db.utils.ProgrammingError: column simpletable.id does not exist LINE 1: SELECT "simpletable"."id", "simpletable"."name", "simpletabl... here is the definition of the table: Is there a way to handle this table in Django (as I'm interested to use ORM) without creating a new column id or views. Can I do something within Django to support this table ? -
Django get all users with last_login older than 360 days
I'm trying the below code ... from datetime import datetime, timedelta from django.utils import timezone yearago = timezone.make_aware(datetime.today() - timedelta(days=366)) old_users = User.objects.filter(last_login__gt=yearago) old_users.all The output show users that have logged in this year, whereas I want users who's last login was over 366 days ago. So what am I missing? -
render_to_string can't access to a context correctly
I want to use weasyprint to transform a html template to PDF. I'm using Django 5.0. Here is a part of my template (The template works fine, Django renders it correctly): <div> <h1>Tu Pedido está listo, {{request.user.username}}!</h1> </div> <h4>Pedido ID: {{pedido}}</h3> <div class="container text-center" > <table class="table"> <thead class="thead-dark"> <tr> <th>Producto</th> <th>Cantidad</th> <th>Precio</th> </tr> </thead> <tbody> {% for key, producto in carro.items %} <tr> <td> {{producto.nombre}} </td> <td> {{producto.cantidad}} </td> <td> $: {{producto.precio}} </td> </tr> {% endfor %} <tr> <td colspan="3">Total: $: {{total}}</td> </tr> </tbody> </table> </div> <div class="container text-center"> <a href="{% url 'home' %}" class="btn btn-outline-primary me-2">Volver</a> <!--pdf--> <form id="pdf_form" method="post" action="{% url 'generar_pdf' %}" style="display: none;"> {% csrf_token %} <input type="hidden" name="pedido" value="{{ pedido }}"> <input type="hidden" name="carro" value="{{ carro }}"> <input type="hidden" name="total" value="{{ total }}"> </form> <button id="pdf_button" class="btn btn-primary" type="submit">Descargar pdf</button> </div> <!-- send form --> <script> document.getElementById("pdf_button").addEventListener("click", function() { document.getElementById("pdf_form").submit(); }); </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> And here is my views.py: def generar_pdf(request): if request.method == "POST": pedido = request.POST.get("pedido") carro_info = request.POST.get("carro") total_compra = request.POST.get("total") # if I print these 3 variables, the values are ok #--- here is the problem ---# html_string = render_to_string( template_name='exito.html', context={"pedido": pedido, "carro":carro_info, "total": total_compra}, request=request) #------# … -
redirect to the django project
good afternoon, there was a problem when creating the project. the situation is as follows, the built-in view logout does not work correctly. when I log out of the project on the site page on behalf of the user, I will be redirected to http://127.0.0.1:8000/users/logout /. moreover, everything is working properly in another project. below are the variables from the settings file, urls and the button template: urls.py from django.contrib.auth.views import LoginView, LogoutView from django.urls import path from users.apps import UsersConfig from users.views import RegisterView, ProfileView app_name = UsersConfig.name urlpatterns = [ path('', LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', LogoutView.as_view(next_page='users:login'), name='logout'), path('register/', RegisterView.as_view(), name='register'), path('profile/', ProfileView.as_view(), name='profile'), ] settings.py AUTH_USER_MODEL = 'users.User' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' template <div class="col-sm-4 offset-md-1 py-4"> <h4 class="text-white">Меню</h4> <ul class="list-unstyled"> <li><a href="{% url 'catalog:home' %}" class="text-white">Главная</a></li> <li><a href="{% url 'catalog:contact' %}" class="text-white">Контакты</a></li> <li><a href="{% url 'blog:blog' %}" class="text-white">Блог</a></li> {% if user.is_authenticated %} <li><a href="{% url 'users:logout' %}" class="text-white">Выйти</a></li> <li><a href="{% url 'users:profile' %}" class="text-white">Профиль</a></li> {% else %} <li><a href="{% url 'users:login' %}" class="text-white">Войти</a></li> <li><a href="{% url 'users:register' %}" class="text-white">Регистрация</a></li> {% endif %} </ul> </div> redirect to the main page -
Django Real time chart when database was updated by MQTT
my Django server receive data from device over MQTT sucessfully. def on_message(mqtt_client, userdata, msg): from lorawan_api.server_processing import SERVER_PROCESSING print(f'Received message on topic: {msg.topic}') # with payload: {msg.payload}') data_processing = SERVER_PROCESSING() data_processing.data_stored(msg.topic,msg.payload) Now i want to display them in real time chart. I found some solution using AsyncWebsocketConsumer. Is that the best way to display real time chart -
Django template, Need 2 values to unpack in for loop; got 1
Been facing issues regarding the error above. I am trying to highlight words based on an ID given by the dictionary in Django <td class="text-center"> {% with background_color=None %} {% for key, value in row.Context.items %} {% if not background_color %} {% for pattern, color in pos_color_map.items %} {% if pattern in value|default:''|lower %} {% with background_color=color %} {% endwith %} {% endif %} {% endfor %} {% endif %} {% endfor %} <span style="background-color: {{ background_color }}"> {{ key }} </span>{% if not forloop.last %}, {% endif %} {% endwith %} </td> -
Why is my Celery configuration not taking effect?
I'm running a Django app with Celery 5.3.4. I'm using Redis as the broker. I want to configure the task_time_limit and task_time_soft_limit options, but I can't get them to take effect when running locally. I've tried setting them very low, and running a slow task that sleeps for 10 seconds: app.conf.task_time_limit = 5 app.conf.task_soft_time_limit = 1 But, when running the Celery worker locally, it completes the slow task and doesn't time out: 2024-03-05T15:46:04.647630Z [info ] Task slow_task[97f51f79-ac48-4aa3-9098-a3ec5a299adc] received [celery.worker.strategy] 2024-03-05T15:46:14.741217Z [info ] Task slow_task[97f51f79-ac48-4aa3-9098-a3ec5a299adc] succeeded in 10.093100208323449s: None [celery.app.trace] I've tried configuring Celery in many different ways. Here's my current config, spread out over 2 files: celery.py: import os from celery import Celery from celery.signals import worker_init from django.conf import settings # Set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kosa_api.settings") app = Celery("kosa_api") # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django apps. app.autodiscover_tasks() app.conf.task_time_limit = 5 app.conf.task_soft_time_limit = 1 settings/celery.py (this is imported in my app's settings): from kosa_api.settings.utils import get_safe_redis_url … -
How to create new database table looping through another model in Django
I have a Thermocouple model and I want to create a different model to record Temperatures for each Thermocouple created and save it to database. for thermocouple | Id | name | | 1 | thermocouple_1 | | 2 | thermocouple_2 | | 3 | thermocouple_3 | then TemperatureRecord should be as | id | date | time | user | thermocouple_1 | thermocouple_2 | thermocouple_3 | | 1 | March 5, 2024 | 2:48 p.m. | 1 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | | 2 | March 5, 2024 | 2:52 p.m. | 2 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | | 3 | March 5, 2024 | 2:55 p.m. | 1 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | Thermocouple model class Thermocouple(models.Model): name = models.CharField(max_length=50, unique=True, help_text="Name of the thermocouple") def __str__(self): return f"{self.name}" class Meta: ordering = ['id'] @classmethod def bulk_create_from_import(cls, data): cls.objects.bulk_create([cls(**item) for item in data]) and i want to create a different database table model named TemperatureRecord consisting id,user,date,time and Thermocouple items. if created 10 thermocouple, need to be 10 column for each Thermocouple to record temperatures (IntegerField) I tried using the following code but didn't work. class TemperatureRecord(models.Model): date = models.DateField() time = … -
hello please help friends solve my problem
[[enter image description here](https://i.stack.imgur.com/3sQfS.png)](https://i.stack.imgur.com/YYUKG.png) tell me how to solve this problem I have already tried everything, nothing helped, if anyone knows how to solve this, I will be grateful for the day I can’t figure out how to fix this error wewewewewewewewewewewe