Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid FileNotFound Error in django model ImageField when file does not exist
I have a Django model which has ImageField img and I have thousands of rows in the db while I also know some of the images in the db do not exist in the directory. But its an existing project and I cant do anything on that for now while the clients produce the missing images later. But the issue is while retrieving a queryset without any reference or specific use of the image files, I get a FileNotFound error. This happens both in Django admin once I paginate to a page that contains one of the records with missing file and also in a ViewSet's queryset I try to create for frontend. And because I have not paginated the ViewSet queryset, I can't even test the endpoint without having the FileNotFound error. How to catch this error or avoid it? -
Getting KeyError: 'answers' when using validated_data.pop('answers') even tho its getting the right data
I'm trying to define create() method in my nested serializers learning from the documentation. When I print the validated_data.pop and it HAS DATA that I requested but its returning keyerror which doesnt make sense since it has data in it. Error: answers_data = validated_data.pop('answers') KeyError: 'answers' serializers from rest_framework import serializers from .models import Question, Answer class AnswerSerializer(serializers.ModelSerializer): """Serialize Answer model""" class Meta: model = Answer fields = ('title', 'body', 'slug', 'author', 'question') lookup_field = 'slug' # https://stackoverflow.com/questions/55031552/how-to-access-child-entire-record-in-parent-model-in-django-rest-framework class QuestionSerializer(serializers.ModelSerializer): """Serialize Question model""" #This answer variable and the fields 'answer' you refer to has to be the SAME but #These can change exp: 'aaa' answer = AnswerSerializer(read_only=False, source='answers', many=True,) print("@@@@@@") print(answer) print("@@@@@@") print(type(answer)) class Meta: model = Question fields = ('title', 'slug', 'author', 'category', 'answer',) lookup_field = 'slug' def create(self, validated_data): print("@@@@@@") print("@@@@@@") print(validated_data.pop('answers')) print("@@@@@@") print("@@@@@@") answers_data = validated_data.pop('answers') question = Question.objects.create(**validated_data) for answer_data in answers_data: Answer.objects.create(question=question, **answer_data) return question views.py from django.shortcuts import render from .models import Question, Answer from django.conf import settings from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from .serializers import QuestionSerializer #from .permissions import UpdateOwnPrice from rest_framework.permissions import IsAdminUser class QuestionViewSet(viewsets.ModelViewSet): """CRUD """ serializer_class = QuestionSerializer queryset = Question.objects.all() authentication_classes = (TokenAuthentication,) #permission_classes = (UpdateOwnPrice,) … -
DJango - Redirect to another apps / from a button click
I've been trying to redirect my user to another apps root on a button click. So I've two apps, 'portfolio' and 'blogs'. 'blogs' is the main app which loads first. I've been able to navigate to 'portfolio' app from 'blogs', but how can I do it the other way around? My Project urls.py path('admin/', admin.site.urls), path('portfolio/', include('portfolio.urls')), path('', include('blogs.urls')), ] -
data i entered in the admin page not reflecting in my webpage,
The data i entered in the admin page not showing up on the web page. i don't know what is going wrong with my code, please help webpage admin.py from django.contrib import admin from blog.models import Post # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ('title','slug','status','created_on') list_filter = ('status',) search_fields = ['title','content'] prepopulated_fields = {'slug':('title',)} admin.site.register(Post, PostAdmin) urls.py from . import views from django.urls import path urlpatterns = [ path('blogspot/',views.PostList.as_view(), name="b"), path('<slug:slug>/',views.PostDetail.as_view(), name="post_detail"), ] views.py from django.views import generic from .models import Post # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'blog/index.html' class PostDetail(generic.DetailView): model = Post template_name = 'blog/post_detail.html' -
Can django queryset date be formatted from 'DD:MM:YYYY HH:MM:SS' TO 'YYYY:MM:DD' using Func,Value,output_field?
My desired output is : { " formated_date:'2021-05-01' ", } Queryset returns : {date : '2021-05-01 12:01:20'} -
Django with Auth0
Currently learning about Auth0 and django. https://github.com/auth0-blog/django-feed-auth0/blob/main/feed/feed/urls.py I saw the URL pattern is like this urlpatterns = [ path('admin/', admin.site.urls), path('', include('feedapp.urls')), path('', include('social_django.urls')), ] From what i learned previously we should have 1 path('', views.xyz) as it will be redundant to have same url pointing to the different views unless we have put other input like int or str. But auth0 have same path with other views. Not really understand why is it okay for it to be like this? Hope you guys can explain to me. Thanks -
How to set up Celery and Heroku Redis
I provisioned a Heroku Redis on my Dashboard and want to use it. Host <x>.compute-1.amazonaws.com User Port <y> Password <x> URI redis://:<x>.compute-1.amazonaws.com:<y> So I ran pip install celery pip install redis And here I need to use it which i used the URI which proceeds to error out. ModuleNotFoundError: No module named 'url' settings.py # CELERY STUFF BROKER_URL = 'url' CELERY_RESULT_BACKEND = 'url' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Nairobi' celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'portfolio.settings') app = Celery('portfolio') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) init.py from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app -
malloc error when migrate in Django using mySQL database
I'm using Django in VSCode and want to connect to the MySQL database, I've created the database in MySQL. When changing the database configuration from mysqlite to MySQL in settings.py, and do the migrate, the error pops up (in the picture below). Basically it says malloc error and asks me to set a breakpoint in malloc_error_break to debug. I have no idea of what's going on here. Anyone knows how to fix this error? The error message disappears once I changed the settings back to sqlite, it only happens when using MySQL. screenshot of error -
Django User Form Update with Groups
I am trying to update a User with django forms. In that form, I include UserGroups also. The problem right now I am facing is that if the user has multiple groups or has no group at all, it is not working. but if the user has a single group then it is working fine. Here is my code. views.py class User(AbstractUser): first_name = models.CharField(blank=False, max_length=25, null=False) last_name = models.CharField(blank=False, max_length=25, null=False) email = models.EmailField(blank=False, null=False, unique=True) password = models.CharField(blank=False, editable=False, max_length=256) company = models.ForeignKey(blank=True, on_delete=models.CASCADE, null=True, related_name="users", related_query_name="user", to='company.Company') is_active = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] username = name = contact = photo = None objects = UserManager() class Meta: ordering = ['id'] def get_absolute_url(self): return reverse('user_detail', kwargs={'pk': self.pk}) def __str__(self) : return self.email forms.py class UserForm(forms.ModelForm): company = forms.ModelChoiceField(queryset=Company.objects.all(), required=True) group = forms.ModelMultipleChoiceField(queryset=Group.objects.all(), required=True) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['first_name'].widget.attrs = { 'class': 'form-control form-control-sm', 'name': 'first_name', 'id': 'first_name', 'type': 'text'} self.fields['last_name'].widget.attrs = { 'class': 'form-control form-control-sm', 'name': 'last_name', 'id': 'last_name', 'type': 'text'} self.fields['email'].widget.attrs = { 'class': 'form-control form-control-sm', 'name': 'email', 'id': 'email', 'type': 'email', 'aria-describedby': 'emailFeedback' } self.fields['company'].widget.attrs = { 'class': 'form-select form-select-sm', 'name': 'company', 'id': 'comapny', 'type': 'select' } self.fields['group'].widget.attrs = { … -
NoReverseMatch Reverse for 'save-post' with arguments '('',)' not found. 1 pattern(s) tried: ['save/(?P<pk>[0-9]+)$']
I cannot figure out why I keep getting this "NoReverseMatch at /". I am trying to add AJAX to a form to save posts. It seems to be a problem with the URL in the Javascript, but I cannot figure out exactly what it is. Can anyone tell me what is wrong here? Thank you in advance. urls.py path('save/<int:pk>', views.AjaxSave, name='save-post'), views.py def AjaxSave(request, pk): if request.POST.get('action') == 'post': id = int(request.POST.get('postid')) result = post.saves.count() post = get_object_or_404(Post, id=id) if post.saves.filter(id=request.user.id).exists(): post.saves.remove(request.user) post.save() else: post.saves.add(request.user) post.save() return JsonResponse({'result': result, }) popular.html This is the form on the HTML <form action="{% url 'save-post' post.id %}" id="save" method="post"> {% csrf_token %} <button class="savebutton" type="submit" name="post_id" title="Save Post" id="save" value="{{ post.id }}"> <i class="fas fa-bookmark"></i> Save Post </button> </form> Javascript <script> $(document).on('click', '#save', function (e){ e.preventDefault(); $.ajax({ type: 'POST', url: "{% url 'save-post' post.id %}", data: { postid: $('#save').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { alert('Post saved!') }, error: function () { alert('Error!') } }); }) </script> -
Django ID of foreign key doesn't exist after migrating
I'm new to Django, and I'm trying to create a "game" model with two attributes: A many-to-one field where multiple instances of the game model are associated with an instance of a custom user model. A many-to-many field where instances of the game model are connected with multiple instances of words, and instances of the word model are connected with multiple instances of the game model Game model: class SortingGame(models.Model): user_current_player = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) field_words = models.ManyToManyField(Word, related_name="field_sorting_games") Word model: class Word(models.Model): str_word = models.CharField(max_length=50,null=True) int_grade_level = models.IntegerField() arrint_phonemes = ArrayField(models.CharField(max_length=50),null=True) arrstr_graphemes = ArrayField(models.CharField(max_length=50),null=True) int_num_syllables = models.IntegerField() arrstr_syllables = ArrayField(models.CharField(max_length=50),null=True) User model: class CustomUser(AbstractBaseUser): # must have the following fields for django email = models.EmailField(verbose_name="email",max_length = 100,unique=True) username = models.CharField(max_length = 30, unique = True) date_joined = models.DateTimeField(verbose_name = "date_joined",auto_now_add=True) last_login = models.DateTimeField(verbose_name = "last_login",auto_now = True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default = False) is_staff = models.BooleanField(default = False) is_active = models.BooleanField(default = True) first_name = models.CharField(max_length=15, blank=True) last_name = models.CharField(max_length=30, blank=True) spelling_level = models.IntegerField(default=1, unique=False) time_played = models.IntegerField(default=0, unique=False) percent_correct = models.IntegerField(default=0, unique=False) When I run python3 manage.py makemigrations and python3 manage.py migrate, it doesn't complain, but when I go to the admin page of my … -
Passing a pk from one template to another
I am relearning django/python recently and trying to build an app to manage a season ticket draft between friends. I've become stuck while searching for this answer, could be my phrasing, but I'm trying to understand how to pass a value from one template to another. Here is an example of what I am doing. views.py def home_page_view(request): sessions = DraftSession.objects.filter(session_status="ACTIVE") return render(request, "index/index.html", { 'arena_mappings': ARENA_MAPPINGS, 'team_mappings': TEAM_MAPPINGS, 'sessions': sessions, }) index.html {% for session in sessions %} <tr> <td> {{ session.season_year }} </td> <td> {{ team_mappings|get_item:session.home_team }} </td> <td> {{ arena_mappings|get_item:session.home_team }} </td> <td> {{ session.create_date }} </td> <td> {{ session.session_owner }} </td> <td> <button type="button" class="btn btn-primary">Join Now!</button> </td> </tr> {% endfor %} Using the button in the last column I want the user to be able to go to a new page that has awareness of the row that was selected, my assumption is this would be passed in via the pk for the db row. I've setup the view, urls, etc; just lost on how to pass the selection on the the new page. Appreciate any help! -
django 3rd party API Event Loop?
I'm quite new to back-end development so please forgive my ignorance. I need to connect my Django backend to a 3rd party API to fetch live location data from GPS trackers. This needs to be done server side as it triggers other events, so it can't just be run in the browser. What's the best way to go about doing this please? So far I have thought of something like an event loop which calls the API every 60 seconds, but can I run this on a separate thread for example? Is that even the best thing to do? Is it possible to do something like a websocket form my backend to the 3rd party? What's the best way of keeping this data updated? Finally, how does a solution like this scale, what if I had 5,000 vehicle trackers which all needed updating? Any advice would be greatly appreciated. Thank you. -
Can't use assertTemplateUsed with unitest.TestCase
Please help, i'm fairly new to Django and not sure what's the best way to proceed with my unit-tests. So, i have a large django app, and it has dozens of views-methods, and the postgresql schemas get pretty complex. I've read that if I use "from django.test import TestCase" then the test database is flushed after running each unit-test. I wanted to prevent from flushing the db in between unit-tests within the same class, so i started using "from unittest import TestCase". That did the trick and the db is preserved in between unit-tests, but now the statement self.assertTemplateUsed(response, 'samplepage.html') gives me errors AttributeError: 'TestViews' object has no attribute 'assertTemplateUsed'. What can I do? Is there an alternative to 'assertTemplateUsed' that can be used with unittest.TestCase? Many thanks in advance! -
How to extend an IIS request - Django
How can I extend the waiting time for e.g. downloading a file? I use ISS and tried to change the Request Timeout from 90 to 300 in FastCGI Settings, but that didn't help. If the file download request takes longer than 90 seconds, I have a 500 error. The entire site is based on python / Django. -
How to share my list to other user (Django)
Hello guys i'm a begginer in Django and i made a Shopping-list-app from wathing videos on youtube. I can make list in my app and i want to share my list to other user, but i do't know how really do that. I would be happy if someone could help me. model.py I tried to use models.ManyToManyField but i know don't what should i do in View.py to app the list from a user to other user from django.db import models from django.db import models from django.contrib.auth.models import User class Liste(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=30, verbose_name = "Titel") item1 = models.CharField(max_length=30, blank=True, verbose_name = "1") preis1 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item2 = models.CharField(max_length=30, blank=True, verbose_name = "2") preis2 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item3 = models.CharField(max_length=30, blank=True, verbose_name = "3") preis3 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item4 = models.CharField(max_length=30, blank=True, verbose_name = "4") preis4 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item5 = models.CharField(max_length=30, blank=True, verbose_name = "5") preis5 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") @property def rate(self): total = (self.preis1) + (self.preis2) + (self.preis3) + (self.preis4) … -
Django get objects that have certain ManyToMany relations
suppose we have two models like this: class User(models.Model): name = models.CharField(max_length=255) date_joined = models.DateField() class Group(models.Model): title = models.CharField(max_length=255) users = models.ManyToManyField(User) we get a queryset of users: user_qs = User.objects.filter(date_joined__range=['2022-01-01', '2022-01-05']) how can I get the list of Group objects that have all users of user_qs in their users? django==3.2 -
Filter foreign key in DetailView Django
I ran into a problem with the queryset query, I need to display certain tags for each article that are related to this article. Each article has tags associated with the article id. model.py class NewsDB(models.Model): title = models.CharField('Название',max_length=300) text = models.TextField('Текст статьи') img = models.ImageField('Фото',upload_to='News',null='Без фото') avtor = models.ForeignKey('Journalist', on_delete=models.PROTECT) date = models.DateField() def __str__(self): return self.title class Meta: verbose_name = 'News' verbose_name_plural = 'News DataBase' class Hashtags(models.Model): News=models.ForeignKey('NewsDB',on_delete=models.PROTECT) Hashtag=models.CharField('Хештег',max_length=150,null='Без темы') def __str__(self): return self.Hashtag view.py class Show_post(DetailView): model = NewsDB template_name = 'navigation/post.html' context_object_name = 'newsDB' def get_context_data(self,**kwargs): hashtags = super(Show_post,self).get_context_data(**kwargs) hashtags['hashtags_list'] = Hashtags.objects.filter(News=self.pk) return hashtags -
Extended fields in custom Django User model not appearing
I am trying to extend the default Django user model to include other fields and enable users to update this information. This is what I have in models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver #extending user model to allow users to add more profile information class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) city = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=50, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() api.py: from rest_framework import generics, permissions, mixins from rest_framework.authentication import TokenAuthentication from rest_framework.response import Response from .serializers import RegisterSerializer, UserSerializer from django.contrib.auth.models import User from rest_framework.permissions import AllowAny #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer #remove this if it doesn't work authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "message": "User Created Successfully. Now perform Login to get your token", }) and serializers.py: from django.contrib.auth.models import User from accounts.models import Profile from rest_framework import serializers #added more imports based on simpleJWT tutorial from rest_framework.permissions import IsAuthenticated from django.db import models from django.contrib.auth import authenticate from … -
May not set both `read_only` and `required` within two different serializers
First Serializer: class RecipeSerializer(serializers.ModelSerializer): step_of_recipe = RecipeStepsSerializer(many=True, required=False) ingredients = serializers.StringRelatedField(many=True, read_only=True) # <---- by_cook = serializers.StringRelatedField(read_only=True) Second Serializer: class RecipeCreateSerializer(serializers.ModelSerializer): step_of_recipe = RecipeStepsSerializer(many=True, required=True) ingredients = serializers.StringRelatedField(many=True, required=True) # <---- Traceback: web_1 | File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked web_1 | File "<frozen importlib._bootstrap>", line 688, in _load_unlocked web_1 | File "<frozen importlib._bootstrap_external>", line 883, in exec_module web_1 | File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed web_1 | File "/code/apps/recipe/urls.py", line 2, in <module> web_1 | from apps.recipe.views.recipe import RecipeView, RecipeCreateView web_1 | File "/code/apps/recipe/views/recipe.py", line 3, in <module> web_1 | from apps.recipe.serializers.recipe import RecipeSerializer, RecipeCreateSerializer web_1 | File "/code/apps/recipe/serializers/recipe.py", line 57, in <module> web_1 | class RecipeCreateSerializer(serializers.ModelSerializer): web_1 | File "/code/apps/recipe/serializers/recipe.py", line 61, in RecipeCreateSerializer web_1 | ingredients = serializers.StringRelatedField(many=True, web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/relations.py", line 123, in __new__ web_1 | return cls.many_init(*args, **kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/relations.py", line 143, in many_init web_1 | list_kwargs = {'child_relation': cls(*args, **kwargs)} web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/relations.py", line 237, in __init__ web_1 | super().__init__(**kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/relations.py", line 117, in __init__ web_1 | super().__init__(**kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/fields.py", line 336, in __init__ web_1 | assert not (read_only and required), NOT_READ_ONLY_REQUIRED web_1 | AssertionError: May not set both `read_only` and `required` As … -
Testing: Can't log in with superuser using Selenium
I have Selenium running tests and when login in with the superuser created from the shell works fine but when login in with a superuser made from test setUp it doesn't accept the credentials. Any idea why is this behavior happening? from django.test import TestCase from django.contrib.auth.models import User from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class FunctionalTestCase(TestCase): def setUp(self): self.username = 'mysuperuser' self.email = 'admintesting@gmail.com' self.password = 'mysecretpassword7' try: admin_user = User.objects.create_superuser(self.username, self.email, self.password) admin_user.save() except: print("Failed") def test_admin_can_navigate_to_courses(self): options = webdriver.ChromeOptions() options.add_argument(" - incognito") self.browser = webdriver.Chrome(executable_path='./chromedriver', options=options) self.browser.get("http://localhost:8000/accounts/login/") username_input = self.browser.find_element_by_id("id_username") password_input = self.browser.find_element_by_id("id_password") username_input.send_keys(self.username) password_input.send_keys(self.password) self.browser.find_element_by_xpath("//input[@type='submit']").click() self.browser.get('http://localhost:8000/site/me') def tearDown(self): self.browser.quit() -
Django adding colon to the path out of nowhere
I have a pretty simple Django project based on the one from the tutorial that I am slowly morphing into my own app. It was working fine locally. I tried to deploy it to Heroku, so I made a few changes, but it was still working fine locally (I am still working on getting it to work on Heroku). But then I ran it once more and out of nowhere I am getting this error: Invalid argument: 'C:\\Users\\cusack\\PycharmProjects\\pythonProject\\website\\:\\index.html' So it is adding :\\ or \\: to the path for some reason. I have looked at settings.py, views.py, urls.py, and I can't find anywhere where I have told it to do this. My urls.py file looks (partially) like this: urlpatterns = [ path('', views.index, name='index'), path('images/random.png',views.my_image,name='randomImage'), path('admin/', admin.site.urls) ] The main page and admin both give this error, but 'images/random.png' works just fine. For the admin page, it is adding the extra :\\ before admin\\index.html. My views.py for this index is trivial: def index(request): return render(request, 'index.html') It happened when I was playing around with DEBUG and ALLOWED_HISTS, although changing them back to True and [] didn't seem to help. Any idea where this could be coming from? -
Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax
I've been working on a Django project, I'm using Pycharm community edition 2021 and Django version as 4.0.3, the problem is that , whenever I reload my site there would be no pictures shown which I want to display from another website. Error would be like "Indicate whether to send a cookie in a cross-site request by specifying its Same Site attribute", I have tried much more method to resolve this adding removing cookies but unable to solve it, as I dnt know whether these same site cookies would be in IDE , Django or chrome? {% extends 'base.html'%} {% block body %} <div class="container my-4 mx-4 py-8 px-8" > <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="https://api.unsplash.com/search/photos?&client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100 " alt="..."> </div> <div class="carousel-item"> <img src="https://api.unsplash.com/search/photos?client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="https://api.unsplash.com/search/photos?client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs- target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs- target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> {% endblock body %} -
how to place the images in the select of my template to make the language change?
it is very very basic but my inexperience does not make me see the error. Well, the flags don't appear, but it is the folder and also the path, because I have other images that have the same path, only instead of flags it says brands <select class="selectpicker" data-width="fit"> <option><img src="{%static 'assets/images/flags/spain.jpg' %}" alt="">English</option> <option><img src="{%static 'assets/images/flags/us.jpg' %}" alt="">Español</option> </select> -
Python Django "surrogates not allowed" error on model.save() call when text includes emoji character
We are currently in the process of building a system that stores text in a PostgreSQL DB via Django. The data gets then extracted via PGSync to ElasticSearch. At the moment we have encountered the following issue in a testcase Error Message: UnicodeEncodeError: 'utf-8' codec can't encode characters in position 159-160: surrogates not allowed We identified the character that causes that issue. It is an emoji. The text itself is a mixture of Greek Characters, "English Characters" and as it seems emojis. The greek is not shown as greek, but instead in the \u form. Relevant Text that causes the issue: \u03bc\u03b5 Some English Text \ud83d\ude9b\n#SomeHashTag \ud83d\ude9b\ translates to this emoji:🚛 As it says here: https://python-list.python.narkive.com/aKjK4Jje/encoding-of-surrogate-code-points-to-utf-8 The definition of UTF-8 prohibits encoding character numbers between U+D800 and U+DFFF, which are reserved for use with the UTF-16 encoding form (as surrogate pairs) and do not directly represent characters. PostgreSQL has the following encodings: Default:UTF8 Collate:en_US.utf8 Ctype:en_US.utf8 Is this an utf8 issue? or specific to emoji? Is this a django or postgresql issue?