Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot find images under templates
So I am creating a Django project and put an image on an HTML page. Issue is that the server cannot see it. This is my folder structure: mysite/app/templates/app/img/pic.png The HTML page is in: mysite/app/templates I tried many different scr formats, such as: <img src="../app/img/pic.png"> but it did not work. -
Django: How to take my query out of my for loop
I got the following code, that contains N queries: for qty in total_qty_bought: product_id = qty["product"] quantity = int(qty["quantity__sum"]) try: method_title = ( self.shipment_model.get(order_id=qty["order_id"]) .method_title.replace("Hent-selv", "") .strip() ) To solve the issue I tried to take the method_title query out of the for loop like this: quantity = 0 for qty in total_qty_bought: quantity = int(qty["quantity__sum"]) method_title = ( self.shipment_model.get(order_id=total_qty_bought[0]['order_id']) .method_title.replace("Hent-selv", "") .strip() ) Note! There will be a full refrence further down, to understand the bigger picture The issue in my solution is, that I am hard choosing which dict to enter , as I select [0] before order_id, and not in a for loop like before, would be selecting every individual item in the loop. Is there a more sufficient way to do this? I do not see a solution without the for loop, but django debugger tool tells me it creates 2k+ queries. CODE FOR REFRENCE class InventoryStatusView(LoginRequiredMixin, View): template_name = "lager-status.html" cinnamon_form = CinnamonForm(prefix="cinnamon_form") peber_form = PeberForm(prefix="peber_form") pc_model = InventoryStatus product_model = Product.objects.all() order_item_model = WCOrderItem.objects.all() shipment_model = WCOrderShipment.objects.all() def get(self, request): # Get all added objects that hasn't been deleted objects = self.pc_model.objects.filter(is_deleted=False) # Get all added objects that has been deleted deleted_objects = self.pc_model.objects.filter(is_deleted=True) … -
Is there a way to set initial values in form fields in django in HTML template?
I have a simple Django form: QUANTITY_CHOICES = [(i, str(i)) for i in range (1,11)] class CartAddFoodForm(forms.Form): quantity = forms.TypedChoiceField( choices=QUANTITY_CHOICES, coerce=int, ) override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) and the view: def cart_detail(request): cart = Cart() quantity_update_form = CartAddFoodForm() return render(request, 'cart/cart_detail.html', {'cart': cart, 'quantity_update_form': quantity_update_form}) cart is a model object which has various cart items and I want to add the quantity_update_form for each and every item in cart. So, my HTML file is: <table> <thead> <tr> <th>Item</th> <th>Quantity</th> </tr> </thead> <tbody> {% for item in cart.get_all_items %} {% with product=item.product %} <tr> <td>{{ product.name }}</td> <td> <form action="{% url 'cart:cart_add' food.id %}" method="post"> {{ quantity_update_form.quantity}} {{ quantity_update_form.override}} <input type="submit" value="Update"> {% csrf_token %} </form> </td> </tr> {% endwith %} {% endfor %} </tbody> </table> get_all_items method would return all items in the cart and item.product is the object of Product model class. I want to set {{ quantity_update_form.quantity}} field to item.quantity and {{ quantity_update_form.override|default:True }} field to true. Is there any template tags or filters to do this? -
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine in Django and Paho mqtt
I am using paho MQTT to establish a connection with a mosquitto server on a windows 2012 r2 server. I have used 2 threads one for the main server process and another for establishing a connection with mosquitto server. This is how I am establishing connection to MQTT. mqtt.py file is placed in main project of Django along with manage.py import random client_id = f'python-mqtt-{random.randint(0, 1000)}' def mqtt_connect(): mqtt_connect.client = mqtt.Client(client_id) mqtt_connect.client.on_connect = on_connect mqtt_connect.client.on_message = on_message mqtt_connect.client.on_disconnect = on_disconnect mqtt_connect.client.connect(config("CLIENT_PORT"),1883) mqtt_connect.client.loop_start() and I have initialized the thread in init.py inside the main folder along with settings.py import pymysql pymysql.version_info = (1, 4, 0, "final", 0) pymysql.install_as_MySQLdb() import mqtt import threading x = threading.Thread(target=mqtt.mqtt_connect) x.start() The Django application is running on an apache server. ISSUE: Every time I receive a message from MQTT after certain intervals this error occurs, ln1/lidIntact\r [Tue Apr 27 10:54:54.817976 2021] [wsgi:error] [pid 72980:tid 1532] <paho.mqtt.client.MQTTMessage object at 0x000000CC2B07DBC8>\r [Tue Apr 27 10:54:54.817976 2021] [wsgi:error] [pid 72980:tid 1532] ['ln1', 'lidIntact']\r [Tue Apr 27 10:54:54.864827 2021] [wsgi:error] [pid 72980:tid 1532] Exception in thread Thread-2:\r [Tue Apr 27 10:54:54.864827 2021] [wsgi:error] [pid 72980:tid 1532] Traceback (most recent call last):\r [Tue Apr 27 10:54:54.864827 2021] [wsgi:error] [pid 72980:tid 1532] … -
How to create a link preview of a django website?
I read about the OpenGraph but still did not fully understand, tell me how I can implement this for my blog in django so that all article links have different previews, I roughly understand how to do this using the {% post.title%} and {% post.image%}tags, but what about url? -
.is_valid() method but is not validating when ajax used
when i used ajax in my project the form.is_valid() method not validating the form. it showing the 'this field required error' but i access that using request.POST means i fill all the fields. ''' this is html code which render the django model form ##HTML FORM## <form action="" method="post" enctype="multipart/form-data" id="reception_form" novalidate> {% csrf_token %} {% for field1 in form1 %} <label for="{{field1.id_for_label}}"> {{field1.label}} </label> {{field1}} <div> {% if field1.errors %}{% for error in field1.errors %} <small class="errorlist">{{error}}</small> {% endfor %}{% endif %} </div> {% endfor %} {% for field2 in reception %} {% if field2.name != 'gender' %} <label for=" {{field2.id_for_label}} "> {{field2.label}} </label> {{field2}} <div> {% if field2.errors %}{% for error in field2.errors %} <small class="errorlist">{{error}}</small> {% endfor %}{% endif %} </div> {% endif %} {% endfor %} {% for radiofield in reception.gender %} {{radiofield.tag}} <label for=" {{radiofield.id_for_label}} "> {{radiofield.choice_label}} </label> <br> {% endfor %} <input type="submit" value="Add Reception" name="Add Reception" class="btn btn-secondary mb-3" > </form> ---------- ajax which has post method ## Ajax ## $('#reception_form').submit(function(e){ console.log(" submit pressed") e.preventDefault(); let Rnm = $('#id_username').val(); let Rfnm = $('#id_first_name').val(); let Rlnm = $('#id_last_name').val(); let Rem = $('#id_email').val(); let Rpwd = $('#id_password1').val(); let Rmob = $('#id_mob_no').val(); let Rcty= $('#id_city').val(); let … -
Django model validator using reference from Foreign Key
I was building models from a LED Strip application based in django. First of all, I have two base models, Strip and Zone, every Strip could have many zones. The Strip model has a field called max_led_number which represents the maximum number of LEDs in the strip. And the Zone model has two fields called initial_led and final_led which represents what its names says. In the validators attributes of the initial_led and final_led fields I added the MaxValueIndicator and MinValueIndicator, which works well if I gave them an integer value, but I tried to do is to pass the max_led_number to the MaxValueIndicator value as a method of validation. These are my models. class Strip(models.Model): name = models.CharField(blank=False, null=False,unique=False, max_length=250) serial_port_name = models.CharField(blank=False, null=False,unique=True, max_length=250) status = models.BooleanField(blank=False, null=False, default=False) max_led_number = models.IntegerField(default=300) def __str__(self): return(str(self.name)) class Zone(models.Model): position = models.IntegerField(blank=False, null=False, default=0, unique=False) strip = models.ForeignKey(Strip, on_delete=models.CASCADE) status = models.BooleanField(blank=False, null=False, default=False) initial_led = models.IntegerField(default=0,validators=[MaxValueValidator(strip.max_led_number), MinValueValidator(0)]) final_led = models.IntegerField(default=0,validators=[MaxValueValidator(strip.max_led_number), MinValueValidator(0)]) mode_choices = [(1,'Fixed color'),(2,'Rainbow'),(3,'Color theatre'),(4,'Rainbow theatre'),(5,'Meteor rain'),(6,'Meteor rain - Trigger')] mode = models.IntegerField(choices=mode_choices,default=0) color = models.CharField(blank=False, null=False,unique=False, default="#FFFFFF", max_length=7) def __str__(self): return("Zone " + str(self.position)) But I receive this error. File "/home/pi/ledcontroller/LEDControllerApp/models.py", line 49, in Zone initial_led = models.IntegerField(default=0,validators=[MaxValueValidator(strip.max_led_number), … -
Rendering a response from request.GET as an iframe
I have a Django view which I need to run a HTTP POST request to a Web application's URL with some parameters, then display the response in an iframe. I have implemented the following code: def auth_view(request): SOME_URL = "SOME URL" data = {"some key": "some value",} response = requests.post(SOME_URL , data=data) context = {'content': response.content.decode("utf-8")} return TemplateResponse(request, template="portal/return_view.html", context=context) For return_view.html, it just looks like this: {{ content | safe }} This is not important, but in case it is The html that the iframe runs on looks like this: <body onload="document.form1.submit()"> <h1>This is the iframe view</h1> <!-- If want to test against development --> <form action="some_url_to_start" method="post" target="tool_content" name="form1"> <input type="hidden" name="some_param" id="some_param" value="{{ some_value }}"> <button type="submit"> Launch iframeTool </button> </form> <iframe src="about:blank" width="700" height="600" name="tool_content" id="tool_content" title="Tool Content" ></iframe> </body> The issue is that the return page renders properly, which looks something like this: enter image description here Question: The links which are inside of the rendered iframe page is relative, yet when clicked, will take on the base url of the parent app. Is there a way for the rendered content to take on its own source base url? Second question: The underlying iframe app … -
Url format in stripe checkout session
I can't perform checkout session, probably because of wrong format of the url. How should I format url to enable redirection to payment stripe page? @login_required def checkout(request): try: if request.user.customer.membership: return redirect('settings') except Customer.DoesNotExist: pass if request.method == 'POST': pass else: membership = 'monthly' final_dollar = 10 membership_id = 'price_1IkjAAHziP1k1SzvFKdNwo3h' if request.method == 'GET' and 'membership' in request.GET: if request.GET['membership'] == 'yearly': membership = 'yearly' membership_id = 'price_1IkjAAHziP1k1Szv9v3TxSHn' final_dollar = 100 # Create Strip Checkout session = stripe.checkout.Session.create( payment_method_types=['card'], customer_email = request.user.email, line_items=[{ 'price': membership_id, 'quantity': 1, }], mode='subscription', allow_promotion_codes=True, success_url='http://domainname.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://domianname.visyrelax.com/cancel', -
Djano ORM datetime filter
I have a simple query where I retrieve all the rows from the current date's 12 AM to current time. time_now = datetime.now() time_passed = time_now.hour * 60 + time_now.minute a = (datetime.now() - timedelta(minutes=time_passed)).strftime('%Y-%m-%d %H:%M:%S') b = datetime.now().strftime('%Y-%m-%d %H:%M:%S') result_inwardCount = MYmsEvents.objects.all().filter(recorded_at__range=[a, b],event='In-ward') print(result_inwardCount.query) print(len(result_inwardCount)) Now when I print the query, it gives me this : SELECT "m_yms_events"."id", "m_yms_events"."vin", "m_yms_events"."event", "m_yms_events"."location", "m_yms_events"."recorded_at", "m_yms_events"."sys_id", "m_yms_events"."x", "m_yms_events"."y", "m_yms_events"."last_updated" FROM "m_yms_events" WHERE ("m_yms_events"."event" = In-ward AND "m_yms_events"."recorded_at" BETWEEN 2021-05-19 00:00:37+05:30 AND 2021-05-19 16:49:37+05:30) This gives me 0 results. When I run the same query in pgAdmin it gives me 41 rows. Below is the query after adding the apostrophie : SELECT "m_yms_events"."id", "m_yms_events"."vin", "m_yms_events"."event", "m_yms_events"."location", "m_yms_events"."recorded_at", "m_yms_events"."sys_id", "m_yms_events"."x", "m_yms_events"."y", "m_yms_events"."last_updated" FROM "m_yms_events" WHERE ("m_yms_events"."event" = 'In-ward' AND "m_yms_events"."recorded_at" BETWEEN '2021-05-19 00:00:37+05:30' AND '2021-05-19 16:49:37+05:30') The timezone in Postgres is IST, so is the timezone on to the server. -
Django-q Scheduled tasks not running properly
I am using Django-q schedulers to create scheduled task to run on every weekend. But whenever i am running my python development server and qcluster we are encountered with two issues-: i) creating two tasks entries in django_q_schedule model after running development server and qucluster ii) Instead on executing on the scheduled time, the scheduler executes its task immediately as qcluster starts then changes its next_run() time to the weekend time. Following is the code snippet i am using -: # Django-Q Cluster Q_CLUSTER = { 'name': 'Name', 'max_attempts': 1, 'retry': 14400, 'orm': 'default' } In my models.py -: from django_q.models import Schedule Schedule.objects.create(func='func()', schedule_type=Schedule.CRON, repeats=-1, cron='25 23 * * 6' ) Please help if anyone having any idea...... Thanks in advance. -
Django Nested Serializer - Understanding why two similar but different approaches have major performance difference
I am trying to use Nested Serializers by two approaches, however both the approaches have a major performance difference even though they have the same number of SQL queries to the database and are similar. I want to understand why this is happening Note I have used a DynamicFieldsModelSerializer to serialise only the necessary fields class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be serialized. Increases speed as you can omit fields that are not needed to be serialized """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) Approach 1 Serializer class Std_Mast_Serializer(DynamicFieldsModelSerializer): item_mast = Item_Mast_Serializer(fields=['id','code','name','pkg','rate','print_order']) installation_mast = Installation_Mast_Serializer(fields=['id','name_short','name_long']) class Meta: model = Std_Mast fields = '__all__' Django Silk - Performance Approach 2 Custom Related Field class NestedField(serializers.RelatedField): def __init__(self, **kwargs): self.serializer = kwargs.pop('serializer', None) self.serializer_fields = kwargs.pop('fields', None) if self.serializer is not None and not issubclass(self.serializer, serializers.Serializer): raise TypeError(f'{self.serializer} is not a valid serializer … -
How to upload a file with lowercase columns in django
I have an upload thro' django-import-export. I have a department column for whose values I'd like to be converted to lowercase. I can't figure out how to do this. Please assist if you can. Here is the view for uploading the file. class uploadBooks(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadBooksForm() self.context['form'] = form return render(request,'libman/upload_books.html',self.context) def post(self, request): school_id = request.user.school.id#Gets the currently logged in user form = UploadBooksForm(request.POST , request.FILES) data_set = Dataset(school = request.user.school) if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportBooksResource(school_id)#Imports for the logged in user's school if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,f'Errors experienced during import.') print("error", result.invalid_rows) self.context['result'] = result return redirect('upload_books') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Books uploaded successfully.') else: self.context['form'] = UploadBooksForm() return render(request, 'libman/upload_books.html', self.context) -
How to handle the rollback of transaction atomic if the transaction fails
Hey i have this following transaction atomic insert query i want to delete the instance of Check Model on the rollback of this atomic transaction from django.dispatch import receiver from django.db.models.signals import post_save from check.models import Check, CheckSheet from django.db import transaction @receiver(post_save, sender=Check) @transaction.atomic def create_checksheets(sender, instance, created, **kwargs): if created: start_number = instance.start_number sheet_count = instance.sheet_count for i in range(sheet_count): check_sheet = CheckSheet.objects.create( batch_check_id=instance.pk, check_number=start_number+i ) -
is postgresql + solr a good idea for a web crawler + search engine?
I am building something like a search engine, with django. The webscraping part is handled by scrapy, with broad web crawlers running in parallel. They normalize the urls found and extract keywords from webpages, before storing them into a postgresql database. Postgres has excellent support from django. In order to actually handle the "searching" part, I am using apache solr to build indexes and efficiently retrieve data. Are there any downsides to this approach? Implementing nosql is going to be very hard, because django does not natively support nosql (except for mongodb which has third party support). What are my options? Can I use postgres or would I need to change my tools? The data collected by the crawler is expected to increase a lot as time progresses - there is no hard limit. The crawler indexes the open web. -
is there any way to use cryptography in web application
I want to develop web application which implies cryptography. can I apply cryptography algorithms like AES, DES, RSA techniques for encryption and decryption on web project? If yes what technologies should I use? -
Django CustomUser make emailfield a reference
In my Django application, I have a Person object and a User object. All of my Persons have e-mail addresses, but not all of them are also Users. Therefore, I'd like to not copy myself by adding an email field to my User model that simply contains the same as User.person.email, and I'd rather have it so that when User.email is called, it tunnels to User.person.email. I was wondering if there was a simple solution to this that I haven't found yet, that also works for authentication, for example. I've tried setting EMAIL_FIELD and USERNAME_FIELD to 'person.email', which doesn't work, and I've tried setting a property like such: @property def email(self): return self.person.email None of these worked for me. -
Django FileField store Keras .h5 file
I am trying to store a trained Keras model within a Django model FileField. Since Keras is not pickleable, I used the .h5 file format (https://www.tensorflow.org/guide/keras/save_and_serialize) to store the keras model. So basically just: kerasmodel.save('temp.h5') dat = open('temp.h5', mode='r') myFile = File(dat) mymodel.content.save('test', myFile) mymodel.content is the Django model FileField This causes the error: UnicodeDecodeError at /model/ 'charmap' codec can't decode byte 0x90 in position 1928: character maps to "undefined" I really dont care if Django can read this file or not, I just want to save it for later purposes. Since I can easily upload the file manually via the Django admin page to the model, it should be feasible. Thanks in advance -
The current URL didn't match any of these
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres dbi5k: image: postgres volumes: - ./data/dbi5k:/var/lib/postgresql/data environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } and $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_i5k', 'USER': 'django', 'PASSWORD': 'postgres', 'HOST': 'dbi5k', 'PORT': '5432', } } Please below the logs Attaching to djangoblast_dbik_1, djangoblast_db_1, djangoblast_web_1 dbik_1 | db_1 | dbik_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization dbik_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 … -
Django password reset link does not work - "A {% csrf_token %} was used in a template, but the context did not provide the value"
I am trying to implement the built-in password reset function from Django. I have implemented a microsoft authenticator and have succesfully managed to get my website to send a password reset email. However, when I click the link in the password reset email, my website automatically disconnects. In the error log, I get the following message: /usr/lib/python3.7/site-packages/django/template/defaulttags.py:63: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. urls.py path('admin/', admin.site.urls), path('', include('myapp.urls')), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_reset_form/', auth_views.PasswordResetView.as_view(), name='password_reset_form'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')), password_reset_email.html {% csrf_token %} Someone asked for password reset for email {{ email }}. Follow the link below: {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} password_reset_confirm.html {% block content %} {% csrf_token %} {% if validlink %} <p>Please enter (and confirm) your new password.</p> <form action="" method="post"> {% csrf_token %} <table> <tr> <td>{{ form.new_password1.errors }} <label for="id_new_password1">New password:</label></td> <td>{{ form.new_password1 }}</td> </tr> <tr> <td>{{ form.new_password2.errors }} <label for="id_new_password2">Confirm password:</label></td> <td>{{ form.new_password2 }}</td> </tr> <tr> <td></td> <td><input type="submit" value="Change my password" /></td> </tr> </table> … -
JSON file upload in Django without saving
I want to upload, process and discard a JSON file without saving it in a database. views.py parser_classes(['FileUploadParser']) @api_view(['POST']) def upload_file(request): file = request.FILES.get('file') # process the file return JsonResponse('status':'successful') urls.py urlpatterns = [ path('api/upload_file/', views.upload_file), ] I am setting the header as Content-Type: multipart/form-data Then it is showing the error "Multipart form parse error - Invalid boundary in multipart: None" What is the correct way of uploading a JSON file in DRF ? Python version : 3.6.9 Django version : 3.2.3 -
Why “accounts/login/?next=/” is coming in url of Django on local development server ? | Way to remove “accounts/login/?next=/” from the url
Why “accounts/login/?next=/” is coming in url of Django on local development server ? | Way to remove “accounts/login/?next=/” from the url . I have used class based views and used LoginRequiredMixin. Can anyone tell me why the path changes from /login to accounts/login/?next=/ path('login/', CustomLoginView.as_view(), name='login'), -
How to get tasks id of Django Periodic Task Object [django-celery-beat]
I'm new using Django and celery. I'm using django admin panel to launch the task directly by selecting each individual PeriodicTask model object. I need to get the ID of the task selected. enter image description here I have something like this: from django_celery_beat.models import PeriodicTask get_task = PeriodicTask.objects.get(id=[NumericID]) -
nginx django gunicorn 404 static file not loading
I have been trying to solve this error for almost 13 hours, looking for thousands of stackoverflow questions and questions of other communities but I still can't find the answer. What I'm trying to do is solve nginx not serving static files. as I said on the top, I tried thousands of answers and none of them seem to work for me. I post only the scripts in nginx /sites-available/ because I think that is the primary script for this question. server { listen 80; server_name localhost 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static { autoindex on; alias /home/ngx/pid/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I use gunicorn for loading django and also the frontend is made with react so without main.js I can't do anything. ngx is not a default user - I made it and also I followed this DigitalOcean tutorial.(Although I didn't follow all of them - I edited after reading answers by other people. Directory /home/ngx/pid (django root) ㄴ diary (project root - settings.py, wsgi.py etc.) ㄴ djenv (virtualenv) ㄴ frontend (react) ㄴ manage.py ㄴ static (made by python3 manage.py collectstatic) Error URL: http://example.com/static/css/index.css http://example.com/static/frontend/main.js <- React … -
How to annotate a Django QuerySet with a custom Function?
I need to annotate a queryset using a custom function agr_suitable_code on a model field. which looks like this def strip_accents(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') def agr_suitable_code(on_distro_code): upper_str = on_distro_code.upper() return strip_accents(upper_str) nothing special here, the function takes a string and returns it with some changes. Then I try to annotate with it as the following query cannot be achieved without this agr_like_code annotated field. related_params[distro.id] = table.objects.filter( ProductId__in=[map["ProductId"] for map in related_maps_by_distro.values("ProductId")] ).annotate( agr_like_code=Func(F("DistributionParameterId__Code"), function=agr_suitable_code), prod_to_param_exists= Exists(AgrDistributionProductParameter.objects.filter(ProductId=context['product'], DistributionParameterId__Code=OuterRef( "agr_like_code")).values('id')), has_agr_param=Case( When(Q(agr_like_code__in=agr_parameter_codes) & Q(DistributionParameterId__Code__in=agr_param_map_codes_distro) , then=2), When(Q(agr_like_code__in=agr_parameter_codes), then=1), default=0, output_field=models.IntegerField(), etc .. I have tried to formulate this line agr_like_code=Func(F("DistributionParameterId__Code"), function=agr_suitable_code) in many ways but with no success. The current error I'm receiving is django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '<'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '<'. (102); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '<'. (102); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '<'. (102); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") I know about Django documentation suggesting writing custom SQL query like class ConcatPair(Func): ... function …