Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem in importing model files from same module
Below is the pic of my Django Project structure. Django Structure I am trying to import model in data_models folder but it saying no module found. I have attached the pic for reference. Please guide me. Error Image I have tried many thing like removing it from main directory but still not working fine. -
django admin. So that in "select" there is a selection from certain records using the appropriate additional key
help to make sure that in "specsAdmin" in the line "Characteristic:" only those options (after selecting the product) that have the same category id as the product are displayed problem here is such a code in model.py class specs(models.Model): """ Характеристика к товару """ tovar = models.ForeignKey(Tovars, on_delete=models.CASCADE) gl_category = models.CharField("Категория xарактеристики", max_length=50, null=True) category = models.ForeignKey("detail", verbose_name="Характеристика", on_delete=models.CASCADE) description = models.TextField("Значение") def clean(self, *args, **kwargs): if self.tovar == self.category: return super().clean(*args, **kwargs) raise ValidationError('товар и характеристика к товару должны совпадать') class Meta: verbose_name = "Характеристика к товару" verbose_name_plural = "Характеристики к товару" def __str__(self): return self.tovar def get_absolute_url(self): return reverse("specs_detail", kwargs={"pk": self.pk}) class detail(models.Model): """ Описание характеритики """ category = models.CharField("Характеристика", max_length=50) сategory_tovar = models.ForeignKey(Category, verbose_name="Категория", on_delete=models.CASCADE) details = models.TextField("Описание характерискики", null=True, blank=True) class Meta: verbose_name = "Описание характеритики" verbose_name_plural = "Описание характеритики" def __str__(self): return self.category def get_absolute_url(self): return reverse("detail_detail", kwargs={"pk": self.pk}) and such in admin.py @admin.register(specs) class specsAdmin(admin.ModelAdmin): """ Характеристика к товару """ list_display = ('tovar', 'gl_category', 'category', 'description') search_fields = ('tovar', 'name') @admin.register(detail) class detailAdmin(admin.ModelAdmin): """ Описание характеритики """ list_display = ('category', 'details', 'сategory_tovar') search_fields = ('category',) this is the detailAdmin detailAdmin detailAdmin this is the specsAdmin specsAdmin -
How do I pass Bing Web Search API Data from Django to display in React
I've got it where I can print the data from my search result in a Django folder called api.py using Python. But now, how do I move this data into react to display it? Could anyone help give me a detailed way to do this. Much Thanks in advance! I also have the Bing API key stored in a .env file currently in the same file level as the api.py file. Bing Web Search API: https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/reference/endpoints code: in api.py file `from pprint import pprint import requests from decouple import config subscription_key = config('subscription_key', default='') search_url = "https://api.bing.microsoft.com/v7.0/search" search_term = 'iphone 13' headers = {"Ocp-Apim-Subscription-Key": subscription_key} params = {"q": search_term, "textDecorations": True, "textFormat": "HTML"} response = requests.get(search_url, headers=headers, params=params) response.raise_for_status() search_results = response.json() pages = search_results\['webPages'\] results = pages\['value'\] pprint(results\[0\])` This is the data I'm getting in the terminal: I've tried looking through stackoverflow and the whole internet, haven't found anyone really using this API.. -
how do i solve my problem for my coding bootcamp walkthrough project?
Hello i am a beginner when it comes to coding and i was wondering if anyone could help me with an issue im doing the django module 'i think therefore i blog' and i am pretty sure i followed the instructions exactly but it is not working how it is intended to. basically when i "enter python3 manage.py migrate" into the terminal i get this error ``` `Traceback (most recent call last): File "/workspaces/djangoblog/manage.py", line 22, in <module> main() File "/workspaces/djangoblog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/codeany/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/codeany/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/codeany/.local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/codeany/.local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/codeany/.local/lib/python3.9/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/home/codeany/.pyenv/versions/3.9.17/lib/python3.9/importlib/__init__.py", line 122, in import_module raise TypeError(msg.format(name)) TypeError: the 'package' argument is required to perform a relative import for '.herokuapp.com'` i was wondering what i did wrong and how to fix it. here is my repository "https://github.com/benbarker04/djangoblog" any help would be appreciated -
Apache2 Too Many Redirects in HTTPS Rewrite Virtual Host
I keep getting too many redirects on one of my virtual hosts, but not the other. I'm sure there is some very small error I made I just don'r recognize. I've attached both Apache2 site configs below. I've tried several different versions of the rewrite conditions, and nothing has changed. I restart apache each time. The rewrite rules that make the most sense to me are these, which due to OR precedence should be (www.stage OR stage) AND HTTPS=OFF by my calculations. It appears the HTTPS check never occurs though? And I'm entirely confused why a direct copy of the working config doesn't work for this new site. RewriteCond %{SERVER_NAME} =www.stage.example.com [OR] RewriteCond %{SERVER_NAME} =stage.example.com RewriteCond %{HTTPS} off RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] I have several sites running in microk8s pods on the server with Apache2 and the virtual hosts pass the traffic to the appropriate port. The main difference between the two sites is one is written in PHP (working) and the new one is in DJango. But I have another site that is a working site in Django, so I doubt that is the issue. # example.com.config # Staging branch, unstable wip # Config also includes 2 other virtual … -
How to render a dictionary passed as Django Form Class parameter
I've got a template that renders two predefined forms depending on two different POST requests handled by a single view method to keep just one URL end point for the whole interaction. Form one doesn't take any parameters but form two does take an external API response a one. How can render the dictionary contents of that response as choice fields in form two class? view.py from django.shortcuts import render, HttpResponse from django.template import loader from .forms import QuestionForm, QuestionLevelForm from urllib import urlopen def process_question(request): if 'level' in request.POST: url = 'http://opentdb.com/api.php?amount=1&category=9&type="multiple"&level=' url += request.POST["level"] try: response = urlopen(url) except URLError as e: if hasattr(e, 'reason'): HttpResponse('Reaching server failed: ', e.reason) elif hasattr(e, 'code'): HttpResponse('Couldn\'t fufill request', e.code) else: question = response["results"][0] # API response passed to Form class instance as parameter form = QuestionForm(question) return render(request, "log/question.html", {"question": question, "form": form}) elif 'answer' in request.POST: return HttpResponse('NOT IMPLEMENTED: Check answer') else: form = QuestionLevelForm(); return render(request, "log/question.html", {"form": form}) forms.py from django import forms from django.forms import widgets class QuestionLevelForm(forms.Form): choices = (('', '---Please choose a level---'), ('easy', 'Easy'), ('medium', 'Medium'), ('hard', 'Hard')) label = forms.CharField(label="Choose your question level") select = forms.CharField(widget=forms.Select(choices=choices)) class QuestionForm(forms.Form): # Gets question dictionary … -
HTML Modals Intertwined on click action, should be separate
I have two modals on a single HTML template. When I implemented the second modal, the first one became tied to its actions and I want them to be separate. When I click the button to add time, I want the just the time form modal to show. When I click a user, I want some of their profile details shown on the right of the page. As of now, when I click the 'add time' button, they now stack together. Here is a picture of the issue: You can see that the front modal covers the form behind, I want these to be separate actions. When I click a button to add time, just this modal form should show: When I click on a user button, just this modal should show on the right hand page: Here are my button HTML: <button class="btn btn-danger add-btn mb-0" data-bs-toggle="modal" data-bs-target="#timetrackModal"><i class="ri-add-line align-bottom me-1"></i> Add Time Entry</button> <button type="button" class="btn py-0 fs-16 text-body" id="settingDropdown" data-bs-toggle="dropdown"> <i class="ri-stack-line"></i> </button> <a href="#userProfileCanvasExample{{tech.pk}}" class="avatar-group-item" data-bs-toggle="offcanvas" data-bs-trigger="hover" data-bs-target="#userProfileCanvasExample{{tech.pk}}" aria-controls="userProfileCanvasExample{{tech.pk}}" title={{tech.username}}> <div class="rounded-circle avatar-xs"> <div class="avatar-title rounded-circle bg-info"> {{tech.username|first}} </div> </div> </a> Here is the Modal HTML: <div class="modal fade zoomIn" id="timetrackModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog … -
TypeError: BaseMiddleware.__call__() missing 2 required positional arguments: 'receive' and 'send'
I am getting the above error for my custom middleware which i created also it's not revoking when i am trying to do so from GOVDairySync.exceptions import * from channels.middleware import BaseMiddleware from rest_framework.authtoken.models import Token from django.contrib.auth.models import AnonymousUser from channels.db import database_sync_to_async def get_user(token): try: token = Token.objects.get(key=token) return token.user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware(BaseMiddleware): async def _call_(self, scope, receive, send): headers = dict(scope['headers']) if b'authorization' in headers: token_name, token_key = headers[b'authorization'].decode().split() if token_name == 'Token': try: print(token_key) # Try to get the user using the token scope['user'] = await get_user(token=token_key) print(scope['user']) except BaseCustomException as e: # If an exception occurs, send an error response to the client response = { 'type': 'authentication.error', 'message': str(e), } await send({ 'type': 'websocket.close', 'code': 400, # Custom code for authentication error 'text': 'Authentication error', }) return await super()._call_(scope, receive, send) above code block is the custom middleware which i created, how can i solve the issue? i want to use ths middleware as below from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from chat_app import routing from channels.auth import AuthMiddlewareStack from .tokenauth_middleware import TokenAuthMiddleware # new application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( TokenAuthMiddleware(URLRouter(routing.websocket_urlpatterns)) … -
Django query doesn't return the instance that I just saved in database
I'm working on a project that requires to trace the events related to a process. In my case I have Registration and RegistrationEvent models with the latter connected throug a ForeignKey to Registration. I also have written a method of RegistrationEvent called _ensure_correct_flow_of_events which prevents from adding Events in an order that doesn't make sense and is called when model.save is called. Infact the flow of events must be SIGNED -> STARTED -> SUCCESS -> CERTIFICATE_ISSUED. At any moment the event CANCELED can happen. In order to evaluate event sequence this method calls another method _get_previous_event which return the last event registered to Registration. After a SUCCESS event is created, the save method calls Registration.threaded_issue_certificate which is a method that should create a certifcate and after that create a CERTIFICATE_ISSUED event in a new thread, in order to process the response fastly. Problem is when CERTIFICATE_ISSUED is about to be created _ensure_correct_flow_of_events and _get_previous_event are called and at this point _get_previous_event does not return the just created SUCCESS event but the previous STARTED event. My log is Checking correct flow, previous event: Course started - admin registration id: 1 current event_type: 3 Checking correct flow, previous event: Course started - … -
Django - Displaying Primary key in the HTML Modal form
I am new to Django, I want to display table data to Modal html form but it always shows the 1st record on Modal form. For e.g. in the image below, I have clicked on 43. TEST - 4, 43 is the primary key, I want to display the primary key in the Modal title, But the Modal title shows the primary key 41 which is 1st record. Here is the HTML code Waara List as of - {% now "jS F Y" %} Pending Waara's Waara already given {% for i in dictTask %} {{i.pk}} - {{i.firstname}} - {{i.lastname}} - {{i.phonenumber}} Mark as Done PRIMARY KEY {{i.pk}} × ... Close Save changes {% endfor %} </div> I was expecting correct Primary Key -
TypeError: Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001C1939EBE90>>
When I try add the product to wishlist it gives me above error, It still saves the object to model def plus_wishlist(reques): if request.method == "GET": prod_id = request.GET.get('prod_id') product = Product.objects.get(id=prod_id) ruser = request.user wishlist = Wishlist.objects.create(user=ruser, product=product) wishlist.save() return JsonResponse({'message': 'Added to Wishlist.'}) Also when i try to use ruser=request.user.id ValueError: Cannot assign "1": "Wishlist.user" must be a "User" instance. -
Custom Select Input With Search on the Frontend
See example here... Hello! The only thing i want to achieve here, is when you click (focus) on that input, automatically appears right below a "customized select popup" where apart from selecting an option, you can select a link and see the results quantity shown at the bottom of the select. Here is my example All i did was a select input with an input search to recreate this. but this is not as scallable as the other example. Im way more experienced with backend, thats why im having this type of issues with the front.... Im using in the frontend just HTML CSS and Vanilla JS. Backend with Django... Any suggestion? -
Python Django no such table: app_db
File "C:\python\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\python\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\python\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\python\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\python\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\python\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) File "C:\python\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\python\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\python\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: app_db I tried python manage.py migrate runserver makemigrations and migrate bu it diddnt work i just delete sqlite and this happened -
Can Django handling multiple id in one view?
In order to do exercises in Django 4.2 and Python, I am creating a project in Django so that users can consult and evaluate the books they read. Some books are already in the database in the "Book" table in the "library" app. My goal is for users to add these books to their user area, which would be saved in the "UserBook" table of the "readers" app so that they could later add notes, or classification. To implement this logic, the idea is for the user to search for a book, if it exists in the "Book" database of the "library" app, enter the book page and use the button "Add to my books" it is automatically added (its copied data) to the "Userbook" table in the "readers" app and is displayed on the book page in the user area. (https://i.stack.imgur.com/0kB1m.png) This is the table "Book" of the app "library" enter image description here This is the code for the url path('book/int:id/', views.single_book, name='single_book'), that have the form and the button "Add to my books". (https://i.stack.imgur.com/oTntg.png) This is the table "UserBook" of the app "readers" (https://i.stack.imgur.com/Wx9C4.png) This is the view for the page that presentes the book in the … -
I don't understand how c react integration works on django
I have a problem integrating the react project with django online (host server), but there are no problems with local servers, everything works fine on react I can upload it to netlify or vercel but I don't understand what to do with django need to upload my project to the internet for free like netlify, versal, etc Please help me I tried to upload the react project to django somehow, but the problem there is that the static path does not find html, maybe because the path is not correct there, or when I registered npm run build on the react, there was a static folder and somehow django addressed him, I don't understand -
Preventing Data Tampering in HTTPS Requests: Safeguarding User-Initiated Donations
Could a Man-in-the-Middle (MITM) attack compromise the integrity of user-initiated transactions over HTTPS? Specifically, if a user selects an amount to donate on a website, is it possible for a hacker to intercept and modify the donation amount?If yes, what strategies can be implemented to safeguard against unauthorized alterations and ensure the security of transactions conducted over HTTPS? note: I'm using django in development. -
I get the admin id but when im logged in as a user i still get admin id when i try to fetch the user id
i created a function in my views.py file which lets you see different dashboards according to the role of the email which is logging in now when im trying to fetch the id of user im getting the id of the user which was loggod on the server before what chnages should i be doing for this.I tried clearing the session during logout but it's still not working and the code is fetching me the id of previous logged in admin. def determine_role(request): user = request.user # Get the authenticated user object role = user.role # Access the role attribute # Now you can use the role to perform further actions if role == 'admin': # If the user is an admin, do something return render(request, 'loginapp/admin_dashboard.html') elif role == 'user': # If the user is a regular user, do something else return render(request, 'loginapp/user_dashboard.html') -
Trouble Connecting Django Application to PostgreSQL Database Running in Docker Container
I'm currently working on a Django project where I'm using a virtual environment (venv) to run Django locally on my machine (Windows). Additionally, I have a PostgreSQL database running in a Docker container. I'm encountering issues trying to establish a connection between my Django application and the PostgreSQL database. Whenever I attempt to run python manage.py makemigrations, I get the following error: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "host.docker.internal" (141.31.78.207), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? warnings.warn( No changes detected Here are the relevant portions of my Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'SilverSurfer', 'USER': 'postgres', 'PASSWORD': "root", 'HOST': "host.docker.internal", 'PORT': '5432', } } And here's my Docker Compose file: version: "3.9" services: db: image: postgres:15.0 environment: POSTGRES_DB: SilverSurfer POSTGRES_USER: postgres POSTGRES_PASSWORD: root ports: - "5432:5432" volumes: - ./db.sql:/docker-entrypoint-initdb.d/db.sql It's worth noting that my Docker container for the database is running: CONTAINER ID IMAGE COMMAND CREATED STATUS 528ad4e3232f postgres:15.0 "docker-entrypoint.s…" 37 minutes ago Up 37 minutes PORTS NAMES 0.0.0.0:5432->5432/tcp 02_db-db-1 I've tried connecting to the PostgreSQL database using psql, but I receive … -
How to add field with its data from one model to another one in Django?
Django already has a User model, which has a username field; I also have a Profile model. What I want to achieve is to send the username from the User model along with the fields of the Profile model, So that I can access the username from the Profile model itself , as to the frontend I'm returning an object of the Profile model MODELS User= get_user_model() class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() department= models.CharField(max_length=50,blank=True) degree= models.CharField(max_length=20,blank=True) year= models.CharField(max_length=20,blank=True) bio = models.TextField(blank=True) profileimg= models.TextField(default=DEFAULT_IMAGE_DATA) def __str__(self): return self.user.username SERIALIZER class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields=['id','user', 'id_user', 'department', 'degree', 'year', 'bio','profileimg'] class ChatMsgSerializer(serializers.ModelSerializer): reciever_profile= ProfileSerializer(read_only=True) sender_profile= ProfileSerializer(read_only=True) class Meta: model = ChatMsg fields=['id','user', 'sender','sender_profile', 'reciever','reciever_profile', 'msg', 'is_read', 'date'] One Solution I though Was to make another fetch request from the frontend and make one more endpoint that returns the username , but idts it would work well when i need both sender and reciever username -
How to reuse a model crated for crate too many model in Django?
I have model in models.py in my app Django : class Personnel(models.Model): id = models.AutoField(primary_key=True) card_number = models.BigIntegerField() name = models.TextField(db_collation='C') family = models.TextField(db_collation='C') height = models.TextField(db_collation='C', blank=True, null=True) weight = models.FloatField(blank=True, null=True) job_type = models.BigIntegerField(db_column='Job_Type', blank=True, null=True) age = models.FloatField(db_column='age', blank=True, null=True) Superviser_score = models.FloatField(db_column='Superviser_score', blank=True, null=True) QC_score = models.FloatField(db_column='QC_score', blank=True, null=True) def __str__(self)-> str: return f'{self.card_number} - {self.family} - {self.name}' class Meta: managed = False db_table = 'personnel' And in admin.py: @admin.register(Personnel) class MyPersonelAdmin(admin.ModelAdmin): list_display = ['card_number','name','family','center','job_type'] How can I reuse personenel model for create too many model ? I try below code in models.py for crate another model but I get error: class SuperviserModel(Personnel): id=Personnel.id card_number = Personnel.card_number name = Personnel.name family = Personnel.family center = Personnel.center distance = Personnel.distance job_type = Personnel.job_type overtime = Personnel.overtime class Meta: managed = False db_table = 'personnel' Error: column personnel.personnel_ptr_id does not exist -
'Expected a value of type List<dynamic> but got one type _JsonMap'
The code below is displays my List<dynamic> casting method, yet when I preview my code, the info displayed is that 'Expected a value of type List<dynamic> but got one type _JsonMap'. My data is being retrieved from a django rest framework into a json format. I run server whenever I start the flutter app. // ignore_for_file: dead_code, prefer_const_constructors, prefer_const_literals_to_create_immutables, deprecated_member_use, avoid_print, non_constant_identifier_names import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:async'; Future<List<Data>> fetchData() async { var url = Uri.parse('http://127.0.0.1:8000/api/?format=json'); final response = await http.get(url); if (response.statusCode == 200) { // final jSon = "[${response.body}]"; List jsonResponse = (json.decode(response.body) as List<dynamic>); return jsonResponse.map((data) => Data.fromJson(data)).toList(); } else { throw Exception('Unexpected error occured!'); } } class Data { final int ID; final String visitor_name; final String visit_date; final String time_in; final String time_out; final String department; final String visitee_name; final String address; final String phone; final String purpose_of_visit; Data({required this.ID, required this.visitor_name, required this.visit_date, required this.time_in, required this.time_out, required this.department, required this.visitee_name, required this.address, required this.phone, required this.purpose_of_visit}); factory Data.fromJson(Map<String, dynamic> json) { return Data( ID: json['ID'], visitor_name: json['visitor_name'], visit_date: json['visit_date'], time_in: json['time_in'], time_out: json['time_out'], department: json['department'], visitee_name: json['visitee_name'], address: json['address'], phone: json['phone'], purpose_of_visit: json['purpose_of_visit'], ); } } class ViewRecord extends … -
Django: update one table based on another
I have two tables Table1 and Table2 with the same field hash_str. from django.db import models class Table1: data = JSONField(...) hash_str = CharField(...) class Table2: name = CharField(...) parsed = DateTimeField(...) hash_str = CharField(...) is_updated = BooleanField(...) # ... Sometimes i need to update Table2 instances based on Table1 instances with the same hash. But i want to use Table2.objects.bulk_update(...) for it. Because there is too much instances to update them one by one like this: # ... for t2_obj in Table2.objects.filter(is_updated=False): t1_obj = Table1.objects.get(hash_str=t2_obj.hash_str) t2_obj.name = t1_obj.data["name"] t2_obj.parsed = t1_obj.data["parsed"] t2_obj.is_updated = True t2_obj.save() # ... How can i do it properly? -
How to get realtime stdout from a celery task?
I have a Django project in which i'm running some background tasks with celery, one of my goal is to show real-time stdout of the running task so that the user can see the progress. the issue is that i get the stdout of the process only when it is finished executing (all is dumped at once). Views.py def run_script(request, file_type, file_id): run_features.delay(arguments) return Tasks.py @shared_task def run_features(arguments): process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) channel_layer = get_channel_layer() while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: print(output) async_to_sync(channel_layer.group_send)( 'output_group', { 'type': 'send_output', 'output': output.strip() } ) process.wait() return process.returncode Celery INFO -------------- celery@ritik v5.3.1 (emerald-rush) --- ***** ----- -- ******* ---- Linux-6.5.0-25-generic-x86_64-with-glibc2.35 2024-03-21 09:30:54 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: Automation:0x7e2bb4073280 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery Expectation - I get the stdout, line by line, while the task is running. Actual result - I … -
Invalid block tag on line 2: 'endblock'. Did you forget to register or load this tag?
{% extends "base.html" %} {% block title %} Home {% endblock %} {% block content %} {% endblock %} Seems correct to me, but it's showing this error. -
Update only specific fields in a models.Model vDjango
I have model in models.py: class SuperviserModel(models.Model): name = models.TextField(db_collation='C') family = models.TextField(db_collation='C') score = models.FloatField(db_column='score ', blank=True, null=True) # def __str__(self)-> str: return f' - {self.family} - {self.name}' class Meta: managed = False db_table = 'personnel' And in admin.py: @admin.register(SuperviserModel) class MySuperviserModelAdmin(admin.ModelAdmin): list_display = ['name','family','score'] sortable_by = ['name','family'] search_fields=['name', 'family'] I want when superviser user edit personnel just update score field, And cant update name and family field. How can I do?