Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use upsert command in django for bulkupdate?
I need to update 1000's of rows each with differant values in timescale db. I found bulk update to do so. list = ModelClass.objects.filter(name = 'bar') obj_to_be_update = [] for obj in list: obj.name = "Dear "+obj.name obj_to_be_update.append(obj) ModelClass.objects.bulk_update(obj_to_be_update, ['name'], batch_size=1000) This takes alot of time to update and even atomic transaction took alot time to update in the db. Instead found upsert for timescale db which does execution faster. Any idea how to do it in django. https://docs.timescale.com/timescaledb/latest/how-to-guides/write-data/upsert/#upsert-functionality -
why docker-compose work and docker run doesn't
I have the following local.yml file version: '3' services: celery-worker-default: image: weapp_app:latest container_name: weapp_celery-worker-default command: celery worker -A WeApp -Q default -n default --loglevel=INFO env_file: - .env volumes: - .:/opt/python/current/app/ When I run docker-compose -f local.yml up celery-worker-default everything work great also running like docker-compose -f local.yml run celery-worker-default celery worker -A WeApp -Q default -n default --loglevel=INFO Everything run OK But If I try to execute with docker with the following command docker run -v "$(pwd):/opt/python/current/app/" -w /opt/python/current/app --env-file .env weapp_app:latest celery worker -A WeApp -Q default -n default --loglevel=INFO I get this error Error: Unable to load celery application. The module "WeApp was not found. I already try change $(pwd) for the local complete local path but I get the same error. In other way I try to pass all the environment value by command line with option -e and get the same error. I try without working directory in the docker options. I try opening a shell inside the container and execute the command, but the same error. -
django-ninja resolvers with access to request
I create an API with django-ninja. For one of the resolver-methods I need to access the request. Example: class ListingSchema(ModelSchema): playback_urls: AnyUrl ... def resolve_playback_urls(self, obj): return obj.get_playback(request) How can I access the request-object? (Where should I add the request to access it later?) -
Django recommend posts from the same user
How to do anological example on Django You need to show posts from the same creator, except which one is being watched now tasksPosts = [{ 'id': 123433, 'title': 'riddle' }, { 'id': 123333, 'title': 'test' }, { 'id': 723433, 'title': 'text' }, { 'id': 177733, 'title': 'text123' }] def get_additional_posts(): task = { 'id': 123433 } return list(filter(lambda post: post['id'] != task['id'], tasksPosts)) print(get_additional_posts()) models.py class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) -
How to create my own CLI like python scrapy/django command line does?
I'm trying to create my own program and execute it like if we are working using scrapy or django. For an example like the line below? scrapy shell <optional-url> django-admin startproject <project-name> -
New objects are made every time
I made a single function for register and login with mobile and otp. The register part is in the else part of the function, and the if part is the login function. Every time I log in with the already registered number, it makes a new object in the database, and I don't want that. I want to just update the otp part from when the number was registered in the database. views.py class RegistrationAPIView(APIView): permission_classes = (AllowAny,) serializer_class = ProfileSerializer def post(self, request): mobile = request.data['mobile'] data = Profile.objects.filter(mobile = mobile).first() if data: serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp} mobile = instance.mobile otp = instance.otp print("Success") send_otp(mobile,otp) return Response(content, status=status.HTTP_201_CREATED) else: return Response({"Error": "Login in Failed"}, status=status.HTTP_400_BAD_REQUEST) else: serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp} mobile = instance.mobile otp = instance.otp send_otp(mobile,otp) return Response(content, status=status.HTTP_201_CREATED) else: return Response({"Error": "Sign Up Failed"}, status=status.HTTP_400_BAD_REQUEST) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['mobile'] def create(self, validated_data): instance = self.Meta.model(**validated_data) global totp secret = pyotp.random_base32() totp = pyotp.TOTP(secret, interval=300) otp = totp.now() instance.otp = str(random.randint(1000 , 9999)) instance.save() return … -
Django Serialization - Partial update on nested objects
Searched around for a few hours on this and I am surprised I couldn't find an answer but here it goes. Let's say I have the following models: class Mission(models.Model): mission_name = models.CharField(max_length=150) ... class Player(models.Model): player_name = models.CharField(max_length=150, unique = True) state = models.CharField(max_length=150) currentMission = models.ForeignKey(Mission,on_delete=models.SET_NULL, blank=True, null=True)) Objectives: When creating a mission, I would like to provide the players' names that are going to participate on this mission (Names are unique). That means, when mission is created, I have to update the currentMission field of each given player. (Players already exist when mission is created) When I try to GET a mission, I would like to see the names of the players that participate My attempt Class MissionSerializer(serializers.ModelSerializer): #This is to get a list of the players that participate in this mission players = PlayerSerializer(many=True, read_only=True) class Meta: model= Mission fields = ['mission_name','players'] def create(self,validated_data): mission = Mission.objects.create(**validated_data) # Notice that I get the "players" data from "self.initial_data" and not from validated_data # This is because validated_data does not have the "players" field, # (I guess because I didn't provide all the required fields on my request for the player. I just provided the players' names ) … -
Django query set filter reverse startswith on charfield
Image some kind of product-rule which has 2 conditions: name are equal sku's have partial match, starts with. The rule model looks like this: class CreateAndAssignRule(models.Model): name_equals = models.CharField(max_length=100) sku_starts_with = models.CharField(max_length=100 Now I want to fetch all of the rules with name Product 1 and match sku sku-b-292 class CreateAndAssignRuleQuerySet(QuerySet): def filter_by_name_and_sku(self, name, sku): # We're looking which of the rules have a matching name, and where the rule have a string which is the string of the sku provided. rules = self.filter(name_equals=name) approved_ids = [] for rule in rules: # We're looping through the rules to find out which of them has the beginnings of the sku. # a sku_starts_with field would contains value eg: 'sku-a' where as the search string would be the full sku 'sku-a-111'. We want to match 'sku-a-111' but not 'sku-b-222'. if sku.startswith(rule.sku_starts_with): approved.append(rule.id) return self.filter(id__in=approved_ids) although the above works, it's hardly efficient especially as the number of rule is starting to grow a lot. How can I resolve this with a queryset? Filtering on __startswith doesn't do the trick as it the reverse. -
Using Django DeleteView and getting a 404 after delete confirmation
After clicking on "confirm" in my organism_delete.html form, I used to be redirected back to the list of organisms (organism_list.html template) as specified in the view. But now I get a 404 error instead. Page not found (404) Request Method: GET Request URL: http://localhost:8000/library/organisms/ABC1233/delete/post?csrfmiddlewaretoken=Rdk575IEp5bbvrriJ1szlYNjmq8V1DvuYzNWEWz07s78IJSal9foHdkvxwcimIEp Using the URLconf defined in itslibrary.urls, Django tried these URL patterns, in this order: admin/ accounts/ [name='home'] library/ organisms/ [name='organism_list'] library/ organisms/new/ [name='organism_new'] library/ organisms/ [name='organism_detail'] library/ organisms//update/ [name='organism_update'] library/ organisms//delete/ [name='organism_delete'] ^media/(?P.*)$ The current path, library/organisms/ABC1233/delete/post, didn’t match any of these. Two things that stand out to me is first that the error says it's a GET request, not a POST as the form specifies. And second is why is it trying to get to .../delete/post...? It might be important to know that I changed my model and added "Primary Key = True" to a unique CharField, and I've been modifying the rest of the app to match that. It may not be related because I can list the organisms and I can get to the delete page, I just can't submit it. I don't know how to debug this, it seems to be hidden behind the Django magic, any guidance will be very appreciated. … -
Trigger multi-configuration jenkins' job remotely using python
I'm developping a django dashboard that trigger a multi-configurations job in jenkins remotely, I tried everything and i read the jenkinsapi documentation but in vain. Any one have an idea please? -
Django annotate with frequency
(django 3.2.12, python 3.9.3, MySQL 8.0.28) Imagine models like the following: class User(models.Model): email = models.EmailField(...) created_datetime = models.DatetimeField(...) class UserLog(models.Model): created_datetime = models.DatetimeField(...) user = models.ForeignKey('user.User' ...) login = models.BooleanField('Log in' ..) And the following query, destined to annotate each user in the queryset with the frequency of their logs(when log.login=True): users = User.objects.filter( Q(...) ).annotate( login_count=Count('userlog', filter=Q(userlog__login=True)), login_duration_over=Now() - F('created_datetime'), login_frequency=ExpressionWrapper( F('login_duration_over') / F('login_count'), output_field=models.DurationField() ), ) This results in a SQL error: (1064, "You have an error in your SQL syntax;) The generated SQL (fragment for login_frequency) looks like this: ( INTERVAL TIMESTAMPDIFF( MICROSECOND, `user_user`.`created_datetime`, CURRENT_TIMESTAMP ) MICROSECOND / ( COUNT( CASE WHEN `user_userlog`.`login` THEN `user_userlog`.`id` ELSE NULL END ) ) ) AS `login_frequency`, and MySQL does not seem to like it. A similar code works on SQLlite and, I am told on PG. What is wrong with the ExpressionWrapper on MySQL, any idea? -
request.META.get('HTTP_REFERER') isn't working when prefix_default_language=True
url = request.META.get('HTTP_REFERER') worked when prefix_default_language=False. But when I make prefix_default_language=True, it isn't getting anything. Help please. -
How to display the product of multiple models in a model using foreign key or something else
I want to display my product offers and monthly plans in the single model Theres products and monthly plan model class Monthlyplan(models.Model): ... name = models.CharField(max_length=220) class Product(models.Model): ... name = models.CharField(max_length=220) class Customers(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) monthly_plan = models.ForeignKey(Monthlyplan, on_delete=models.CASCADE) Packages = GenericForeignKey('product', 'frozen_food') error core.Customers.Packages: (contenttypes.E004) 'Customers.product' is not a ForeignKey to 'contenttypes.ContentType'. HINT: GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field. -
ImportError: No module named sentry_sdk.integrations.wsgi
I'm trying to upgrade the implementation of the old Sentry config to the new one for my wsgi configuration in my django project but I'm getting the following error. ImportError: No module named sentry_sdk.integrations.wsgi Earlier I had: from raven.contrib.django.raven_compat.middleware.wsgi import Sentry Now I have: from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware My sentry init is in settings.py file as: sentry_sdk.init( dsn=SENTRY_CONFIG.get("dsn", ""), environment=SENTRY_CONFIG["environment"], integrations=[ DjangoIntegration(), CeleryIntegration(), sentry_logging, ], attach_stacktrace=True, send_default_pii=True, ) Using: Django==4.0.3 sentry-sdk==1.5.8 python3.8 Any help is appreciated, thanks in advance! -
got error while setting default image in ImageField Django
my model have an imagefield which stores the image for post . I want to add default image to that in case if not is not uploaded.But I am getting error The 'title_image' attribute has no file associated with it. If I upload image then its working fine. Models.py class Post(models.Model): title_image = models.ImageField( upload_to='Images/PostTitleImages/', max_length=None, default = 'Images/Image_not_found.jpg', blank = True, null = True) home.html <img src="{{post.title_image.url}}" height="350px"/> Settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('MainSite.urls'), name = "Main"), path('account/',include('account.urls'), name = 'Accounts') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) what I am doing wrong here I checked the file is in this directory /media/Images/PostTitleImages/ -
how can ı submit more than one row in django view with table form
ı wanna submit more than one record but in that code only first student can be record how can ı add more than one record in django view ı am prety new in django can anyone help about that table image thats the model.py class GonulluOgrenciDevamsizlik(models.Model): ogrenci_dersi = models.ForeignKey('Ogrenci', null=True, on_delete=models.SET_NULL) gonulu = models.ForeignKey('Gonullu', null=True, on_delete=models.SET_NULL) devamsizlik = models.BooleanField(verbose_name="Devamsızlık Bilgisi",blank=True, default=False) sinif = models.ForeignKey('SinifListe', null=True, on_delete=models.SET_NULL) olusturma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturma Tarihi') guncelleme_tarihi = models.DateTimeField(auto_now=True) class Meta: ordering = ['-devamsizlik'] verbose_name = 'Devamsızlık' verbose_name_plural = 'Devamsızlıklar' def __str__(self): return self.gonulu.ad + ' ' + self.gonulu.soyad here is my view: in view ı had been add required foreign keys for my table and then try to save coming post data from table form. def ogrencidevamsizlik(request, id): details = "hesabim/ogrenci-devamsizlik.html" siniflar = SinifListe.objects.filter(gonullu__gonullu__email=request.user.email) ogrenci = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email) gonulu = GonulluDersleri.objects.get(gonullu__email__iexact=request.user.email, id=id) gonulluler = Gonullu.objects.get(email__iexact=request.user.email) ders = GonulluDersleri.objects.filter(gonullu__email=request.user.email, id=id) devamsizliklar = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email, sinif__gonullu__id=id) if request.method == 'POST': form = DevamsizlikDetayForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'Devamsızlıklar başarılı bir şekilde eklendi.') return redirect('gonullu-siniflar') else: messages.error(request, 'Devamsızlık bilgilerinizdeki zorunlu alanları eksiksiz doldurmalısınız.') else: form = DevamsizlikDetayForm() context = {'devamsizliklar': devamsizliklar, 'gonulu': gonulu, 'ders': ders, 'form': form, 'ogrenci': ogrenci, 'siniflar': siniflar, 'gonulluler': gonulluler} return render(request, details, context) and … -
Function like keyword in return statement before loop in DRF APIView permission
Hey guys I am having a hard time understanding the following return statement code in django drf APIView source code: def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ return [permission() for permission in self.permission_classes] I understand that permission is the key iterating through permission_classes but what on earth is the permission() doing here -
How to implement Django social login using google for different type of users(eg: candidate ,employer, customer)
I want to implement Social login in my Django project. When I searched about it, I found social login for only one user. But I want to implement it for different type of users as I mentioned in the title. Can anyone suggest a solution to implement this in my project. -
Django-Python : Check if network file exists from web client
I would like to know if a network file exists from web client. On the server in localhost, it works (return True) but return False with IP adress. Code : folder = "\\IP\dir_test" id = "123456" filename = "{}.pdf".format(str(id)) path = os.path.abspath(folder + filename) check = os.path.isfile(path) return check Thanks for your help. Ben. -
Repetition of the same results consecutif
I need to check if I have repetition 4 times the same value for "PCR POS/Neg" consecutive, 3 times in my "output_df". How i can do it ? def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) headers = ['Vector Name', 'Date and Time', 'Test ID', 'PCR POS/Neg'] output_df = pd.DataFrame(columns=headers) with open(names_loc, "r") as fp: for line in fp.readlines(): line = line.rstrip("\\\n") full_name = line.split(',') sample_name = full_name[0].split('_mean') output_df['Date and Time'] = pd.to_datetime(output_df['Date and Time']) -
Django: Duplicate value to the new field on mingration
I have a modal called Account as below class Account(models.Model): name = models.CharField(max_length=225) category = models.ForeignKey(AccountCategory, on_delete=models.PROTECT) date_added = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(Staff, on_delete=models.SET_NULL, null=True) I already have data there, but i need to add another field called display_name which i need to inherit the value of name. i tried adding a field with a default value of name like this display_name = models.CharField(max_length=255, default=name) This was my final modal: class Account(models.Model): name = models.CharField(max_length=225) display_name = models.CharField(max_length=255, default=name) category = models.ForeignKey(AccountCategory, on_delete=models.PROTECT) date_added = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(Staff, on_delete=models.SET_NULL, null=True) But it failed to populate the field. someone help me out. -
How to handle 50k or above array of objects in Django Rest Framework?
I'm facing a problem. Our requirement is we cannot use pagination so we need all records at a time in Response. my function like this: from rest_framework.response import Response class TestingViewsAPI(APIView): def get(self, request): data_list = [{}....................] #50k list of dict return Response({ "Data": { "data": data_list, } }) When doing this then my system hang how i can handle this? I need expert guidelines I don't use pagination -
Manager isn't accessible via Police instances
Error is occurred in if user.objects.filter(login_id=login_obj).exists(): how to solve this error This is my police_app/views.py def police_register(request): if request.method == 'POST': login_obj = Login() login_obj.username = request.POST.get('uname') login_obj.password = request.POST.get('pwd') login_obj.save() if Login.objects.filter(username=request.POST.get('uname')).exists(): user = Police() user.station_name = request.POST.get('name') user.email = request.POST.get('email') user.mobile = request.POST.get('mob') user.district = request.POST.get('district') user.state = request.POST.get('state') user.login_id = login_obj user.save() if user.objects.filter(login_id=login_obj).exists(): return render(request, "login.html") return render(request, "police_app/police_register.html", context={'error': 'Registration failed'}) return render(request, "police_app/police_register.html") -
How to resolve problem with CORS policy django
I try to create module with OpenStreetMaps on my website, but when I try use it i got some errors: Access to image at 'https://c.tile.openstreetmap.org/3/6/5.png' (redirected from 'http://c.tile.openstreetmap.org/3/6/5.png') from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I try some method from web, but still not results. Can you see any error in code? In website script map is loading but map image have error. I try add corsheader middleware but problem still exist. I don't what to do more to repair this problem. All is fine but images have problem. Settings file from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS=['127.0.0.1'] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '--' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gosgucompl', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True ROOT_URLCONF = 'gosgu.urls' TEMPLATES = [ { … -
Need to make two model fileds as primary key
Here profile and category should be primary key how can i do this. class QuickApproximation(models.Model): profile = models.CharField(primary_key=True, null=False, max_length=1024, default=None) category = models.CharField(null=False, max_length=1024, default=None) approximation = models.IntegerField(null=False, default=None) I need to dump this data into DB Profile,Category,Approximations Always on road,Groceries,500 Always on road,Dining,500 Always on road,Gas,500 Always on road,Others,1500 Social Butterfly,Groceries,500 Social Butterfly,Dining,500 Social Butterfly,Gas,500 Social Butterfly,Others,1500 Foodie,Groceries,500 Foodie,Dining,500 Foodie,Gas,500 Foodie,Others,1500 Pantry Stocker,Groceries,500 Pantry Stocker,Dining,500 Pantry Stocker,Gas,500 Pantry Stocker,Others,1500 Avid Shopper,Groceries,500 Avid Shopper,Dining,500 Avid Shopper,Gas,500 Avid Shopper,Others,1500 Healthy nut,Groceries,500 Healthy nut,Dining,500 Healthy nut,Gas,500 Healthy nut,Others,1500 Digital Junky,Groceries,500 Digital Junky,Dining,500 Digital Junky,Gas,500 Digital Junky,Others,1500 and everything should be available in db