Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
send event id of eventClick to views.py Django
I'm really new in Javascript and Fullcalendar and I need to know how to pass the event id of the clicked event (event_id) to the views.py. so for now I'm having that: document.addEventListener('DOMContentLoaded', function () { var calendarUI = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarUI, { eventClick: function (info) { alert('Event: ' + info.event.id); var event_id = info.event.id; $('#exampleModalToggle').modal('show');} selectable: true, editable: true, displayEventTime: true, displayEventEnd: true, contentHeight: "auto", allDaySlot: false, initialView: 'timeGridWeek', headerToolbar: { left: 'today', center: 'prev title next', right: 'dayGridMonth timeGridWeek' }, views: { timeGridWeek: { //titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' } columnHeaderFormat: { weekday: 'numeric', month: 'numeric', day: 'numeric', omitCommas: true } } }, //slotLabelFormat: [{ month: 'long', year: 'numeric' }, { weekday: 'short' }], //slotLabelFormat: ['ddd D/M', 'H:mm'], events: [ {% for reservation in reservations_api %} { title: '{% for machine in machines %} {% if reservation.machine_id == machine.id %} {{machine.machine_name}} {% endif %} {% endfor %} - {% for enterprise in enterprises %} {% if reservation.company_id == enterprise.id %} {{enterprise.name}} {% endif %} {% endfor %} ', start: '{{ reservation.start_date }}', end: '{{ reservation.end_date }}', color: '{% for enterprise in enterprises %} {% if reservation.company_id == enterprise.id %} {{enterprise.color}} {% endif … -
OpenCv videoCapture in cpanel (Incomplete response received from application)
Here I call Videocamera to open the camera and then return streaminghttpresponse and there i call gen(cam). Now i am facing 2 problem. i want to store 100 images of user and go back to another screen. here this code working locally fine but when i upload it on server its give error Incomplete response received from application and second problem is will render to another screen when count == 10 def getImages(request): global postReq postReq = request print(request) global userRequest global userFaceName userFaceName = request.POST['name'] print(userFaceName) userRequest = request.user.pk print(userRequest) try: cam = VideoCamera() print("hello check") return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: print("killed") pass return redirect('imagess') class VideoCamera(): def __init__(self): global count print("video camera") self.video = cv2.VideoCapture(0) print("video") (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): print("destriy") self.video.release() def get_frame(self): face_id=1 image = self.frame # face_detector = cv2.CascadeClassifier('C:\\Users\\abbas\\Desktop\\final try\\FYP\\isight\\Application\\haarcascade_frontalface_default.xml') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # faces = face_detector.detectMultiScale(gray, 1.3, 5) # for (x,y,w,h) in faces: # cv2.rectangle(gray, (x,y), (x+w,y+h), (255,0,0), 2) # global count # count = count + 1 # face = cv2.resize(image, (400, 400)) # face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY) # writePic = cv2.imwrite("static/pdfbook/images/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w]) # c = 'C:\\Users\\abbas\\Desktop\\final try\\FYP\\isight\\static\\pdfbook\\images\\' + "User." + … -
How to write this SQL lines in Django Models?
CREATE TABLE animal ( ID number not null primary key , GENDER varchar2(1) not null , SIRE_ID number , DAM_ID number , constraint animal_gender check (gender in ('M','F')) , constraint animal_sire_fk FOREIGN KEY (sire_id) REFERENCES animal(id) DEFERRABLE INITIALLY DEFERRED , constraint animal_dam_fk FOREIGN KEY (dam_id) REFERENCES animal(id) DEFERRABLE INITIALLY DEFERRED ); -
How can I make a tree data structure
I'm working on a small project (File Browser) using Django / Javascript. i have two models: from django.db import models # Create your models here. class Folder(models.Model): name = models.CharField(blank=False, null=False, max_length=60) parent = models.IntegerField(blank=False, null=False) class Document(models.Model): folder = models.ForeignKey(Folder, on_delete=models.CASCADE, null=True, blank=True) filename = models.CharField(blank=False, null=False, max_length=60) I would like to have this data structure : root: { name: 'Files', children:[ { 'name': 'music', children:[ { name: 'song.mp3' }, { name: 'song2.mp3' } ] }, { name: 'Books', children:[ { name: 'php.pdf' } ] } ] } can someone help me to make it thank you -
How would you model in django a hierarchy of objects where one type might has itself as a child?
I would like to model the following hierarchy in Django, but don't really know how to approach the Opportunity relationships to other Opportunities and/or Solutions. Outcome |- Opportunity 1 | |- Opportunity 1.1 | | |- Solution 1 | | |- Solution 2 | |- Opportunity 1.2 | |- Solution 3 | |- Solution 4 |- Opportunity 2 |- Solution 5 |- Solution 6 Each outcome has many Opportunities. Each Solution belongs to an Opportunity. Opportunities might either have many Opportunities or many Solutions, but not both. Sub-opportunities can not have more Opportunities, just Solutions. -
Inner HTML with Django tamplate if statement usig Js variable
I'm really new in JavaScript and I have a question: I need to add inside an inner Html, a Django template if statement that uses a JavaScript variable to compare (in this case the variable is event_id) I have tried a lot of alternatives after hours and also I have searched with no success. This is my JS code. eventClick: function (info) { var event_id = info.event.id; $('#exampleModalToggle').modal('show'); selected_group_member.innerHTML = ` {% for reservation in reservations_api %} {% if reservation.id == ${event_id} %} <option value="1" selected>{{reservation.id}}</option> {% endif %} {% endfor %} `; } with this option, I'm getting this error: Could not parse the remainder: '${event_id}' from '${event_id}' and if I change it for {% if reservation.id == + event_id + %}, I'm getting this error: Could not parse the remainder: '' from '' So, is that possible to do? Do you know how could it work please !!! I really don't know how to solve it, I really appreciate your help thanks :) -
Should I start over my project in a new Django Virtual Environment
I began my project without creating a virtual environment. Now I am wondering how big of a mistake was that. pip install Pillow not executing no matter what I do to include an image in my classs Model. Can or should I migrate my files to a new virtual environment. Or should I start coding from scratch. -
How to add ''draw a marker" Control to leaflet Map and capture event?
I want to create a map with leaflet and give the user the opportunity to add a marker to that map from the user interface. The user shuld mark a point(market to th map). Then when the point is set I want to get the location (coordinates) of that marker and perform other operations. It should allow only one marker I want this result -
Why does this error appear in my JailedShell when installing Django?
The error that appears on the console I want to create a project in Django in my hosting, I was investigated that it was what I had to do using JailedShell in cpanel, but at the time of installing it does not work and i mark the errors that are in the image that I attach. When I asked in my hosting they sent me this link step by step what I have to do to install Django is its version 1.11 since the hosting is using python 2.75, I followed the steps of the article but I do not understand well, likewise, leave the link of the article here https://soporte-latam.hostgator.com/hc/es-419/articles/115002998391#pasoinicial Hoping someone can help me, thank you very much -
cant connect stripe webhook with heroku
iam currently deployed my website on Heroku but after the user pay for the order Stripe Webhook dosent work at all although it worked before in (Development) so how can i work with Stripe in production with Heroku -
Django REST Framework Depth Only For Specified Fields
So I have a Django REST Framework Serializer. Now I added a serializer for my Blog Posts, but I want the Serializer depth only for a specified field. Until now I get this: This is my serializer: class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = Job fields = ["postid", "title", "description", "slug", "tag", "views", "user", "release_date", "city", "country"] depth = 1 And this is the wrong output { "results": [ { "postid": 1, "title": "Test Title", "slug": "test-title", "description": "Test Description", "tag": { "tagid": 1, "tagname": "school" }, "views": 15, "release_date": "2021-05-25T17:15:22.223311Z", "user": { "userid": 1, "password": "pbkdf2_sha256$216000$drVQlm6CdO+g90ygM3gXFUHBb+ctaKDA=", "username": "user1", "email": "testemail@gmail.com", "posts": 0, "date_joined": "2021-05-25T17:13:29.865119Z", "last_login": "2021-05-25T17:14:12.808671Z", "is_admin": true, "is_active": true, "is_staff": true, "is_superuser": true }, "city": "New York", "country": { "countryid": 1, "continent": "america", "countryname": "usa", "currency": "$", "symbol": "US" } }, ... ] } But the problem is, I only want the depth for tag and country, not for user :/ Like this: { "results": [ { "postid": 1, "title": "Test Title", "slug": "test-title", "description": "Test Description", "tag": { "tagid": 1, "tagname": "school" }, "views": 15, "release_date": "2021-05-25T17:15:22.223311Z", "user": 1, "city": "New York", "country": { "countryid": 1, "continent": "america", "countryname": "usa", "currency": "$", "symbol": "US" } }, ... ] … -
Multiplication of SQL queries for one django objects.get request
I'm working on Django, an I have a ClientPartner class as Model : class ClientPartner(BusinessObject): charge_account = models.ForeignKey("ClientAccount", on_delete=models.DO_NOTHING, null=True, blank=True, related_name="partners_as_charge") client_account = models.ForeignKey("ClientAccount", on_delete=models.DO_NOTHING, null=True, blank=True, related_name="partners_as_client") legal_entity = models.ForeignKey("legal_entity.LegalEntity", on_delete=models.CASCADE, related_name="partners") partner = models.ForeignKey("legal_entity.LegalEntity", on_delete=models.CASCADE, related_name="client_legal_entities") product_account = models.ForeignKey("ClientAccount", on_delete=models.DO_NOTHING, null=True, blank=True, related_name="partners_as_product") vendor_account = models.ForeignKey("ClientAccount", on_delete=models.DO_NOTHING, null=True, blank=True, related_name="partners_as_vendor") and I query the table as shown below : lo_partnership = ClientPartner.objects.get(legal_entity=self.owner, partner=io_vendor) I use django standard logs and when I run this line I have the SQL queries below : DEBUG 2021-05-27 21:38:42,237 utils 21776 22144 (0.016) SELECT "client_clientpartner"."id", "client_clientpartner"."creation_date", "client_clientpartner"."creation_user_id", "client_clientpartner"."deleted", "client_clientpartner"."deletion_date", "client_clientpartner"."deletion_user_id", "client_clientpartner"."update_date", "client_clientpartner"."update_user_id", "client_clientpartner"."charge_account_id", "client_clientpartner"."client_account_id", "client_clientpartner"."legal_entity_id", "client_clientpartner"."partner_id", "client_clientpartner"."product_account_id", "client_clientpartner"."vendor_account_id" FROM "client_clientpartner" WHERE ("client_clientpartner"."legal_entity_id" = 2 AND "client_clientpartner"."partner_id" = 935) LIMIT 21; args=(2, 935) DEBUG 2021-05-27 21:38:42,243 utils 21776 22144 (0.000) SELECT "legal_entity_legalentity"."id", "legal_entity_legalentity"."creation_date", "legal_entity_legalentity"."creation_user_id", "legal_entity_legalentity"."deleted", "legal_entity_legalentity"."deletion_date", "legal_entity_legalentity"."deletion_user_id", "legal_entity_legalentity"."update_date", "legal_entity_legalentity"."update_user_id", "legal_entity_legalentity"."comment", "legal_entity_legalentity"."image_id" FROM "legal_entity_legalentity" WHERE "legal_entity_legalentity"."id" = 2 LIMIT 21; args=(2,) DEBUG 2021-05-27 21:38:42,248 utils 21776 22144 (0.000) SELECT "legal_entity_legalentity"."id", "legal_entity_legalentity"."creation_date", "legal_entity_legalentity"."creation_user_id", "legal_entity_legalentity"."deleted", "legal_entity_legalentity"."deletion_date", "legal_entity_legalentity"."deletion_user_id", "legal_entity_legalentity"."update_date", "legal_entity_legalentity"."update_user_id", "legal_entity_legalentity"."comment", "legal_entity_legalentity"."image_id", "legal_entity_organization"."legalentity_ptr_id", "legal_entity_organization"."accounting_method_id", "legal_entity_organization"."ape", "legal_entity_organization"."bic", "legal_entity_organization"."commercial_name", "legal_entity_organization"."country_id", "legal_entity_organization"."draft", "legal_entity_organization"."factory_code", "legal_entity_organization"."legal_form_id", "legal_entity_organization"."main_activity_id", "legal_entity_organization"."name", "legal_entity_organization"."siren", "legal_entity_organization"."tax_model_id", "legal_entity_organization"."url_login", "legal_entity_organization"."url_privacy", "legal_entity_organization"."url_website", "legal_entity_organization"."vat_number", "legal_entity_organization"."vat_regime_id" FROM "legal_entity_organization" INNER JOIN "legal_entity_legalentity" ON ("legal_entity_organization"."legalentity_ptr_id" = "legal_entity_legalentity"."id") WHERE "legal_entity_organization"."legalentity_ptr_id" = 2 LIMIT 21; args=(2,) DEBUG … -
How to add event to LeafletWidget in django-leaflet?
In my django app I have a Worker model with a name and location (Point). Using django-leflet LeafletWidget I can create a Form where the user can set a location (marker to that worker). Is it possible to add an event to the widget, so, every time the user sets the marker, or change the marker position it gets the coordinates of that point and perform other actions (like an ajax request)? class WorkerForm(forms.ModelForm): class Meta: model = WorkerModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'location': LeafletWidget(), } in the template i just call 'forms.location' and it renders the map with the controls to set a marker Every time the user sets the marker I want to get the location of that marker. How do I do that? -
Django form only takes user registration only as a whole
I'm trying to create a registration form using the django.auth but when try to submit the form it doesn't work if i specify forms.username, forms.email etc. only if i use {{form}} as a whole. like if i have <form method="POST" class='form-group'> {%csrf_token%} <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1"><i class="fa fa-user"></i></span> {{form.username}} </div> <button type="submit" class="btn btn-success">Register</button> </form> instead of using <form method="POST" class='form-group'> {%csrf_token%} {{form}} <button type="submit" class="btn btn-success">Register</button> </form> it doesn't work, it doesn't submit and i can't find the new user in admin django/users. -
could not translate host name "db" to address: Name or service not known - Heroku via Docker
I know there is a lot of this floating around, but their answers does not seem to apply to my case. I'm deploying a gis web application from docker to heroku. I am encountering this problem when I run heroku run python manage.py migrate I have this line in my settings.py import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES.update(default=db_from_env) This is my docker-compose-prod.yml db: image: kartoza/postgis:13.0 volumes: - postgis-data:/var/lib/postgresql environment: - POSTGRES_DB=gis - POSTGRES_USER=foo - POSTGRES_PASS=bar - ALLOW_IP_RANGE=0.0.0.0/0 - POSTGRES_MULTIPLE_EXTENSIONS=postgis,hstore,postgis_topology,postgis_raster,pgrouting I used the build package https://github.com/cyberdelia/heroku-geo-buildpack.git and also manually changed the DATABASE_URL to heroku config:add DATABASE_URL=postgis://foo:bar@db:5432/gis Isn't db_from_env automatically points to kartoza/postgis:13.0? Why is this happening here. -
Django + Bootstrap modal form still shows Djangos default errors, not bootstrapped errors?
I am struggling with displaying bootstraps form errors in a popup form modal. When I submit the form, with some missing required fields, I am still getting Django's built in basic form error messages, or even if a field requires a decimal, I enter text, I get an error but it's still django's built in basic validation error. I am using crispy-forms and bootstrap to try to display the errors in a nicer way on the page. This is the way errors are being displayed now.... I have a simple form here... {% load crispy_forms_tags %} <form role="form" method="post" name="employee-add" id="employee-add" action="{% url 'employee_add' company_id %}"> {% csrf_token %} <input type="hidden" id="companyID" name="comp" value="{{ company_id }}"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Add Employee</h4> </div> <div class="modal-body"> <div class="modal-inner defult-inner"> {% for field in employee_form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> {{ field|as_crispy_field }} {% for error in field.errors %} <span class="error-msg">{{ error }}</span>s {% endfor %} </div> {% endfor %} <div class="footer-button employee-footer"> <button class="btn btn-default" data-dismiss="modal">Cancel</button> <button class="btn btn-danger" id="save">Save</button> </div> </div> </div> </form> The modal form is populated with an AJAX GET request. $(function () { // GET request … -
Django: how set default random value for readonly_field in admin view?
In django project, I created a default function called "create_code" to randomly generate a default value for "code" field in models.py file. # models.py class Project(models.Model): name = models.CharField("Project name", max_length=255) code = models.CharField("Code", max_length=10, default=create_code, editable=False) In admin.py file, I set "code" as a readonly_field. #admin.py @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): fields = ('name', 'code') readonly_fields = ('code', ) The problem occours when I create a new Project object in admin page. The default value for "code" appers (eg. ABCD), but when I save the data this value change to another one (eg. EFGH). I think two objects are been created: one when loads the page and other when save the data. How can I read the "code" value from first object to overwrite the last one and save "ABCD" instead of "EFGH"? -
Django ORM bulk update with group by condition
At first have a look at models and query: This is my models class Dish(models.Model): restaurant = models.ForeignKey( restaurant, on_delete=models.CASCADE, related_name="dishes", ) is_active = models.BooleanField(default=True) start = models.DateTimeField(null=True, blank=True) and this is my query def update_dish_status(): today = datetime.today().strftime('%Y-%m-%d') for dish in Dish.objects.all(): if str(dish.start.date()) == str(today): dish.is_active = True dish.save() else: dish.is_active =False dish.save() You may notice that i am updating dish to change is_active and is_active status. Currently it's working the way i dont want that way. I want to when in a restaurant at least one dish's date are same as today's date, then that restaturant's all the dish should be active status False except the dish that is date is same as today date. and if any restaurants dont have such dish that start date matched with today's date, then those restaurants all the dish status should be active, i mean is_active=True For example, i have a restaurants, and in my restaurants 10 dishes. if at least one dish's start date is same as today's date, then that dish will is_active=True and all those dish whose date are not same as today, those dish will be is_active=False But there is another case should be handled like, … -
Connection Timed Out - Apache2 & Django Deployment
I rent a Ubuntu VPS and deployed my Django project using Apache2. But when I try to connect port 80(HTTP) with the IP number it results in the connection timed out. Here is my Apache configuration: <VirtualHost *:80> WSGIScriptAlias / /var/www/html/SistemDedektifi/SistemDedektifi/SistemDedektifi/wsgi.py WSGIDaemonProcess SistemDedektifi python-home=/var/www/html/SistemDedektifi/SistekDedektifi/venv python-path=/var/www/html/SistemDedektifi/SistemDedektifi WSGIProcessGroup SistemDedektifi Alias /static /var/www/html/SistemDedektifi/SistemDedektifi/static <Directory /var/www/html/SistemDedektifi/SistemDedektifi/static> Require all granted </Directory> <Directory /var/www/html/SistemDedektifi/SistemDedektifi/SistemDedektifi> <Files wsgi.py> Require all granted </Files> </Directory> Last two days I am working on configuring this but I can't figure it out. -
How to mock serializer in django testing?
So i was testing a rest api method in with we are returning json formatted serializer.data but when we tried to make testcases for this object we couldn't able to mock serializer properly. views.py data = {Something in jason format} serializer = ClassName1(data=data) serializer.is_valid(raise_exception=True) rec_data = {Something in json format} rec_serializer = ClassName2(data=rec_data) rec_serializer.is_valid(raise_exception=True) return Response({'key01':serializer.data, 'key02':rec_serializer.data}) test_views.py @mock.patch('myapp.serializers.ClassName1.data') @mock.patch('myapp.serializers.ClassName2.data') @mock.patch('myapp.serializers.ClassName1.is_valid') @mock.patch('myapp.serializers.ClassName2.is_valid') def test_serializer(TestCase, mock_c2_isvalid, mock_c1_isvalid, mock_c2_data, mock_c1_data): url = reverse('view-name') mock_c2_data.return_value = {dummy json data} mock_c1_data.return_value = {dummy json data} req = RequestFactory().get(url) response = views.Class.as_view()(req) self.assertEquals(response.status_code, 200) above test case is working but we have to patch two times for one serializer if there is any way to mock the serializer object if self and use that to return value for some method. let me know if there is another better way to mock serializer. -
Getting External url Hit in newrelic APM without the actual url
We are using newrelic in docker container on aws ec2. The transaction details on APM for a particular API is showing "urllib3[169.254.169.254]" in stacktrace, but I cannot identiy the source of it, also as per code no external link should be hit(tested in local no link is being hit; tested using pyinstrument). I have attached an image of the stacktrace please let me know how to find the target and get to the actual link being hit. -
how can adjust divs card position
i want to adjust divs so the last login list come on the right of devices list so what tags should i use and ? and this is the code : <div class="row "> <div class="card card-body col text-center"> <h5>All devices </h5> <hr> <table class="table"> <tr> .... </tr> {% for device in devices %} <tr> ..... </tr> {% endfor %} </table> </div> <div class="card card-body col text-center"> <h5>Last login </h5> <hr> <table class="table"> <tr> .... </tr> {% endfor %} </table> </div> </div> -
FactoryBoy - how to pass initial values?
I'm trying to use factory_boy in my tests. The problem is that it seems not to be taking to account Factory parameters. factory class ProductFactory(DjangoModelFactory): class Meta: model = Product title = factory.Faker('sentence') created_by = factory.SubFactory(UserFactory) organisation = factory.RelatedFactory(OrganisationFactory) sku = factory.Faker('word') usage def test_sku_organisation_uniqueness(self) -> None: print(self.product.organisation) product1 = ProductFactory.create(sku='xxxx', organisation=self.product.organisation) product2 = ProductFactory.create(sku='xxxx', organisation=self.product.organisation) print(product1.sku) print(product1.organisation) print(product2.sku) print(product2.organisation) Which returns: My organisation xxxx owner xxxx newspaper The strings "owner" and "newspaper" are organisations but I wanted it to have "My organisation" object. How can I do that? -
Django dependent drop down not functioning properly
Django noob I am currently attempting to implement a dependent drop down list for car models - manufactures I am following this tutorial I have the form displaying properly but the issue I am facing is if I select a manufacture no models are displayed. I have spent a bunch of time attempting to solve this and I am out of ideas All feedback welcome! forms.py from blog.models import Post, Manufactures, Models class PostForm(ModelForm): class Meta: model = Post fields = 'title', 'manufacture', 'model', 'content', 'image', 'aspiration' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Models.objects.none() models.py class Manufactures(models.Model): manufacture_id = models.AutoField(primary_key=True) manufacture = models.CharField(max_length=55) def __str__(self): return self.manufacture def get_absolute_url(self): return reverse('db-manufactures', kwargs={'pk': self.pk}) class Models(models.Model): model_id = models.AutoField(primary_key=True) model = models.CharField(max_length=55) model_manufacture = models.ForeignKey(Manufactures, on_delete=models.CASCADE) def __str__(self): return self.model def get_absolute_url(self): return reverse('blog-models', kwargs={'pk': self.pk}) Views.py def loadModels(request): manufacture_id = request.GET.get('model_manufacture') models = Models.objects.filter(manufacture_id = manufacture_id) return render(request, 'model_dropdown_list.html', {'models': models}) class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def save(self, *args, **kwargs): super(Post,self).save(*args, **kwargs) model_dropdown_list.html <option value="">---------</option> {% for model in models %} <option value="{{ model.pk }}">{{ model.name }}</option> {% endfor %} post_form.html {% extends "blog/base.html" %} {% … -
Emojis are replaced by question marks (Django / MySQL)
Emojis are replaced by '?' when saved to the db and I cannot find where it does come from. I get "a🙂a" transformed to "a?a", either via django admin or directly through my code Any idea to fix this problem? My configuration: settings.py: DATABASES = { 'default': { ... 'OPTIONS': { 'init_command': "SET NAMES utf8mb4; SET CHARACTER SET utf8mb4; SET character_set_connection=utf8mb4; SET collation_connection = 'utf8_unicode_ci';", 'charset': 'utf8mb4', }, } } my mysql configuration: [mysqld] character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci init-connect='SET NAMES utf8mb4' [client] default-character-set=utf8mb4 [mysql] default-character-set=utf8mb4 charset in db: MariaDB [dbn]> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%'; +--------------------------+--------------------+ | Variable_name | Value | +--------------------------+--------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | collation_connection | utf8mb4_general_ci | | collation_database | utf8mb4_unicode_ci | | collation_server | utf8mb4_unicode_ci | +--------------------------+--------------------+ the table containing the field: SHOW TABLE STATUS where name="xxx" => "utf8mb4_unicode_ci" for that table the field receiving the emoji string: MariaDB [dbn]> SELECT column_name, character_set_name, collation_name FROM information_schema.columns where TABLE_NAME='xxx'; +-----------------+--------------------+--------------------+ | column_name | character_set_name | collation_name | +-----------------+--------------------+--------------------+ …