Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nested function working but returning messages in Django
I have a function called inside another one. The functions are working properly but, while using a validator to raise some error in case of wrong entries by the users, the validator works but is calling either the success and the error message. I post some code for better explanation. utils.py def add_flight_function(request): try: aircraft_maintenance_type = AircraftMaintenanceType.objects.first() except: aircraft_maintenance_type = None aircraft = request.POST.get('aircraft') adep = request.POST.get('adep') ades = request.POST.get('ades') date = request.POST.get('date') atd = request.POST.get('atd') ata = request.POST.get('ata') function_type_obj = request.POST.get('function_type') function_type_obj = FunctionType.objects.get(id=function_type_obj) operational_condition = request.POST.get('operational_condition') student = request.POST.get('student') instructor = request.POST.get('instructor') night = request.POST.get('night') note = request.POST.get('note') aircraft_type = Aircraft.objects.get( id=aircraft).aircraft_type.abbreviation if aircraft_maintenance_type.is_tacho == True: atd_tacho = request.POST.get('atd_tacho') ata_tacho = request.POST.get('ata_tacho') if float(ata_tacho) <= float(atd_tacho): messages.error( request, "ATA Tacho cannot be lower than ATD Tacho") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) is_valid_flight, error_message = flight_validator( request, ata, atd, function_type_obj.name, instructor) if not is_valid_flight: messages.error(request, error_message) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: is_valid_flight, error_message = flight_validator( request, ata, atd, function_type_obj.name, instructor) if not is_valid_flight: messages.error(request, error_message) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) log_entry = LogEntry.objects.create(aircraft_id=aircraft, adep_id=adep, ades_id=ades, date=date, atd=atd, ata=ata, function_type_id=function_type_obj.id, student_id=student, instructor_id=instructor, operational_condition_id=operational_condition, note=note) if night == 'on': log_entry.night_flight = True # if function_type_obj.name == 'Dual Command': # instructor_flight_payment = InstructorFlightPayment(log_entry=log_entry, instructor_id=instructor) # instructor_flight_payment.save() if function_type_obj.name == 'Single … -
Div spacing issue
I would like the lines to be much closer to each other, but margin and height are not working <h4>TITLE:</h4> <div style="width: 290px; display: table-cell;"> <h4>AAA</h4> </div> <div style="display: table-cell;"> <h4>€ 123</h4> </div> <br> <div style="width: 290px; display: table-cell;"> <h4>BBB</h4> </div> <div style="display: table-cell;"> <h4>€ 123</h4> </div> Result: There is almost a full line size between AAA and BBB. That's the issue. -
Are there "N + 1 problems" in "formfield_for_foreignkey()"? (Django)
I overrided formfield_for_foreignkey() to display the combination text of foreign key and its parent to Django Admin as shown below: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): formfield = super().formfield_for_foreignkey(db_field, request, **kwargs) if db_field.name == "my_field": formfield.label_from_instance = lambda obj: f'{obj} ({obj.my_parent})' return formfield Then, with "print()", I checked how many time "formfield_for_foreignkey()" and "if block" in "formfield_for_foreignkey()" are called as shown below: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): formfield = super().formfield_for_foreignkey(db_field, request, **kwargs) print("formfield_for_foreignkey") # Called "18 times" if db_field.name == "my_field": print("if block") # Called "9 times" formfield.label_from_instance = lambda obj: f'{obj} ({obj.my_parent})' return formfield As a result, print("formfield_for_foreignkey") is called 18 times which means "formfield_for_foreignkey()" is called 18 times. And print("if block") is called 9 times which means "if block" in "formfield_for_foreignkey()" is called 9 times. My questions: Is it "N + 1 problem" that: "formfield_for_foreignkey()" itself is called 18 times? "if block" itself is called 9 times? "{obj}" in "if block" is called 9 times? "{obj.my_parent}" in "if block" is called 9 times? -
pass parameters to an modal django?
I'm starting to program with python and django. I'm trying to implement the modal in my web page. I have already achieved the implementation of modals for the creation of objects, but I have a problem updating or deleting, since they require sending a parameter. total_alumnos.html <div class="table-responsive"> <h5>Alumos de Secundaria</h5> <form method="get" class="forms-sample"> <label for="as" >Apellido Paterno:&nbsp;</label>{{filtro.form.apellido_p}} <button class="btn btn-info" type="submit"><i class="fa-solid fa-magnifying-glass"></i>&nbsp; Buscar</button> </form> <br> <table style="text-align:center;" class="table table-bordered table-striped table-contextual "> <tr class="table-info"> <th>Usuario</th> <th>Nombre</th> <th>Apellidos</th> <th>Correo</th> <th>Grado</th> <th>Año</th> <th>Salon</th> <th>Asignar</th> </tr> {% for alumno in alumno %} <tr> <td class="py-1"> <img src="{{alumno.profile_pic.url}}" alt="image" /> </td> <td>{{alumno.nombre }}</td> <td>{{alumno.apellido_p }} {{ alumno.apellido_m }}</td> <td>{{alumno.email }}</td> <td>{{alumno.aula.grado }}</td> <td>{{alumno.aula.año }}</td> <td>{{alumno.aula.salon }}</td> <td><a class="btn btn-sm btn-info btn-rounded" href="{% url 'asignar_alumno' alumno.id %}" ><i class="fa-solid fa-circle-plus"></i>&nbsp;Asignar</a></td> <td><button type="button" data-bs-toggle="modal" data-bs-target="#asignarModal" class="btn btn-info" ><i class="fa-solid fa-circle-plus"></i>Asignar</button></i></td> </tr> {% endfor %} </table> asignar_alumno.html <div class="modal fade" id="asignarModal" tabindex="-1" role="dialog" aria-labelledby="asignarModal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Agregar Curso</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method='POST'action="" enctype="multipart/form-data" > {% csrf_token %} <div class="modal-body"> {{aula_form.aula}} </div> <div class="modal-footer"> <a class="btn btn-warning" href="{% url 'total_alumnos' %}">Cancelar</a> <input class="btn btn-primary" type="submit" name="Submit" value="Asignar Aula"> </div> </form> </div> </div> … -
Create a history record in Django for every UPDATE of a class instance
I have a model in Django that is used to create an item of stock class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='item') amount = models.IntegerField(default=0, blank=False) place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='place') issue_amount = models.IntegerField(default=0, blank=True) receive_amount = models.IntegerField(default=0, blank=True) The item amount will be updated everytime an item is issued by adding or subtracting the issue or receive amount in a views function that alters the instance amount and calls save on that instance. I want to be able to keep a record of every update and make this information available to both my frontend and to an admin model. I found this tutorial in which the poster creates a separate model with the same field values as Item and then writes SQL commands directly to the database to create a TRIGGER that saves each Item field on every update: https://www.youtube.com/watch?v=d26DUXynf8s Is there a way I can replicate this same behaviour using Django? -
Django query_set order_by default field if ordering field is an empty string
I have a query_set that I want to order by Lower('title'). However, for some elements, title is blank (blank=True). So, when I sort, those elements are rightfully are on top. However, all elements, no matter what, have a default_title. So, I want to use an element's default_title in the sorting if title is blank. -
how to connect my project with zoho books via api in Django
I was trying to integrate my Django project ZohoBooks via API. So I got stuck while generating the AuthToken or Code. how to create an invoice on Zoho books automatically, when the Order objects are created in my Django project. please help!!!! thanks in advance -
Django Celery Redis
I have this error A rediss:// URL must have parameter ssl_cert_reqs and this must be set to CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE settings CELERY_BROKER_URL = os.environ.get('REDIS_URL', "redis://localhost:6379") CELERY_RESULT_BACKEND = os.environ.get('REDIS_URL', "redis://localhost:6379") CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py from __future__ import absolute_import, unicode_literals from celery import Celery import os, ssl os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings') app = Celery( 'myproj', broker_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }) app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() I changed the value of ssl_cert_reqs to different value 'none', 'cert_required', ..., but nothing, always the same error when I use rediss:// instead of redis://. -
How do I access exception traceback during graphene-django request?
I'm using graphene-django v2.15.0 because that's the latest stable release, which pulls in graphene v2.1.9. Any time an exception is raised during a graphql request, all I get to see is the HTTP response body which looks something like: {"errors":[{"message":"this is my exception","locations":[{"line":1,"column":3}],"path":["hello"]}],"data":{"hello":null}} Just the message, not the traceback, and some useless location information that has nothing to do with the cause. I've spent an hour googling things like "graphene-django errors traceback", and I found tons of results - but all of them were people trying to silence errors and tracebacks, not access them! Am I in the wrong timeline? Did I get Mandela'd? What the hell is going on? BTW - I already tried the following based on a suggestion I found, but it had zero effect on behavior, either in the response or in the console where I have ./manage.py runserver going. import logging ; logging.getLogger("graphql.execution.utils").setLevel(logging.DEBUG) I've also tried looking through graphene and graphene-django docs for settings to flip with no success. -
Get data from second api call based on data coming from the first api (python/django)
I am making a simple web application in pycharm (python/django) that displays data that it picks up from growstuff.org. The main page displays all the crops based on what it finds on growstuff.org/crops.json like the plant's name,scientific name and description. However, info of the plants themselves (like spread,height,days to harvest,sun requirements) are contained in growstuf.org/crops/ID.json. I have already managed to get the data from crops.json and display it on the website,however i can't combine the two files to display the full info i need. How can I make the second call based on the first one's data? views.py apidata = requests.get('https://www.growstuff.org/crops').json() #cropdata = requests.get(f"https://www.growstuff.org/crops/{}.json").json() return render(request, 'index.html', {'apidata':apidata}) index.html <table Width="70%" Height="180px"> <thead> <tr style="font-family:asul; "> <td>Crop</td> <td>Name</td> <td>Scientific Name</td> <td>Description</td> <td>Suniness</td> <td>Companions</td> </tr> </thead> <tbody id="myTable"> {% for i in apidata %} <tr> <td><img src="{{i.thumbnail_url}}" style=" border: 1px solid #ddd; border-radius: 4px; padding: 5px; width: 150px;"></td> <td><h4>{{i.name}}</h4></td> <td><h4>{{i.scientific_name}}</h4></td> <td><h4>"{{i.description}}"</h4></td> {% for j in cropdata %} <td><h4>{{i.j.sun_requirements}}</h4></td> <td><h4>{{i.j.relationships}}</h4></td> {% endfor %} </tr> {% endfor %} </tbody> </table> -
orator migrate command not working in django
When i'm running orator migrate command then with giving config path like orator migrate -c db.py Then the result is comming Command Cancelled! I have installed orator in django Orato 0.9 Python 3.9.7 django 4.0.5 I create a migration and model in the mean project that you can see my code and set the connection but when I'm running migrate command db connection from orator import DatabaseManager, Schema import environ env = environ.Env() environ.Env.read_env() databases = { 'mysql': { 'driver': 'mysql', 'host': 'localhost', 'database': env('DB_DATABASE'), 'user': env('DB_USERNAME'), 'password': env('DB_PASSWORD'), 'prefix': '' } } db = DatabaseManager(databases) schema = Schema(db) migration file from orator.migrations import Migration class CreateProductsable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('products') as table: table.increments('id') table.integer('category_id').unsigned() table.timestamps() table.foreign('category_id').references('id').on('jobs').on_delete('cascade') def down(self): """ Revert the migrations. """ self.schema.drop('products') model file class Product(Model): __table__ = 'products' -
Django adding new courses by users in Learning Management System app from UI
On my app, I can add new courses from Django Admin Panel Only by using the model in Django Admin Panel. Picture 1 - Django Admin Panel Picture 2 - Adding New Course from Admin Panel I want to automate this whole process. I want to create a form where users can fill out the form and submit their Course using UI. And That course will automatically be added to the Courses. So, to achieve my goal, what are the necessary steps I should take? For a better understanding of my problem here is the GitHub repo link to my project. GitHub Repo of My Project -
Django view to download a file from server
I have a views.py that: creates some .xlsx files select the correct .zip and place the file inside After that, I want this .zip to be automatically downloaded. I did some research and tested some codes but none worked. I created a "temp" folder in the root of the app where the created files are stored. simplified view.py def generate_ws(request,cource,ca_id): ca = get_object_or_404(CreditAnalysis,pk=ca_id) ca_owners = CAOwner.objects.filter(ca_operation=ca) mo_farms = MOFarm.objects.filter(ca_operation=ca) misses = [] generate_owner_mo(ca_owner,misses,city) zip_name = 'temp/MOs - ' + str(ca_owner.owner) + '.zip' zf = zipfile.ZipFile(zip_name,'w') zf.close() generate_farm_mo(mo_farm,misses,city) generate_production_mo(ca,misses,city,production_city,pks) files = glob.glob('temp/*.xlsx') for file in files: file_key = file.split('.')[0] file_key=file_key.split(' - ') for ca_owner in ca_owners: zip_name = 'temp/MOs - ' + str(ca_owner.owner) + '.zip' if str(ca_owner.owner) in file_key: zf = zipfile.ZipFile(zip_name,'a') new_file_name = file[5:] zf.write(file,new_file_name) zf.close() break for file in files: if file[5:8]=='MOs': download_mo(request,file) misses = list(set(misses)) return render(request,'generate_mo.html',{'misses':misses,}) download_mo def download_mo(request,file): path_to_file = os.path.realpath(file) with open(path_to_file,'rb') as fh: response = HttpResponse(fh.read()) file_name = file[5:] response['Content-Disposition'] = 'inline; filename=' + file_name return response Everything works correctly except the download which never starts -
How to use opencv-python for Java blob in Django
I'm building a Django website. My users can record a video and then others can see these videos. The recording is done with javascript: const mimeType = 'video/mp4'; shouldStop = false; const constraints = { audio: { echoCancellation: true, noiseSuppression: true, }, // audio: true, video: { width: 480, height: 480, facingMode: 'user', }, }; const stream = await navigator.mediaDevices.getUserMedia(constraints); const blob = new Blob(recordedChunks, { type: mimeType }); And the sent to a django view: let response = await fetch("/send-video/", { method: "post", body: blob, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', "X-CSRFToken":csrftoken, }, }).then( ... ) In my views if request.method == 'POST': user = request.user file_name = f"{user}.mp4" if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'): file_path = file_name else: file_path = f"{your_media_root}temp/{file_name}" webm_bytes = bytes(request.body) video_file = open(file_path, "wb") video_file.write(webm_bytes) if mimetypes.guess_type(file_path)[0].startswith('video/mp4'): print(mimetypes.guess_type(file_path)) video_file.close() else: video_file.write(b"") video_file.close() I like to understand how I can use opencv-python instead of raw file saving. How can I implement this ? -
Handling different SSO implementations in Django webapp
I am not very experienced in SSO so please forgive me if my question sounds silly. I have a Django webapp which currently uses the embedded model-based Django authentication. This application of mine is meant to work in different companies where different authentication/authorization systems are used (Microsoft AD, Google, Oracle, etc.). So I want to implement SSO in my webapp but without knowing which implementation will be used. My question would be if there is a Python SSO library that can handle different SSO implementations? Naturally that would be fine if there were separate config parameters per SSO engine. Or do I have to use different libraries per SSO implementations? Thank you! -
Django Postgres makemigrations only Autofield at 0001_initial.py
Python 3.10.4 Django 4.0.5 PostgreSQL 14 When I start "python manage.py makemigrations" i got the file "0001_initial.py" but all Fields, except autofields, are missing. models.py from django.db import models # Create your models here. class Username(models.Model): #id = models.AutoField(primary_key=True) username: models.CharField(max_length=100) class Carrier(models.Model): #id = models.AutoField(primary_key=True) carriername: models.CharField(max_length=100) desc: models.TextField() 0001_initial.py # Generated by Django 4.0.5 on 2022-06-29 13:18 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Carrier', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Username', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] -
Mysql-python for upgraded Django
I'm upgrading a system from Django 1.11.16 Debian 9.6 Python 2.7.13 mysql-server 5.5.9999+default to Django 4.0.5 Debian 11.1 Python 3.9.2 mariadb-server 10.5.15 . My plan is to make a dump from the existing database and use it in the new server within the very new, upgraded environment. With Django 1.11.16 I used MySQL-python==1.2.5 as a connector to the database. My question is what package with what version do You advise to use for the same purpose with the given set of versions? -
Not all stylesheets are loaded
There are 2 stylesheets. One is under the project folder (created for base.html) and another is inside the app folder (for applist.html). collectstatic command did collect both the stylesheets and put inside the STATIC_ROOT folder 'assets'. But when runserver is on, the app's stylesheet isn't loaded only the base.html's stylesheet got loaded and working. base.html {% load static %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> {% block title %} {% endblock %} </title> <!-- Add additional CSS in static file --> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> </head> <body> {% block content %}{% endblock %} </body> </html> applist.html <!DOCTYPE html> {% extends "base.html" %} <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> {% load static %} <meta charset="utf-8" /> <title>List</title> <!-- Add additional CSS in static file --> <link rel="stylesheet" type="text/css" href="{% static 'css/dstyles.css' %}"> </head> {% block content %} <body> <h2>Testing for stylesheet linking</h2> </body> {% endblock content %} </html> folder structure is like, Dev_ static css styles.css app static css dstyles.css assets static css styles.css dstyles.css The base.html's styles are working whereas app's stylesheet is not working. I did F12 and checked to see only style.css got loaded and dstyles.css didn't appear. attaching … -
Connecting Django on Ubuntu EC2 to AWS RDS MySQL: pymysql tries to connect to localhost instead of foreign server
I am in the process of deploying a Django project on an Ubuntu EC2. It should connect to a MySQL server on AWS RDS. The project works fine on the built-in Django development server you start with runserver and it also connects to the RDS instance properly there. However, if I try running it in production, it throws a 500 Internal Server Error that creates the following output in the error log: mod_wsgi (pid=18656): Exception occurred processing WSGI script '/home/ubuntu/mysite/mysite/wsgi.py'. Traceback (most recent call last): File "/home/ubuntu/mysite/mysite_venv/lib/python3.8/site-packages/pymysql/connections.py", line 613, in connect sock = socket.create_connection( File "/usr/lib/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: ... pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") This socket error occurs both with my custom views and with the mydomain.com/admin view. The relevant snippet of views.py looks like this: # get environment variables db_host = os.environ.get('DB_HOST') db_user = os.environ.get('DB_USER') db_pass = os.environ.get('DB_PASS') # connect to db conn = pymysql.connect(host=db_host, user=db_user, password=db_pass) c = conn.cursor() c.execute('''USE mysitedatabase''') The file is generally executed properly, log statements I inserted as a test before … -
Outlook office 365 mail SMTP email authentication doesn't work in django?
django settings config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@outlook.com' EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_USE_TLS = True EMAIL_USE_SSL = False it shows error smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful [BM1P287CA0013.INDP287.PROD.OUTLOOK.COM]') -
Python Django - Making changes to Model
So I had a model with fields which was in use. Now, I removed some fields from original model and created their own model and linked this new model with the original model using some constraint. Now, when I add new instances, they are being added. But how to handle instances which are already in database before changes were made. Can add more information if required or some confusion is there. Thanks. -
Want to save returned value or printed value of another python file in postgresql's existing table of a specific column.from django file DB created
I have the smtp mailing code in smtp.py file with following below code. In the field "number_of_emails_sent in (models.py).At the beginning when the user will post his details that field will be empty as default. But when we start our process to implement the smtp.py file it(number_of_emails_sent in database) should be appended each time we run the code for the specific user with his details. For example there are 3 users["king","queen","soldier"], when they post at the first time he has fields in api like {"user_email" :"King@gmail.com", "password":"1587687", "SMTP_PORT" :" 078", "SMTP_HOST" : "025", "Is_Active" :"True", "subject" : "Hi", "Body" : "How are you", "Number_of_emails_sent: "" } So this data will be saved in Database of specific table but the number of fields will be empty for all users.So here I want to insert value which should be increases each time the smtp flow of a specific user will done. For example today for user "king" I run the smtp flow 3 times so the value of particular user will be 3.And if I run the flow after two days,the code I run in that day suppose 5 times so the value in the ("Number_of_emails_sent") should be 8. So it should … -
How to upload a file using forms in django
I have being having issues with uploading an image file into my database. Here is the code. models.py from django.db import models from datetime import datetime class Product(models.Model): name = models.CharField(max_length=1000, blank=False, null=False) image = models.FileField() price = models.IntegerField(default=0, blank=False, null=False) stock = models.IntegerField(default=0, blank=False, null=False) forms.py from django import forms from .models import Product class ProductCreationForm(forms.ModelForm): class Meta: model = Product fields = ( "name", "image", "price", "stock", ) views.py from .models import Product from .forms import ProductCreationForm def product_create(request): form = ProductCreationForm() if request.method == "POST": form = ProductCreationForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] image = form.cleaned_data['image'] price = form.cleaned_data['price'] stock = form.cleaned_data['stock'] item = Product.objects.create(name=name, image=image, price=price, stock=stock) item.save() return redirect('product-view') else: messages.info(request, 'Invalid information entry!') return redirect('product-create') else: return render(request, "create.html", {"form": form}) create.html {% if user.is_authenticated %} <form method="post"> {% csrf_token %} {% for message in messages %} {{ message }} {% endfor %} {{ form.as_p }} <input type="submit", value="Done"> </form> {% endif %} settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.conf.urls.static import static from django.conf import settings if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Everytime i create a new product from … -
How to create correct url in tepmplate Django
I have this link in my templates: <a href="{% url 'main:user-main-account' %}?=client_account{{ client_account.id }}"> like a link it looks like: https://mysite.ua/main/user_main_account/?=client_account=1 How can I change my template link to get link like this: https://mysite.ua/main/client_account/1/user_main_accounts My 2 urls in urls.py look like this: path('user_main_account/<int:pk>/', ........) path('client_account'/<int:pk>/'.........) Please help me!I am stuck of 3 days. -
How to make REST Search-filter case-insensitive for none english letters?
Accordance to the REST's search-filter, "By default, searches will use case-insensitive partial matches". Everything works fine for english letters but for none-english ones it doesn't. class ProductsAPIView(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.SearchFilter,) search_fields = ['title', 'name'] My view path('all/', views.ProductsAPIView.as_view()), My url path For example: When I search in english letters: When I search in none-english letters: I have an item: { "id": 10, "productType": "Напитки", "measurment": "л", "product_image": "http://127.0.0.1:8000/images/logo.png", "title": "Фанта (0.5)", "name": "Фанта", "price": 40, "description": "", "created": "2022-06-21T07:20:07.582387Z", "updated": "2022-06-21T07:20:07.582435Z" }, "title": "Фанта (0.5)", - starts with upper case. So when I try /api/all/?search=ф. ( ф - lower, Ф - upper, in this case I wrote the lower ). I don't get this item. But I get it when I try with /api/all/?search=Ф (The upper one) I get the item what is contrary to case-insensitive.