Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OperationalError at /register/ no such table: CustomUser
models.py from django.db import models class CustomUser(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(unique=True) password = models.CharField(max_length=100) address = models.CharField(max_length=255) adharcard = models.CharField(max_length=12, unique=True) age = models.PositiveIntegerField() phone = models.CharField(max_length=15) class Meta: db_table = 'CustomUser' def __str__(self): return self.email views.py from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.hashers import make_password from django.views import View from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import CustomUser def home(request): return render(request, 'app/login.html') def register(request): if request.method == 'POST': first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') password = request.POST.get('password') address = request.POST.get('address') adharcard = request.POST.get('adharcard') phone = request.POST.get('phone') age = request.POST.get('age') hashed_password = make_password(password) user = CustomUser.objects.create( first_name=first_name, last_name=last_name, email=email, password=hashed_password, address=address, adharcard=adharcard, phone=phone, age=age ) user.save() return redirect('app/login.html') return render(request, 'app/register.html') class LoginView(View): """ Login view for the user. Returns: Response: indicating the result of the login attempt. - If successful, redirects to the dashboard. - If the user is not found, renders the login page with an error message. - If the password is incorrect, renders the login page with an error message. """ def get(self, request): return render(request, 'app/login.html') def post(self, request, *args, **kwargs): email = request.POST.get('email') … -
Imgur error 429: Only when trying to access image from Django application
So basically I have an active Django project where in a module I am uploading images to the Imgur server and retrieving them as a background image for generating a PDF using the direct link for the images (https://i.imgur.com/<hash>.png) The issue is that when trying to retrieve any image from the django server which is running on the local network IP (since the Imgur server blocks localhost) the server responds with a bizzare 429 error code. The bizzare thing is I can upload images to my application without any problem, and also access the direct image links from postman API / browser, but as soon as I try to read the image direct link from my Django server imgur responds with a status code of 429. Rate Limit data for my application: { "data": { "UserLimit": 500, "UserRemaining": 499, "UserReset": 1709980963, "ClientLimit": 12500, "ClientRemaining": 12495 }, "success": true, "status": 200 } Request code: import requests id = '<hash>' res = requests.get(f'https://i.imgur.com/{id}.png') # print(res.json()) #! Throws JSONDecodeError print({ "Headers": res.headers, "status_code": res.status_code, "reason": res.reason, "content": res.text, "url": res.url, }) Response Headers and content I have retrieved from debugging because the res.json() method is failing { "Headers": { "Connection": "close", "Content-Length": "0", … -
Reversed foreign key on an unmanaged model doesn't work
I've recentrly ran into a following problem. I have a couple of unmanaged models class A(models.Model): # some fields class Meta: app_label = "app" db_table = "table_a" managed = False class B(models.Model): # some fields a_fk = models.ForeignKey(A, on_delete=models.RESTRICT, related_name="b_objects") class Meta: app_label = "app" db_table = "table_b" managed = False so, as you can see, I've added related_name="b_objects" which I need to access objects B from objects A via django ORM. I need to get a count of B objects for each A object in my view, so what I do is: class InventoryLocationsCollectionView(ListAPIView): queryset = A.objects.prefetch_related("b_objects").annotate(total=Count("b_objects")) however what I get is an error that there's no such field 'b_objects' in A model. I also tried to use queryset = A.objects.raw("my query") however it didn't work as it calls .all() somewhere under the hood and raw querysets do not have .all() method. Also the difficulty is that I'm gonna need to add some filters and pagination raw queryset do not seem to support either. Are there any workarounds to make reversed foreign key work in unmanaged models? -
Django Rest Framework session authentication default view JSON Parse
I'm making a user session auth via DRF, React and Axios. I also use Postman for testing my endpoints. So the question is how to make default login view from rest_framework.urls work with JSON format. When I send user data (username and password) via form-data radio button inside Postman everything is working as intended. But when I use JSON format inside both Postman and Axios the DRF endpoint returns such html page: settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } urls.py urlpatterns = [ path('drf-auth/', include('rest_framework.urls')), ] My JSON data {"username": "admin", "password": "admin"} -
Users may not be connecting to the same websocket - django channels
I’m developing a chat feature using django channels. when a message is sent, It gets created on the server side and I think it’s being broadcasted. in my consumer I'm adding both the sender and receiver to the same group. on the client side I’m using javascript to get the sender and receiver IDs and connect them to the websocket. but when user A sends a message to user B. even though the message object is created and sent, it doesn’t appear for User B. I've verified that both users are connected to the websocket and there are no errors. but i think the issue might be that they are not connecting to the same websocket but I’m not sure why this is happening. also I'm new to django channels and javascript. Javascript let senderId = null; let receiverId = null; document.addEventListener('DOMContentLoaded', function () { const chatLog = document.querySelector('#chat-conversation-content'); const messageInput = document.querySelector('#chat-message-input'); const chatMessageSubmit = document.querySelector('#chat-message-submit'); const activeChat = document.querySelector('.fade.tab-pane.show'); let chatSocket = null; function connectToChat(sender_id, receiver_id) { const wsURL = 'ws://' + window.location.host + '/ws/messenger/' + sender_id + '/' + receiver_id + '/'; try { chatSocket = new WebSocket(wsURL); chatSocket.onopen = function (e) { console.log('WebSocket connection established.'); }; … -
'Settings' object has no attribute 'PASSWORD_RESET_CONFIRM_URL'
A strange error 'Settings' object has no attribute 'PASSWORD_RESET_CONFIRM_URL', although Djoser settings have this field. the error occurs when trying to reset the password for an activated account. In addition, Djoser does not send an e-mail for activation of the account for some reason, but it does not display any errors. DJOSER = { 'USER_MODEL': 'users.Users', 'LOGIN_FIELD': 'email', "PASSWORD_RESET_CONFIRM_URL": '{}/password/reset/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SEND_CONFIRM_EMAIL': False, 'USER_AUTHENTICATION_RULES': \['djoser.auth.authentication.UserAuthentication'\], 'SERIALIZERS': {'user_create': 'users.serializers.UserSerializer',} }``` the error occurs when trying to reset the password for an activated account. -
Swagger Documentation Issue: Incorrect Field Definition for SerializerMethodField in Django REST Framework
Problem Description I'm encountering an issue with generating Swagger documentation for a Django REST Framework project. Specifically, I'm using a SerializerMethodField named info in my serializer. However, in the generated Swagger documentation, it's incorrectly defined as a string, whereas info is derived from a related model and is not a string. Example In the Swagger documentation, info is incorrectly represented as a string: { "count": 0, "next": "http://example.com", "previous": "http://example.com", "results": [ { ... "info": "string", ... } ] } Relevant Serializer Code Here's a snippet of the serializer where the issue arises: class ProductSerializer(serializers.ModelSerializer): ... @staticmethod def get_info(obj): info = ProductInfo.objects.filter(product=obj.id) return ProductInfoSerializer(info, many=True).data ... I tried using swagger_serializer_method, but it doesn't seem to have any effect. Here's what I attempted: from drf_yasg.utils import swagger_serializer_method class ProductSerializer(serializers.ModelSerializer): ... @staticmethod @swagger_serializer_method(serializer_or_field=ProductInfoSerializer().fields) def get_info(obj): info = ProductInfo.objects.filter(product=obj.id) return ProductInfoSerializer(info, many=True).data ... However, this didn't resolve the issue. The problem applies to several fields, not just info. I'm seeking guidance on how to correctly represent info and other similar fields in the Swagger documentation. Any help or suggestions would be greatly appreciated. -
I created a filter function for my website but the javascript is not working
I created a filter option to filter the products by brand So, In my index.html <select id="brandFilter"> {% for v in vendors %} <option value="">All Brands</option> <option value="brand1" data-filter="vendor" class="filter-checkbox" type="checkbox" name="checkbox" value="{{v.id}}">{{v.title}}</option> <!-- Add more options as needed --> {% endfor %} </select> And I make a script for this So, In my function.js $(document).ready(function(){ $(".filter-checkbox").on("click" , function(){ console.log("Clicked"); }) }) And I also connected the template with the js file <script src="{% static 'assets/js/function.js' %}"></script> by this code. I am sure that the js file is connected with template but the filter function is not working. And also In my context-processor.py def default(request): categories=Category.objects.all() vendors=Vendor.objects.all() try: address=Address.objects.get(user=request.user) except: address=None return { 'categories':categories, 'address':address, 'vendors':vendors, } Please help me out with this!!! -
Getting whitenoise.storage.MissingFileError: The file 'vendor/bootswatch/default/bootstrap.min.css.map' could not be found
When I am using whitenoise to host my static files, after entering the python manage.py collecstatic command I am getting this error: whitenoise.storage.MissingFileError: The file 'vendor/bootswatch/default/bootstrap.min.css.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x0000029983D66570>. but when I remove all the whitenoise configurations it works collects all the static files successfully. Below are white noise and static files config in my settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR /'static'] STATIC_ROOT = "static_root" STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" and MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Method not allowed DRF 405
I have API that should retrieve data about some country based on their names. But instead I'm getting error Method not allowed. How do I fix it? I am not using models for the countries. def get_country_info(country): country_info = { "Germany": [ _("Germany is a country with a rich history and culture, located in Central Europe. It is home to world-famous cities such as Berlin, Munich, Hamburg and Cologne. Germany is famous for its architecture, museums, beer and sausages."), ['img1', 'img2'], ], "USA": _( "The USA is the largest country in the world by area and population. It is located in North America and is a leading global economic and cultural center. The USA is known for its skyscrapers, Hollywood, Disneyland and Niagara Falls." ), "UK": _( "The United Kingdom is an island nation located in the North Atlantic. It comprises England, Scotland, Wales and Northern Ireland. The UK is the birthplace of the English language, Parliament, Big Ben and Queen Elizabeth II." ), "Turkey": _( "Turkey is a country located at the crossroads of Europe and Asia. It is known for its beaches, ancient ruins, mosques and bazaars. Turkey is a popular tourist destination for lovers of history, culture … -
Model fields not being displayed in django admin
actually i am beginner learning django and i wanted to create my own project. so i started with making models and fields of all required apps then i also registered in admin.py but still the fields are not being shown in the django admin panel. So this is models.py of one of my django app from django.db import models from authentication.models import User from course_management.models import Course # Create your models here. class Attendance(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) course=models.ForeignKey(Course,on_delete=models.CASCADE) date=models.DateField() status=models.CharField(max_length=250) and i have registered it in admin.py as well, but still the fields are not shown in django admin. this is happening w all the other django apps as well from django.contrib import admin from .models import Attendance # Register your models here. class AttendanceAdmin(admin.ModelAdmin): list_display=('user','course','date','status') admin.site.register(Attendance,AttendanceAdmin)``` -
Django Model email field is required even after i set it as null=True and blank=True
I have a problem with email field in django model. I have set it null True and blank True but this couldn't prevent admin user forms or any other web forms where i include email, to not require email if sumitted blank. Seems it is related to overriden email field in my custom user model but I am new to Django, so I don't have any idea where to pay attention to troubleshoot. here is my custom user model with its manager.. `from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from .managers import UserManager class User(AbstractUser): GENDER_CHOICES = ( ('male', _('Male')), ('female', _('Female')), ('not_set', _('Not set')), ) email = models.CharField(_('Email'), max_length=30, unique=True, blank=True, null=True) phone = models.PositiveBigIntegerField(_('Phone number'), unique=True, null=True, blank=True) telegram = models.BigIntegerField(_('Telegram ID'), unique=True, null=True, blank=True) first_name = models.CharField(_('First name'), max_length=50, blank=True, null=True ) last_name = models.CharField(_('Last name'), max_length=50, blank=True, null=True ) middle_name = models.CharField(_('Middle name'), max_length=50, blank=True, null=True ) gender = models.CharField(_('Gender'), max_length=7, choices=GENDER_CHOICES, default='not_set') profile_image = models.ImageField(_("Profile image"), upload_to='user/img/profile/', blank=True, null=True) cover_image = models.ImageField(_("Cover image"), upload_to='user/img/cover/', blank=True, null=True) user_verified_at = models.DateTimeField(_('User verified at'), null=True, blank=True) phone_verified_at = models.DateTimeField(_('Phone verified at'), null=True, blank=True) telegram_linked_at = models.DateTimeField(_('Telegram linked at'), null=True, blank=True) USERNAME_FIELD … -
Retrieve all activities from Strava API to Python
I Already registered my API in my Strava Account and I Want to fetch all activities of the user. Here's my current snippet code: auth_url = "https://www.strava.com/oauth/token" activites_url = "https://www.strava.com/api/v3/athlete/activities" payload = { 'client_id': "xxxx", 'client_secret': 'xxxx', 'refresh_token': 'xxxx', 'grant_type': "refresh_token", 'f': 'json' } res = requests.post(auth_url, data=payload, verify=False) print("Authentication Status:", res.status_code) access_token = res.json()['access_token'] print('ACCESS TOKEN: ', access_token) #Prints '200' which is correct header = {'Authorization': 'Bearer ' + access_token} param = {'per_page': 200, 'page': 1} my_dataset = requests.get(activites_url, headers=header, params=param).json() print('DATASET: ', my_dataset) #This line returns: {'message': 'Authorization Error', 'errors': [{'resource': 'AccessToken', 'field': 'activity:read_permission', 'code': 'missing'}]} It says that the 'code' is missing. Is that the main and only reason that leads to Authorization Error? How do I Retrieved it? I'm Currently developing on localhost only. Access_token is not expired. -
Cannot access Django project homepage (Docker)
I'm building an app with Django, but although my app runs fine (at least, it's what CLI tells me) I can´t access it via browser. The docker-compose build and up works just fine, I get this output: matt $ docker-compose run app sh -c "python manage.py runserver" [+] Creating 2/2 ✔ Network nexus_default Created 0.0s ✔ Container nexus-db-1 Created 0.1s [+] Running 1/1 ✔ Container nexus-db-1 Started 0.2s Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 08, 2024 - 23:21:49 Django version 5.0.3, using settings 'app.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But I can't access it through my browser (Screenshot attached) My configs are below Dockerfile: FROM python:3.12-alpine3.19 LABEL maintainer="Matheus Tenório" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf … -
Django celery getting PermissionError when trying to delete file
I am using django celery for downloading and uploading image but when try to delete image after upload more specifically after .save() method got this error os.remove(filename) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'UKXCWKYRPMPKNXBK6111_img_91b00679-dc6f-4078-96f6-23c7274d4577_958e8046-4b0f-4396-82c2-0dac374b72df_flaskj.webp' my image is downloading and uploading but can't delete after upload complete successfully my celery code: @shared_task def download_s3image(image_id,order_id=None): s3 = boto3.client('s3') image_id = image_id image = ProductImage.objects.get(id=image_id) image = str(image.image) img_path = image.replace('product_images/','').replace('.webp','') # Get the OrderItem model dynamically to avoid circular import OrderItem = apps.get_model('order', 'OrderItem') order_item = OrderItem.objects.get(id=order_id) # Assuming there is a relationship between OrderItem and Order filename = f'{order_item.order.order_id}_img_{img_path}.webp' s3.download_file('epeey',image,filename) order_item.order_image_file.save(filename, open(filename, 'rb')) order_item.save() #can't remove file using os.remove os.remove(filename) -
Left join in Django with three models
I am new to Django and I don't know how to do joins. I have the following models and their corresponding tables: ModelA -> Table a: id, name ModelB -> Table b: a_id, c_id, extra ModelC -> Table c: id, number I would like to perform this left join: SELECT a.*, b.extra, c.number FROM a LEFT JOIN b ON a.id = b.a_id LEFT JOIN c ON c.id = b.d_id I don't know how to do that, or if it's even possible. -
How to dynamically change static urls in an Angular application in every component
I have an Angular application that I am using alongside a Django application. In Django we have something like this src="{% static 'folder/file' %}" where we can change the static urls dynamically based on our environment. (Example, I can have static files pointing to my local machine vs I can have them deployed in AWS S3, changing it in one place in the application, will change it everywhere.) How can I implement something similar in Angular, where I can change the static_url dynamically based on the environment. I would like this to work on all the components within my application. Example: When using ng serve it could be /assets But when using ng build it would be https://s3_bucket_url/assets -
Django Channels Custom Middleware Not Being Called
With Django 4 and Channels 4 I have a middleware as follows from channels.middleware import BaseMiddleware class TokenAuthMiddleware(BaseMiddleware): async def __call__(self, scope, receive, send): print('asdf') headers = dict(scope['headers']) if b'authorization' in headers: # Fetch the token here token = headers[b'authorization'].decode().split(' ')[-1] scope['token'] = token return await self.inner(scope, receive, send) In my INSTALLED_APPS, I have channels and daphne near the top. I also have properly set ASGI_APPLICATION in my django settings. And in my asgi.py I have: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': TokenAuthMiddleware(AuthMiddlewareStack( URLRouter([ re_path(r'ws/agent/$', AgentConsumer.as_asgi()), ]) )), }) AgentConsumer is a channels consumer based on AsyncChannelConsumer Yet when I connect to the websocket (in this case, a raw python script using the websockets module), I don't think the middleware is being run. If I put a print statement in the class definition, I see it. But if I put it in __call__(), I never see the print statement. To add, I have AuthMiddlewareStack, but it seems like it's allowing even unauthenticated socket connections, meaning none of that middleware is being executed? Is there a reason it seems like the middleware is not being executed? -
How do I add dependencies that can't be installed with pip to my (django) project on Heroku?
I've come across multiple similar issues to this and I haven't seen a clear answer so I thought it best to ask here. I'm working on a django project, and one of the packages it uses requires PyMuPDF which in turn requires swig, which can't be installed with pip/add to requirements.txt. I'm trying to deploy this project to Heroku and this is causing it to fail. See the build error from Heroku below. PyMuPDF/setup.py: Finished building mupdf. PyMuPDF/setup.py: library_dirs=['mupdf-1.20.0-source/build/release'] PyMuPDF/setup.py: libraries=['mupdf', 'mupdf-third', 'jbig2dec', 'openjp2', 'jpeg', 'freetype', 'gumbo', 'harfbuzz', 'png16', 'mujs'] PyMuPDF/setup.py: include_dirs=['mupdf-1.20.0-source/include', 'mupdf-1.20.0-source/include/mupdf', 'mupdf-1.20.0-source/thirdparty/freetype/include', '/usr/include/freetype2'] PyMuPDF/setup.py: extra_link_args=[] running bdist_wheel running build running build_py running build_ext building 'fitz._fitz' extension swigging fitz/fitz.i to fitz/fitz_wrap.c swig -python -o fitz/fitz_wrap.c fitz/fitz.i error: command 'swig' failed: No such file or directory [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for PyMuPDF Running setup.py clean for PyMuPDF Successfully built docopt fire langdetect mplcursors Failed to build PyMuPDF ERROR: Could not build wheels for PyMuPDF, which is required to install pyproject.toml-based projects ! Push rejected, failed to compile Python app. ! Push failed I had a similar situation where a package required libffi … -
Having issue returning data in django templates
So I am working on a small django project and I am having an issue with a foreign key. I have a model with 2 tables mymodel1 and mymodel2. #Models.py class Mymodel1(moels.Model): name = models.CharField(max_length=20) blurb = models.CharField(max_length=20) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Mymodel2(moels.Model): name = models.ForeignKey(Mymdoel1, on_delete=models.CASCADE) somethingelse = models.CharField(max_length=20) my urls pass in the id from Mymodel1 and my template returns the data but I also want the template to return the data from my model2 def get_details(request ,id): if User.is_authenticated: try: single_record = Mymodle1.objects.get(id=id) details = Mymodel2.objects.get(id=single_record.name) except Exception as e: raise e context = { 'single_asset': single_asset, 'details': details, } return render(request, 'detail.html', context=context) else: return render(request, 'home.html') but I cannot get the view to return the details. -
why is " docker build ." failing with "ERROR [internal] load metadata for docker.io/library/python:3.11"
(venv) PS D:\DESK\desktop\django code\Django_Docker_with_PostgreSql> docker build . [+] Building 1.0s (3/3) FINISHED docker:default => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 215B 0.0s => ERROR [internal] load metadata for docker.io/library/python:3.11 0.9s => [auth] library/python:pull token for registry-1.docker.io 0.0s [internal] load metadata for docker.io/library/python:3.11: Dockerfile:1 1 | >>> FROM python:3.11 2 | 3 | ENV PYTHONDONTWRITEBYTECODE 1 ERROR: failed to solve: python:3.11: failed to authorize: failed to fetch oauth token: unexpected status from POST request to https://auth.docker.io/token: 403 Forbidden restarted docker,labtop, sign in and sign-out docker initial new project ..... nothing has worked for me -
How to Let users have free counted days then after that they should pay?
I'm trying to make the users of type Manager to have a free 4 days for example then after that they should pay to get access to some features I tried this class CustomUser(AbstractUser): territorial=models.CharField(max_length=80) phone_number=models.CharField(max_length=15) is_real=models.BooleanField(default=False) is_resident=models.BooleanField(default=False) is_manager=models.BooleanField(default=False) def __str__(self) : return self.username def fullname(self): return f'{self.first_name} {self.last_name}' class Manager(models.Model): user=models.OneToOneField(CustomUser,on_delete=models.CASCADE,related_name='manager') village_name=models.CharField(max_length=60) manimg=models.ImageField(blank=True,null=True) is_has_dwar=models.BooleanField(default=False) is_subscribed=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return self.user.username def save(self,*args, **kwargs): two_days_later = timezone.now() + timedelta(minutes=5) if timezone.now() >= two_days_later: self.is_subscribed = False else: self.is_subscribed=True super().save(*args, **kwargs) I also tried this @receiver(post_save, sender=CustomUser) def set_manager_subscription(sender, instance, created, **kwargs): if created and instance.is_manager: manager = instance.manager manager.is_subscribed = True manager.save() # Set is_subscribed back to False after two days two_days_later = manager.created_at + timezone.timedelta(days=2) if timezone.now() > two_days_later: manager.is_subscribed = False manager.save() but with no result so please if you have any solutions or you handled this write it bellow and explain how it work , thanks in advance -
SQL Server FREETEXTTABLE query to mySQL
I got a Django project that was previously using a Sql Server database. I need to adapt it now for mySQL. I struggle to implement and find the equivalent for that raw sql using FREETEXTTABLE. If anyone could point me in the right direction on any documentation that would be greatly appreciated. Original SQL Server raw query sql = "select c.myKey, b.[KEY], b.RANK, a.article_appendix, c.article_appendix as article, c.title_en as t1_en, c.title_fr as t1_fr, a.title_en as t2_en, a.title_fr as t2_fr from [myapp_collectiveagreementsubarticle] a inner join (SELECT * FROM FREETEXTTABLE ([myapp_collectiveagreementsubarticle], ([content_en]), " + search2 + ")) b on a.myKey = b.[KEY] inner join [myapp_collectiveagreement] c on a.articleKey_id = c.myKey order by b.RANK desc" searchResult = Collectiveagreement.objects.raw(sql) -
Uploading multiple large files with django on Google App Engine -- how to do multiple requests
I'm trying to figure out how to load multiple large files (like 4K images) to Google Cloud Storage via django using the default admin interface. For example, I have a model with multiple images: MyModel(models.Model): image_1 = models.ImageField( null=True, upload_to="myapp/images" ) image_2 = models.ImageField( null=True, upload_to="myapp/images" ) However, if I enter data for this model in the admin interface, this causes an error if I load two large files that go over GAE's 32 MB post limit. I've tried using django-gcp and BlobField, but this also causes issues because the temporary uploads overwrite each other before transferring to Google Cloud Storage -- and it doesn't look like this is solvable with django-gcp out of the box. So right now I'm wondering if it's possible to break out upload into multiple POST requests -- that way each one can be a separate ImageField (if under 32MB) or BlobField, and I won't have any issues. Is there a way I can upload a model in multiple POSTs? -
Python opentelemetry events in Application Insights
I'm following the guides below trying to setup logging in Azure Application Insights for my django application: https://uptrace.dev/get/instrument/opentelemetry-django.html https://uptrace.dev/opentelemetry/python-tracing.html https://opentelemetry.io/docs/languages/python/automatic/logs-example/ And have ended up with code that looks like this: myapp/manage.py def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') # Configure OpenTelemetry to use Azure Monitor with the specified connection string configure_azure_monitor( connection_string="InstrumentationKey=myKey;IngestionEndpoint=https://centralus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://centralus.livediagnostics.monitor.azure.com/", ) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() myapp/views.py import logging from opentelemetry import trace class SomeView(LoginRequiredMixin, TemplateView): login_required = True template_name = "myapp/index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("SomeView") as span: if span.is_recording(): span.set_attribute("user.id", self.request.user.id) span.set_attribute("user.email", self.request.user.email) span.add_event("log", { "log.severity": "info", "log.message": "Mark was here.", "user.id": self.request.user.id, "user.email": self.request.user.email, }) span.add_event("This is a span event") logging.getLogger().error("This is a log message") context['something'] = SomeThing.objects.all() return context The good: I do get results in Application Insights. When I look at end-to-end transaction details I see something like this, which is great. Traces & Events 10 Traces 0 Events <- THIS IS THE ISSUE View timeline Filter to a specific …