Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Error when try to integrate payment system
I try to integrate payment system to django. I did use django-flexible-subscriptions, installed, created appropriate url, view and html. But when I created Subscription Plan and when tried to save get an error "conversion from NoneType to Decimal is not supported". Somebody knows how can I fix this error? Best regards -
How to get the day difference in a little complicated way using queryset in Django
I am using Django, and whenever the manager of a task is changed, the change is saved in the history field. The history field is saved as follows. Here, I would like to get the duration of each manager. EX: {'field_summary': {'manager': 'Michael -> Michael/Amelia', 'contact': '010-1234-1234-> 010-1234-1234/010-9876-9876'}} [models.py] Task(models.Model): task_name = models.CharField(max_length=100, blank=False) manager_name = models.CharField(max_length=100, blank=False) history = models.ForeignKey(History, on_deleted=models.SET_NULL) .... create_date = models.DateTimeField(auto_now_add=True) [views.py] task = Task.objects.filter(id='20', history__summary__icontains='manager') [statistic.html] {% for task in task %} {% for h in task.history %} {% if h.summary_json.field_summary.manager %} manager: {{ h.summary_json.field_summary.manager }} date: {{ h.create_date }}, {% endif %} {% endfor %} {% endfor %} [result] manager: Michael/Amelia -> Michael/Sophia change_date: 2022-02-25, manager: Michael -> Michael/Amelia change_date: 2021-10-12, manager: Michael/Amelia -> Michael change_date: 2021-09-23, manager: who -> Michael/Amelia change_date: 2021-05-12, manager: None -> who change_date: 2021-04-12 I want to output something like Michael: 2021.05.12 ~ today total: 316 days Amelia:2021.05.12 ~ 2021.09.23 (134), 2021.10.12 ~ 2022.02.25. (136) total: 270 days Sophia: 2022.02.25. ~ today total: 27 days queryset -> Michael, 316, Amelia, 270, Sophia, 27 -
django : rename in admin panel does not work
When i change the primary key in the admin panel and choose the save button a new recrod is created. But i want to rename the primary key. models.py: class Firma(models.Model): firma = models.CharField( primary_key=True, max_length=50, db_column='Firma', help_text='Firma', verbose_name = 'Firma', ) def __str__(self): return self.firma admin.py: class FirmaAdmin(admin.ModelAdmin): list_display = ( 'firma', ) ordering = ('firma',) I use Django 3.2. What am I doing wrong? -
why is my list cannot be convert into zip list? python
i have 2 list that i got from input in my html i want to ouput that 2 list together but when i use zip(lista, listb) no output shown {% for proc, ope in procslist %} <tr> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.name}}</td> <td style="width:10%;">{{proc.setcost}} / {{proc.proccost}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.settime}}</td> <td style="width:10%;"> <input type="hidden" name="opetimelist" value="{{proc.id}}" id=""> <input type="text" name="opetime-{{proc.id}}" id="" value="{{ope}}" style="width: 80%;"> </td> </tr> {% endfor %} and this is my views.py proc = '' choosenproc = request.POST.get('choosenproc') if choosenproc: proc = Proc.objects.get(Q(name__icontains=choosenproc) | Q(id__icontains=choosenproc)) flag = False if proc: if selectedproc != []: for product in selectedproc: if product.id == proc.id: flag = True break if flag == False: selectedproc.append(proc) opetimelist = request.POST.getlist('opetimelist') opetimevalue = [request.POST['opetime-{}'.format(o)] for o in opetimelist] procslist = zip(selectedproc, opetimevalue) the result it no ouput how to fix this? -
django rest framework saving data to multiple tables from a single view
I'm currently new to DRF I am looking to save data to two database tables via the viewset and I don't know how to go about it. I am using react for my frontend here is my models from django.db import models # Create your models here. class Customer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=255) town = models.CharField(max_length=255) region = models.CharField(max_length=255) added_on = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Order(models.Model): id = models.AutoField(primary_key=True) order_no = models.CharField(max_length=255) customer_name = models.CharField(max_length=255) phone = models.CharField(max_length=255) town = models.CharField(max_length=255) region = models.CharField(max_length=255) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE) price_per_kgs = models.CharField(max_length=255) kgs = models.CharField(max_length=255) packaging = models.CharField(max_length=255) transport = models.CharField(max_length=255) discount = models.CharField(max_length=255) amount = models.CharField(max_length=255) status = models.BooleanField(default=False) added_on = models.DateTimeField(auto_now_add=True) objects = models.Manager() and here is my serializer from rest_framework import serializers # Create your serializers here from barakasalessystemApp.models import Farmer, Customer, Bill, Payments, Orders class FarmerSerializer(serializers.ModelSerializer): class Meta: model = Farmer fields = "__all__" class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = "__all__" class OrdersSerializer(serializers.ModelSerializer): class Meta: model = Orders fields = "__all__" def to_representation(self, instance): response = super().to_representation(instance) response["farmer"] = FarmerSerializer(instance.farmer_id).data return response this is my views from functools import partial from django.shortcuts import render from rest_framework import viewsets, … -
how to password protect my site in django
Is is possible to password protect my whole site. I'm new to Django and i want to create a chatroom for a group of friends, but i want to have a password to get into the room. is there any tutorial out there in where i can put a password that anyone can use over my whole site? so far I have a website which can be used to input text but has no verification for passwords. all i've found are complicated tutorials for creating users and managing them. I'm looking for something simple. Thanks. -
How to view my data on the page without reload it and how to post my data on server?
I have a python script on my PC, that takes data from sensors and return it in the list like: [24 25, 32, 56] This data from different 4 sensors. Also i have a server with django site. I want to take data from sensors and display it on my html page without reloading the page. How can i do it? I listened about ajax, maybe you have helpful links to similar problem or lesson. my python-script for taking data from hardware: import serial import time wox = serial.Serial('COM3', 115200,stopbits=1) #Открыли порт while True: #if wox.inWaiting() two_sensors = wox.readline().decode("utf-8") two_sensors = two_sensors.replace("\n","") st_two_sensors = two_sensors.split(",") st_two_sensors[3] = float(st_two_sensors[3])/220000 print(st_two_sensors) temperature_0 = int(st_two_sensors[0]) temperature_1 = int(st_two_sensors[1]) voltage = st_two_sensors[2] Simple html: {% load static %} <html> <head> <meta http-equiv="Content-Type" content="text/html; Charset=UTF-8"> <!--<meta http-equiv="refresh" content="7"> --> <script type="text/javascript" src="{% static '/js/jquery-3.6.0.js' %}"></script> </head> <body> I want to have sensor data here with live updating. </body> </html> beside ajax i listened about web-sockets what would be easier? and where can i find examples Also i intrested how to transmit that data to the server, maybe some url requests?