Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unauthorized response to POST request in Django Rest Framework with Simple JWT
I am doing a project with REST API and Django Rest Framework. I currently have an issue in my post request where some of my endpoints return HTTP 401 Unauthorized, though all other get or update objects are returning correct responses. I am using -> djangorestframework-simplejwt==5.2.2. settings.py INSTALLED_APPS = [ # ... 'rest_framework_simplejwt.token_blacklist', # ... ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=50), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, "JSON_ENCODER": None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } main urls.py schema_view = get_schema_view( openapi.Info( title="Blog Backend API's", default_version="v1", description="This is the documentation for the backend API", terms_of_service="http://mywebsite.com/policies/", contact=openapi.Contact(email="sabab@gmail.com"), license=openapi.License(name="BDSM License"), ), public=True, permission_classes=(permissions.AllowAny, ) ) urlpatterns = [ path('admin/', admin.site.urls), path("api/v1/", include("api.urls")), path("", schema_view.with_ui('swagger', cache_timeout=0), name="schema-swagger-ui"), ] views.py class PostCommentApiView(APIView): @swagger_auto_schema( request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'post_id': openapi.Schema(type=openapi.TYPE_INTEGER), 'name': openapi.Schema(type=openapi.TYPE_STRING), 'email': openapi.Schema(type=openapi.TYPE_STRING), 'comment': openapi.Schema(type=openapi.TYPE_STRING), }, ), ) def post(self, request): post_id = request.data["post_id"] name = request.data["name"] email = request.data["email"] comment = request.data["comment"] post = api_models.Post.objects.get(id=post_id) api_models.Comment.objects.create( post=post, name=name, email=email, comment=comment, … -
Wagtailmenus does not seem to recognize the sub_menu tag in my install
First of all, all of these pages have the "Show in menu" item checked, and in my menu config, it has "Allow 3 levels of sub-navigation" selected. Apologies if I'm being short, but I lost this question the first time I tried to post it. The browser went into perpetual loading state. There is a tutorial in the first few pages of the wagtailmenus plug-in. I'm following that tutorial, which cuts off half-way through and instead turns into a tag reference manual. The docs are terrible due to that, and it's a little bit of divination studies based on bad writing. Based on the tutorial, however, I have in my config: ` INSTALLED_APPS = [ 'home', 'scripts', 'settings', 'triggers', 'tasks', 'schedules', ..... 'wagtailmenus', 'wagtail_modeladmin', # if Wagtail >=5.1; Don't repeat if it's there already ] ..... TEMPLATES = [ { .... "context_processors": [ .... 'wagtailmenus.context_processors.wagtailmenus', ], }, }, ]` I have this menu structure: -my dashboards (There are no sub-menus here.) -settings -Triggers -Scripts -Tasks -Schedules This is really just items created to get this displaying before I add additional items. I only want the sub-menus to display, but they won't do so. My templates are setup according to the … -
Django static url not seem to be loading css file
I'm actually new to Django and tried to load my theme into newly created project. I have a home.html template file placed at {APP_NAME}/templates/ directory of my Django project. The APP_NAME is called website here and projectname is dentist. Here is the structure top-level directory of project: dentist env (virtual environment) static website css templatemo_style.css images ... website templates home.html manage.py As you see the static files are placed in the static under the APP_NAME. Now here is the home.html: {% load static %} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>free template one - templatemo</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="{% static 'website/css/templatemo_style.css' %}" rel="stylesheet" type="text/css" /> </head> And this is settings.py added configuration: STATIC_URL = 'static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,'static') ] But now the problem is whenever I load the project, the css file is not being loaded and the html is corrupted! I check the source code and it shows this link: <link href="/static/website/css/templatemo_style.css" rel="stylesheet" type="text/css" /> However it is not found and the page comes up this way: -
I'm getting a 400 error and the endpoint isn't even entered. Why?
I've encountered a situation with my Django Rest Framework (DRF) app in which a client mobile app is calling one of my endpoints and is getting a 400 error, but I can't debug what's going wrong. This is what appears in the log: Sep 02 11:11:29 myapp heroku/router at=info method=POST path="/users/generate_otp/?device_token=cBB2x2Y2L04qpQCbYukR31%3AAPA91bEHqCZ3ztI9wim0EzxVZ1Nv6clZMfsDxw7_6reWIVkm5dQcxuWlifnfxkn7Ope_2wTM75_TMw6BV-pAZyEYdrICz1dsk2gX6_aYJwz0-H3SDR2vLWvceiioUs21dTwXQIMwmBN1&mobile=%2B13104014335&device_type=ios" host=myhost.com request_id=fad10208-c01d-4f64-9640-1aff889ab3ee fwd="66.246.86.216" dyno=web.1 connect=0ms service=1ms status=400 bytes=28 protocol=https If I send the same URL via Postman the endpoint returns successfully: Sep 02 11:41:48 myapp heroku/router at=info method=POST path="/users/generate_otp/?device_token=cKY2x2Y2L04qpQCbYukR31%3AAPA91bEHqCZ3ztI9wim0EzxVZ1Nv6clZMfsDxw7_6reWIVkm5dQcxuWlifnfxkn7Ope_2wTM75_TMw6BV-pAZyEYdrICz1dsk2gX6_aYJwz0-H3SDR2vLWvceiioUs21dTwXQIMwmBN1&mobile=%2B13104014335&device_type=ios" host=myhost.com request_id=4ddabe5f-619d-4665-aff5-28afb9ac277d fwd="66.246.86.216" dyno=web.1 connect=0ms service=572ms status=200 bytes=1686 protocol=https I've tried to examine the request that comes in, by making these the first lines of the endpoint: @action(detail=False, methods=["POST"]) def generate_otp(self, request): """ Text a one-time password to the given mobile number to login. If there's not yet a user with that number, register them. """ print("IN GENERATE OTP", flush=True) print("IN GENERATE OTP, request.data =", request.data, flush=True) print("IN GENERATE OTP, request.headers =", request.headers, flush=True) But those print statements never get called -- so it's as if it's not entering the endpoint at all. To try to debug what's being sent in the request further, I added this middleware: class RequestLoggingMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print("--- … -
i'm not able to delete a model object Field 'id' expected a number but got 'not found'
Models class User(AbstractUser, PermissionsMixin): WEBSITE_ROLLS = [ ("Owner","Owner"), ("Manager","Manager"), ("Operator","Operator"), ("Customer","Customer") ] username = models.CharField(max_length=150, null=True) email = models.EmailField(max_length=255, unique=True) phone = models.CharField(max_length=16, null=True, blank=True) img = models.ImageField(upload_to="images/profile",default="images/profile/default.jpg") roll = models.CharField(max_length=30, choices=WEBSITE_ROLLS, default='Customer') is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) joined_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Staffs(User): class Meta: proxy = True verbose_name = "Staff" verbose_name_plural = "Staffs" What i wrote in my CBV class StaffDeleteView(View): success_url = "accounts:profile_staff_add" model = Staffs def get(self, request, *args, **kwargs): staff_obj = self.model.objects.get(id=self.kwargs['pk']) staff_obj.delete() These are my models and i'm trying to delete a staff member, staff_obj fills with the specific data but it won't let me delete it. what am i doing wrong here? -
Django collectstatic Error: MissingFileError for a File That Exists with Correct Name and Path
I'm encountering a MissingFileError while running collectstatic in my Django project. The error message is as follows: Traceback (most recent call last): File "C:\Path\To\Project\manage.py", line 22, in <module> main() File "C:\Path\To\Project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 209, in handle collected = self.collect() File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 154, in collect raise processed whitenoise.storage.MissingFileError: The file 'background_image_nislex8.jpg' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x000002CCDD5DE500>. The CSS file 'styles.css' references a file which could not be found: background_image_nislex8.jpg Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. I'm getting this error despite having changed the name of the file to background_image_nislex.jpg and updating the reference in the styles.css file to the same name. How can I resolve this issue and ensure that collectstatic recognizes the updated file name? What I've Tried: Verified that the file background_image_nislex.jpg exists in the correct directory. Updated the reference in the styles.css file to match the new filename. Cleared the … -
How to get https working in DRF deployed to AWS Fargate + API GW?
I'm struggling to set up a Django Rest Framework app in AWS to use TLS. I have an API Gateway v2 proxying requests to an Application Load Balancer that reaches some ECS containers (ECS cluster created via Fargate). API GW is doing the TLS termination and the connection to the LB is in HTTP. The load balancer listens on a different port than 443. The flow/URLs are like this: https://api-gw.example.com:443 -> http://lb-internal.foo:1234 -> ecs_containers This mostly works, except from internal links that are misrepresented. For example, in the root of my DRF API the URLs returned are like http://api-gw.example.com:1234/foo instead of https://api-gw.example.com/foo. This link does not work: wrong protocol and wrong port, but correct URL. I do have SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") on my settings.py. How can I get this setup to work as expected? How to troubleshoot further? -
how to iterate through django-friendship provided template tag
I am using Django 5.1 and django-friendship library. django-friendship provides some built in template tags that work but not when I try and iterate over them. so {% friends request.user %} returns a list of friends by username. But I cant seem to get any of the template tags work work when I iterate through them. {% if request.user != profile.user %} {% if profile.user in friends_list %} <p>You are friends with {{ profile.user.username }}.</p> <a href="{% url 'remove_friend' to_user_id=profile.user.id %}">Remove Friend</a> {% else %} {% for friend_request in friend_requests %} {% if friend_request.from_user == profile.user %} <p>{{ profile.user.username }} has sent you a friend request. Check your <a href="{% url 'view_friend_requests' %}">friend requests</a>.</p> {% elif friend_request.to_user == profile.user %} <p>You have already sent a friend request to {{ profile.user.username }}.</p> {% endif %} {% empty %} <a href="{% url 'send_friend_request' to_user_id=profile.user.id %}">Send Friend Request</a> {% endfor %} {% endif %} {% else %} {# This is the current user's own profile #} <h3>Your Friends</h3> {% if friends_list %} <ul> {% for friend in friends_list %} <li>{{ friend }}</li> {% endfor %} </ul> {% else %} <p>You have no friends yet.</p> {% endif %} {% endif %} Here is a … -
How can I add multiple rows from a table to one row of an another table?
actually I've explained everything in the title. Let's say I have two tables, one of them stores specific car model names(e.g Audi s3, Ford edge etc). Another one stores tire brands. Each car model good with different tire brands and some cars good with multiple brands(e.g., s3 good with Yokohama, Bridgestone and Micheline), so I need to add these tire brands to just one row. How can I do that? Thanks for helps. Database that I use is the MySQL with the Django models. -
Django Application CSS Not Applying Correctly Despite 200 Status Code?
I am developing a web app using Django and am using external CSS in my layouts. The static files, such as images, are working properly, but the CSS and JS are not functioning correctly. When I checked the Chrome developer tools, the CSS file is loading with a 200 status code. I have tried various techniques to resolve the issue, but nothing seems to be working. I tried troubleshooting but none of them worked. -
How to Upload and Process a File in Django Admin
I am working on a Django project where I need to upload a file via the Django admin interface, process it using a specific class, and then store the processed data in different models based on the file's content. The key requirement is that the file itself should not be saved in the database or the file system after it is uploaded. Here’s a summary of what I need: Upload a file (KML format) via Django Admin: I want to create a file upload field in the admin that allows users to upload a KML file. 2.Process the file using a custom class: After the file is uploaded, it should be immediately processed by a class I’ve written (KmlLicense), which extracts geometrical data from the KML file. Store processed data in other models: The extracted data (points, lines, polygons) should be stored in different models (LicensePoint, LicenseLine, LicensePolygon), depending on the geometry. No need to save the uploaded file: I don’t want the uploaded KML file itself to be saved either in the database or in the media directory of my Django project. Questions: How can I set up the Django admin to upload a file, process it with my … -
Want to use COALESCE on related fields on django model
I have model structure as below. from django.db import models class Switch(models.Model): fqdn = models.CharField(unique=True) class Meta: db_table = 'Switch' class Colo(models.Model): name = models.CharField() class Meta: db_table = 'Colo' class Clstr(models.Model): colo = models.ForeignKey('Colo', db_column='colo', related_name='clstrs') name = models.CharField() class Meta: db_table = 'Clstr' class ESwtch(models.Model): switch = models.OneToOneField(Switch, db_column='switch', primary_key=True, related_name='e_swtch') clstr = models.ForeignKey('Clstr', db_column='Clstr', related_name="e_swtches") class Meta: db_table = 'ESwtch' class BSwtch(models.Model): switch = models.OneToOneField(Switch, db_column='switch', primary_key=True, related_name='b_swtch') clstr = models.ForeignKey('Clstr', db_column='clstr', related_name='b_swtches') class Meta: db_table = 'BSwtch' class VChas(models.Model): clstr = models.ForeignKey('Clstr', db_column='clstr', related_name='v_chas') vc_num = models.IntegerField() class Meta: db_table = 'VChas' class VSwtch(models.Model): switch = models.OneToOneField(Switch, db_column='switch', primary_key=True, related_name='v_swtch') v_chas = models.ForeignKey(VChas, db_column='v_chas', related_name='v_switches') role = models.CharField() class Meta: db_table = 'VSwtch' class CTrig(models.Model): switch = models.ForeignKey(Switch, db_column='switch', related_name='c_trig') config_trigger = models.CharField() class Meta: db_table = 'CTrig' I want to get the CTrig based on Colo.name. I ran raw query as below. SELECT `CTrig`.`switch`, `CTrig`.`config_trigger`, `Switch`.`fqdn` FROM `CTrig` LEFT OUTER JOIN `Switch` ON (`CTrig`.`switch` = `Switch`.`id`) LEFT OUTER JOIN `BSwtch` ON (`Switch`.`id` = `BSwtch`.`switch`) LEFT OUTER JOIN `ESwtch` ON (`Switch`.`id` = `ESwtch`.`switch`) LEFT OUTER JOIN `VSwtch` ON (`Switch`.`id` = `VSwtch`.`switch`) LEFT OUTER JOIN `VChas` ON (`VSwtch`.`v_chas` = `VChas`.`id`) LEFT OUTER JOIN `Cluster` ON (COALESCE(`BSwtch`.`clstr`, `VChas`.`clstr`, … -
Django and react webrtc remote isn't being added
I am making a chat app with django for backend and react for frontend. I use django channels. consumers.py def receive(self, text_data): text_data_json = json.loads(text_data) if 'message' in text_data_json: # Handle chat message message = text_data_json["message"] user = text_data_json["user"] print(message) # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat.message", "message": message, 'user': user} ) elif 'webrtc' in text_data_json: # Handle WebRTC signaling signal_data = text_data_json['webrtc'] user = text_data_json['user'] # Relay WebRTC signaling data to the group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type": "webrtc.signal", "webrtc": signal_data, "user": user } ) def chat_message(self, event): message = event["message"] user = event["user"] # Send message to WebSocket self.send(text_data=json.dumps({"message": message, 'user': user})) def webrtc_signal(self, event): signal_data = event["webrtc"] user = event["user"] # Send WebRTC signaling data to WebSocket self.send(text_data=json.dumps({ "webrtc": signal_data, "user": user })) **VideoChat.js ** const [socket, setSocket] = useState(null); const localAudioRef = useRef(null); const remoteAudioRef = useRef(null); const peerConnectionRef = useRef(null); const [localStream, setLocalStream] = useState(null); useEffect(() => { const initializeSocket = () => { const newSocket = new WebSocket(`ws://${window.location.host}/ws/chat/1/`); setSocket(newSocket); newSocket.onopen = () => { console.log('WebSocket connected'); }; newSocket.onmessage = async (event) => { const data = JSON.parse(event.data); console.log('Message received:', data); const messageType = data.webrtc?.type; if (messageType === 'offer') { await handleOffer(data.webrtc); } … -
reset_password function causing Internal Server Error
i work in django project and i have this function : def reset_password(request): if request.method == 'POST': email = request.POST['email'] try: # Check if the user exists user = RestPassword.objects.get(email=email) # Generate a unique reset token reset_token = str(uuid.uuid4()) user.reset_token = reset_token user.save() # Send the reset password email subject = 'Password Reset' message = f'Please click the following link to reset your password: {settings.SITE_URL}/authentication/reset/{reset_token}/' from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [email] send_mail(subject, message, from_email, recipient_list) success_message = 'A password reset link has been sent to your email.' return render(request, "authentication/login.html", {'success_message': success_message}) except RestPassword.DoesNotExist: error_message = 'No account found with the provided email.' return render(request, "authentication/reset_password.html", {'error_message': error_message}) return render(request, "authentication/reset_password.html")``` and this the HTML fil <!DOCTYPE html> <html lang="en"> <head> <title>Password Reset</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <style> body { background-color: #f8f9fa; } .container { max-width: 400px; margin: 100px auto; padding: 30px; border: 1px solid #ced4da; border-radius: 5px; background-color: #fff; } .btn-reset { width: 100%; } </style> </head> <body> <div class="container"> <h2>Password Reset</h2> <form id="resetPasswordForm" action="{% url 'reset_password' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" name="email" required> </div> <button type="submit" class="btn btn-primary btn-reset" onclick="return verificate_email()">Reset Password</button> </form> </div> <script> function verificate_email() { const email = … -
CSRF token not generated in django backend
I have a web application that I built using a Vuejs for the frontend and django for the backend. When I was developing the application, I did not have issues in regards to csrf token generation. I have only begin encountering this issue 2 months after development. I am not sure why this issue is happening, or what was the behaviour for setting the csrf token when I was developing it. As far as I understand, an initial get request to the backend sets the csrf token in the browser, and can then be used by all other subsequent requests. But I do not see any csrf cookie in the applications tab. I have this method for setting the csrf cookie in the backend: def get_csrf_token(request): return JsonResponse({"detail": "CSRF cookie set"}) and this is where I call the method in my frontend: onMounted( async()=>{ const response = await fetch('http://127.0.0.1:8000/get-csrf-token', { method: 'GET', credentials: 'include' // This ensures cookies are sent with the request }); console.log if (response.ok) { console.log("CSRF token set successfully."); } else { console.log("Failed to set CSRF token."); } }) this is my setting.py file if its needed: """ Django settings for api project. Generated by 'django-admin startproject' … -
Add pyproject.toml to Django apps that are part of a source tree
I have a Django application which consists of two Django 'apps' - the term used in the Django world for (potentially) reusable packages. My whole application lives in one git repository. I would like to use one of the apps in another Python application. Specifically, I want to use the Django ORM and need to use the models definied in that app. Currently I put the parent directory of the app onto my sys.path and it works fine. But I would like to be able to pip install that app. My directory layout looks like this: website/ website/ <- main Django app settings.py urls.py ... crawls/ <- app I want to share views.py urls.py pyproject.toml <- this is new ... other_app/ <- application where I want to use `crawls` What I tried now is to place a pyproject.toml into crawls. However, both hatchling and flit seem to insist on an additional subdirectory. For example, the following results in ValueError: No file/folder found for module gen_crawler_crawls: [build-system] requires = ["flit_core >=3.2,<4"] build-backend = "flit_core.buildapi" [project] name = "gen-crawler-crawls" dependencies = [ "Django>=5.0.6", ] requires-python = ">=3.12" authors = [ {name = "Homer Simpson", email = "homer.simpson@example.com"}, ] dynamic = ["version", "description"] … -
Godaddy Professional Mail Connecting with django to send mails through django api
Im trying to send emails through my django api by connecting the Godady Professional email This is my settings.py config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'Password' EMAIL_PORT = 587 Postman api it shows email sent sucessfully but i didnt recieve any email utils.py from django.core.mail import EmailMessage from django.conf import settings from django.core.exceptions import ImproperlyConfigured class Util: @staticmethod def send_email(data): try: email = EmailMessage( subject=data['email_subject'], body=data['email_body'], to=[data['to_email']], from_email=settings.DEFAULT_FROM_EMAIL ) email.send(fail_silently=False) # logger.info(f"Email sent successfully to {data['to_email']}") except Exception as e: print(f"Failed to send email to : {e}") Views.py class SendEmailView(viewsets.ViewSet): def list(self, request): serialized_items = [] # Append serialized item data to the list serialized_items.append({ 'url': "", }) # Return the list of items as a JSON response # return Response(serialized_items) try: email_body = "Hello, This is a test email sent from our API." email_data = { 'email_body': email_body, 'to_email': "email@gmail.com", 'email_subject': 'Test Email from API' } # Send the email using the Util.send_email function Util.send_email(email_data) return Response({"message": "Email sent successfully!"}, status=status.HTTP_200_OK) except ObjectDoesNotExist: return Response({"error": "User with this email does not exist."}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) it shows the email sent sucessfully while i use the api through … -
How to annotate after group by and order_by in django?
I have a DB table which has a field "created_at". This is a auto_now_add=True field. This table is inserted data once everyday. What I want to do is filter data that corresponds to the last day of each month of each year. I have a query as follows: qs = ( self.model.objects().with_months() .with_years() .values('year', 'month') .annotate(last_day=Max('created_at')) .order_by('year', 'month') ) with_months() and with_years() methods are queryset methods that annotate year and month. What I want to do is to annotate other fields of this model in this queryset; however, since values() returns a list of dictionaries, I am not able to do that. I cannot add other fields inside values() as they won't be grouped. How can I achieve this? Best -
Remove products from the cart [closed]
The button to remove the product from the cart don`t work. when user add first product to the cart he can not remove that product from cart. But this problem is only for the product that was initially added to the cart I have no problem when I use the method GET, but when I use the method POST, this is the error my cart: Cart_Session_Id = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(Cart_Session_Id) if not cart: cart = self.session[Cart_Session_Id] = {} self.cart = cart def __iter__(self): cart = self.cart.copy() for item in cart.values(): product = Product.objects.get(id=int(item['id'])) item['product'] = product item['total'] = int(item['quantity']) * int(item['price']) item['unique_id'] = self.unique_id_generator(product.id, item['color'], item['size']) yield item def unique_id_generator(self, id, color, size): color_encoded = quote(str(color)) # کدگذاری رنگ size_encoded = quote(str(size)) # کدگذاری سایز result = f'{id}-{color_encoded}-{size_encoded}' return result def remove_cart(self): del self.session[Cart_Session_Id] self.save() def add(self, product, quantity, color, size): unique = self.unique_id_generator(product.id, color, size) if unique not in self.cart: self.cart[unique] = { 'quantity': int(quantity), 'price': str(product.Price), 'size': size, 'id': str(product.id), 'color': color } else: self.cart[unique]['quantity'] += int(quantity) self.save() def total_price(self): cart = self.cart.values() total_price = sum(int(item['price']) * int(item['quantity']) for item in cart) return total_price def delete(self, unique_id): if unique_id … -
Celery/Redis trigger send_email task twice per task
I have a Celery task to send an email, but since some time ago this email arrives 2 times with the same subject and body. I consider important to mention, for sending emails I use SendGrid. Attached is a fragment of the code used to run the task app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.broker_transport_options = {'visibility_timeout': 43200} "send_sales_ga_rental":{ "task": "core.tasks.send_sales_ga_rental", 'schedule': crontab(0, hour=12, day_of_week='1') } app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Finally, I consider important to mention that this application runs on a Heroku server. [![enter image description here][1]][1] [1]: https://i.sstatic.net/K6cAoCGy.png -
how to send data returned from a function to client in django in real time without the client need to refresh
I am writing a program to retrieve data and display it in a Django template. I have a function called match_algo() that takes a long time to run. I want to initially show 'Loading...........' on the page, and once the function completes and returns the result, I want to display the retrieved content on the page. This is the view I tried first : def redirected_page(request): data = match_algo() context = { 'data' : json.dumps(data), 'test' : 'test' } return render(request , 'redirected_page.html' , context ) After some research, I found that WebSockets might help with this, but I'm still not sure if it's the solution I need. This is my consumer.py: class LoadingConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() # Send "loading..." message when the connection is established await self.send(text_data=json.dumps({ 'message': 'loading...', "status" : False })) data = match_algo() # Send "loading completed" message after processing is done await self.send(text_data=json.dumps({ 'message': "loaded", "status" : True, # "matches" : data })) # Close the connection after sending the final message await self.close() for testing purpose I commented this line data = match_algo() then added time.sleep(5). this actually works. But when i run with match_algo after few seconds the websockets disconnects. but … -
Djagno ORM diacritic and case insensitive query with matching at least 3 chars
I'd like to quiry the columns "title" and "content" of the following django model w postgresql integration in a diacritic- and casing-insensitive way. The query should return articles when the string "Ronald" is present in either of these columns, for every of the following user inputs: "ronálD", "Ron" and even "ronald reagan" for example. class Article(models.Model): date = models.DateField() content = models.TextField() title = models.CharField(max_length=300) category = models.CharField(max_length=50) length = models.IntegerField(default=4, null=True) thumbnail = models.TextField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) img_location = ArrayField(models.TextField(), blank=True, default=list, null=True) Thanks for the assistance! I came as far as returning articles casing and diacritic-insensitively w substring mathcing, but did not manage to return articles when only a set of letters are matching: eg: "Reagen" for the input "Ronald Reagan", or when querying multiple columns: from django.db.models import Func, Value, F, Q class Unaccent(Func): function = 'unaccent' class Lower(Func): function = 'lower' def normalize_field(field_name, is_array=False): if is_array: return Unaccent(Lower(F(field_name), function='unnest')) return Lower(Unaccent(F(field_name))) normalized_term = Lower(Unaccent(Value(input_term))) articles = list(Article.objects.annotate( normalized_content=normalize_field('content'), ).filter( Q(normalized_content__icontains=normalized_term) ).order_by("-id").values()[:20]) -
Switching execution engine from Celery to Kubernetes for my django app
In my current Django application i'm using celery to execute my tasks. After knowing capabilities of kubernetes i want to switch from celery to Django. I have implemented one architecture but it is incomplete I'm using docker to host BE and FE which is primarily outside k8s cluster, I have define a message broker like redis same as celery which keeps track of new task, after receiving task my kube.py will generate pod in k8s cluster and will execute that task. This was the overview of my current architecture Note: My app is monolithic (don't want to convert it to microservice for some reason) My concerns are straight forward. How can i pass tasks from my native application to k8s cluster how to keep track of tasks i.e success, failed if failed i want to re-execute it how to keep logs, i want to keep one pod running at all time i want to scaleup and scale down pods based on tasks available -
Encoding cookies in Django
It seems like Django does not encode my cookies properly I tried using: resp = request.get_signed_cookie('age', salt='code') However the output for number '20' would be '20:1sl4MF:RUUEG71gABt4-MeCj_lZiuklArWiCOLTKsxKfjLvlUg', meaning that the value is still visible, and the code just adds ':' and a bunch of characters. Same goes for other numbers and strings. Is it normal or am I doing something wrong? -
Send response from a function as real time in Django
I am writing a program to retrive data and display it in django template. I have a function match_algo() This takes a long time to run. What i want it is to load and display "Loading.........." in the page. After getting the response from the function . display this content in the page. This is the view I tried first : def redirected_page(request): data = match_algo() context = { 'data' : json.dumps(data), 'test' : 'test' } return render(request , 'redirected_page.html' , context ) after few research I found out that websockets can help with that. Still I am not sure if it is the one that i need. This is my consumer.py: class LoadingConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() # Send "loading..." message when the connection is established await self.send(text_data=json.dumps({ 'message': 'loading...', "status" : False })) data = match_algo() # Send "loading completed" message after processing is done await self.send(text_data=json.dumps({ 'message': "loaded", "status" : True, # "matches" : data })) # Close the connection after sending the final message await self.close() for testing purpose I commented this line data = match_algo() then added time.sleep(5). this actually works. But when i run with match_algo after few seconds the websockets disconnects. but …