Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my Elasticsearch request doesn't show any hits?
I have dockerized Django project. I want to use Elasticsearch, so I choosed django-elasticsearch-dsl. My steps were: In my Django project's settings file (settings.py), I configured the Elasticsearch connection settings. ELASTICSEARCH_DSL = { 'default': { 'hosts': ["http://localhost:9200"], }, } Created a file named documents.py my Django app. In this file, I defined Elasticsearch documents that correspond to my Django models. from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Filmwork @registry.register_document class FilmWorkDocument(Document): class Index: name = 'film' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Filmwork fields = ['title', 'description'] So then I indexed data from my Django model into Elasticsearch by using command python3 manage.py search_index --rebuild. I used this command outside docker, it showed: File "/Users/ArtemBoss/Desktop/artem_yandex_repo/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "database" to address: nodename nor servname provided, or not known At the same time, when I'm trying to index data inside django container it shows: File "/usr/local/lib/python3.10/site-packages/elastic_transport/_node/_http_urllib3.py", line 202, in perform_request raise err from None elastic_transport.ConnectionError: Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f9150762b60>: Failed to establish a new connection: [Errno 111] Connection refused)) Anyway Index was successfully … -
CSRF verification failed. Request aborted. Origin checking failed
Here is my setup: localhost (Windows 11) - Nginx listening on port 80 and 443, 80 is NOT automatically redirected to 443 each proxy_passed to http://wsgi-server where wsgi-server=127.0.0.1:8080 - waitress_wsgi running as a service on port 8080 Here is Django config: <!-- email_test.html --> <!-- ... --> <form action="{% url 'identity:email_test' %}" method="post"> {% csrf_token %} {{ email_form }} {% translate 'Send email' as submit_translated %} <!-- I use django_bootstrap5 --> {% bootstrap_button button_type="submit" content=submit_translated extra_classes='w-100'%} </form> # settings.py ---------- MIDDLEWARE = { # ... 'django.middleware.csrf.CsrfViewMiddleware', # ... } # forms.py ------------- class EmailTestForm(forms.Form): email = forms.EmailField( # help_text=password_validation.password_validators_help_text_html(), label=_('Email'), max_length=128, ) # views.py ------------- def email_test(request): context = {} context.update(template_globals()) if request.method == "POST": email_form = EmailTestForm(request.POST) if email_form.is_valid(): email_obj = EmailMessage(subject='Hello', body='Email body', from_email='noreply@nutrihub.hnet', to=[email_form.cleaned_data.get('email')]) email_obj.send(fail_silently=False) else: email_form = EmailTestForm() context['email_form'] = email_form return render(request, "identity/email_test.html", context) Here are my test resuts when I visit the URL on browser: py manage.py runserver (default port 8000), browser http://127.0.0.1:8000, empty settings.CSRF_TRUSTED_ORIGINS: Works fine. Browser http://localhost or http://127.0.0.1 or https://localhost or https://127.0.0.1 with individual entry not in settings.CSRF_TRUSTED_ORIGINS: CSRF error. Browser http://localhost or http://127.0.0.1 or https://localhost or https://127.0.0.1 with individual entry not settings.CSRF_TRUSTED_ORIGINS: Works fine. Browser https://mymachine.net with this entry in … -
Import Error while using python manage.py migrate command
Recently, i forked some source code from github to use as a basis for a project that i'm using to learn Django. As per the deployment instructions, i tried to use this command for the database in my terminal: python manage.py migrate Yet i keep getting this error: ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\afric.virtualenvs\Online-Examination-System-aZtpAN9a\lib\site-packages\django\utils\encoding.py) the error stems from the terminal trying to proccess this command: from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError can anyone please help me solve this? -
What's the best approach to keeping data consistent in a django-based app used in parallel by three or four users?
I'm making a Django app using a postgresql database for a family who need to coordinate their grocery purchases. Say one person has on their mobile device a full list of the groceries and is in the supermarket, buying and ticking each item off the list. His partner decides to stop at another shop and begins buying the items on the same list. How would you approach ensuring that they don't buy double or, more importantly, that they don't end up messing up the data entirely? A simple first-come, first-served lock, giving the second user only read-only rights? Or is there a more flexible way? And if the best way is a lock, how much does postgresql do for you? -
Django: Pass model ID to url using bootstrap modal
I'm trying to create a delete confirmation dialog using bootstrap 5 modals in my Django project. {% extends 'base.html' %} {% block content %} <div class="col-md-6 offset-md-3"> {% if messages %} {% for message in messages %} <div class="alert alert-success alert-dismissible fade show" role="alert"> {{ message }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} </div> <h1>Service Overview</h1> <br/> <div class="d-grid gap-2 justify-content-md-end"> <a class="btn btn-primary" href="{% url 'add_service' %}">Add service</a> <br/> </div> <table class="table table-hover table-bordered"> <thead class="table-secondary"> <tr> <th class="text-center" scope="col">#</th> <th scope="col">Name</th> <th scope="col">Description</th> <th class="text-center" scope="col">Cost</th> <th class="text-center" scope="col">Created at</th> <th class="text-center" scope="col">Updated at</th> <th class="text-center" scope="col">Status</th> <th class="text-center" scope="col">Actions</th> </tr> </thead> <tbody> {% for service in services %} <tr> <td class="text-center">{{ service.id }}</td> <td>{{ service.name }}</td> <td>{{ service.description}}</td> <td class="text-center">{{ service.cost }} AED</td> <td class="text-center">{{ service.created_date }}</td> <td class="text-center">{{ service.updated_date }}</td> {% if service.status == "ACTIVE" %} <td class="text-center"> <span class="badge text-bg-success" style="font-size:0.7em;">{{ service.status }}</span> </td> {% elif service.status == "INACTIVE"%} <td class="text-center"> <span class="badge text-bg-danger" style="font-size:0.7em;">{{ service.status }}</span> </td> {% endif %} <td class="text-center"> <!--Update--> <a href="{% url 'service_record' service.id %}" class="text-decoration-none"> <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="tooltip" title="Update service"> <i class="bi bi-pencil-fill"></i> </button> </a> <!--Delete modal--> <!-- Button trigger … -
Django URL 404 - 1 week spent debugging with GPT4, Claude luck. One specific function is just NOT resolving
Issue Summary: I'm facing an issue where the /LS/mark-text-responses/ URL in my Django application is not being found when an AJAX request is sent to the mark_text_responses view. This issue is occurring in the user-facing part of my application, specifically in the JavaScript code that sends the AJAX request. I'm receiving a 404 Not Found error, indicating that the URL is not being resolved correctly. Relevant JavaScript Code: **javascript ** function submitWorksheet(event, activityIndex) { event.preventDefault(); const worksheetForm = event.target; const worksheetQuestionsData = worksheetForm.querySelector('.worksheet-questions').textContent; let worksheetData = {}; try { worksheetData = JSON.parse(worksheetQuestionsData); } catch (error) { console.error('Error parsing worksheet data:', error); return; } // ... (code omitted for brevity) ... if (question.type === 'text_response') { const textResponse = worksheetForm.querySelector(`textarea[name="response_${index + 1}"]`).value; const feedbackElement = document.getElementById(`text-response-feedback-${index + 1}`); // Make an AJAX request to the server to get feedback on the text response fetch('/lessons/mark-text-responses/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.querySelector('input[name="csrfmiddlewaretoken"]').value }, body: JSON.stringify({ activity_id: '{{ activity.id }}', question_index: index, text_response: textResponse }) }) .then(response => response.json()) .then(data => { if (data.feedback) { feedbackElement.textContent = data.feedback; } else { console.error('Error:', data.error); feedbackElement.textContent = 'Error processing text responses.'; } }) .catch(error => { console.error('Error:', error); feedbackElement.textContent = 'Error processing text … -
A "django.core.exceptions.SuspiciousFileOperation" error is occurring despite setting everything up correctly
Currently attempting to serve all of my static files via whitenoise. Funnily enough, the function itself works a treat. It seeks out all the directories labelled static in all of my Django apps. However, why is Django consistently returning the django.core.exceptions.SuspiciousFileOperation exception in my traceback, and why is this returning this just one css file. Logic would dictate that seeing as this css file is among other .css files in the same directory, Django seems to have some sort of personal vendetta against this one file. On the face it it, what Django is doing is completely illogical. My settings are as follows: pip install whitenoise settings.py INSTALLED_APPS = [ .... 'django.contrib.staticfiles', .... ] BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [ BASE_DIR / "static/libraries/assets/brand-assets", BASE_DIR / "static/libraries/assets/images", BASE_DIR / "static/libraries/assets/vectors", BASE_DIR / "static/libraries/assets/videos", BASE_DIR / "static/libraries/css", BASE_DIR / "static/libraries/js", BASE_DIR / "static/main", BASE_DIR / "legal/static", BASE_DIR / "blog/static", BASE_DIR / "events/static", BASE_DIR / "careers/static", BASE_DIR / "media/static", BASE_DIR / "static", ] My file directory is as follows: PROJECT NAME-| Root-| settings.py careers-| static-| careers.css media-| static-| media.css blog-| static-| blog.css legal-| static-| legal.css static-| main-| xxx.css xxx.css libraries-| css # <- location of … -
401 unauthorized Django Rest API Login
Im having problems with my login API Endpoint, it was working the last time I checked, now after working blindly for a few hours it doesnt work anymore and i don´t know what i´ve done :) Register is working smoothly, the user also gets created in the db and is visible in the admin panel. The same credentials are not working for the login. I´ve posted the code below, thanks for the help in advance views.py #register new users @api_view(['POST']) def register_user(request): if request.method == 'POST': serializer = UserSerializer(data= request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.data,status=status.HTTP_400_BAD_REQUEST) #userlogin with authentication tokens @api_view(['POST']) def user_login(request): if request.method == 'POST': email = request.data.get('email') password = request.data.get('password') user = None if not user: user = authenticate(email = email, password=password) if user: #token creation for the logged in user token, _ = Token.objects.get_or_create(user=user) return Response(user.getDetails(), status=status.HTTP_200_OK) # type: ignore return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) models.py class CustomUser(AbstractUser): # username = models.CharField(max_length = 25 ,default = 'No name',unique = True) username = None email = models.EmailField(default ="no email",unique = True) first_name = models.CharField(max_length = 25 ,default = 'No name') last_name = models.CharField(max_length = 25, default = 'No surname') password = models.CharField(max_length = 25,default = "no … -
Deployment not found error on deploying django project on cpanel
I have an issue in deploying my django project to cpanel after creating the python setup on cpanel pointing my subdomain to the setup project .I get 404(deployment not found) error once i click the url how can i fix that i expect the project should show the passenger_wsgi.py IT Works Screen on click of the url -
make authenticated and login work for multiple table other then auth User table django?
I have created hostTable model in hostlogin app and I want to use this table for login purpose for that i have created custom authenticate function because default authenticate() was working for auth user table only. Also login() is not attaching current session to the users from hostTable. Although it working fine if I set AUTH_USER_MODEL ='hostlogin.HostTable' but then admin page is not working also this is not acceptable solution because hostTable I will use for teaches login (127.0.0.1:8081/tlogin/) and studentlogin table I will use for student login (127.0.0.1:8081/slogin/) that time how will I use two different table for different login() and authenticate (), for non of these two users I don't want to provide admin access (127.0.0.1:8081/admin/) that's why I am not using auth user table. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser,AbstractBaseUser,PermissionsMixin from django.contrib.auth.hashers import make_password, check_password class HostTable(AbstractBaseUser): pid=models.AutoField(primary_key=True,auto_created=True) username=models.CharField(max_length=50,unique=True) password=models.CharField(max_length=128) createdtime =models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(default=timezone.now) is_authenticated=models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS=['hostname','ownername','password'] def save(self, *args, **kwargs): self.password = make_password(self.password) super(HostTable, self).save(*args, **kwargs) def __str__(self): return self.hostname view.py def hostlogin(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') print('view',username,password) user = hostTableAuth.authenticate(request,username,password) … -
When we upload a selfie we get a 500 error [closed]
def upload_selfie_document(self,cleardil_id,document_id,selfie_image): url = f"{self.url}customers/{cleardil_id}/identifications" print(url, "url") selfie_image.seek(0) selfie_image = selfie_image.read() selfie_image_base64 = base64.b64encode(selfie_image).decode('utf-8') payload = json.dumps({ 'document_id': document_id, 'selfie_image': selfie_image_base64, }) # print(payload, "payload") headers = { **self.headers , 'Content-Type': 'application/json'} print(headers, "headers") try: response = requests.post(url, headers=headers, data=payload) print(response, "response") if response.status_code in range(400, 505): {response.text}") return None return response.json() except Exception as e: logger.error(f"Request exception: {str(e)}") return None I am trying to upload a selfie but I get response <Response [500]> response -
No output in serializermethodfield()
I defined a serializermethodfield. My problem in displaying the output. When this method exists, the image field is empty for me. But if I delete this serializermethodfield, my image output will be correct. serilizer: class ArticleSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) image=serializers.SerializerMethodField() class Meta: model=Article fields="__all__" validators=[Checktitle()] def get_image (self , obj ): request=self.context.get("request") if obj.image: image_url=obj.image.url return request.build_absolute_uri(image_url) return None view: class ArticleListview(APIView): def get(self,request): query_set=Article.objects.all() ser = ArticleSerializer(instance=query_set,many=True,context={'request':request}) print(request) return Response(data=ser.data) I wanted to change the url image. But by defining this method, the image is not saved at all. -
Unable to start Django app, error related to what seems like a circular import?
I'm currently attempting to build my first django app, a resume website. I get this error when trying to start the app. <class 'mainapp.admin.CertificateAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'is_active', which is not a callable, an attribute of 'CertificateAdmin', or an attribute or method on 'mainapp.Certificate'. This is what I have in my models.py file related to "certificate" (comments included): `class Certificate(models.Model): class Meta: verbose_name_plural = 'Certificates' verbose_name = 'Certificate' date = models.DateTimeField(blank=True, null=True) # When the certificate was earned name = models.CharField(max_length=50, blank=True, null=True) # Name of the certificate title = models.CharField(max_length=200, blank=True, null=True) # Title or description of the certificate description = models.CharField(max_length=500, blank=True, null=True) # Additional details about the certificate is_active = models.BooleanField(default=True)` And this is what I have in my admin.py file: @admin.register(Certificate) class CertificateAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'title', 'is_active') # Display 'id', 'name', and 'is_active' fields ChatGPT has been no help so far, only circular answers to make sure 'is_active' is properly called, I'm not sure it is, it seems like it (I'm sort of a beginner). I'm following instructions from a youtube video (yes, I have been learning python and django since last year, did not follow THAT blindly!), the "is_active" … -
Memcached-MemcacheIllegalInputError - Data values must be binary-safe: 'ascii' codec can't encode characters in position 2-5: ordinal not in range(128
I'm doing some tests with memcached on my django project to understand if I can get benefit of it. But I stuck at unicode character caching. I read many article about it but still could not understand how can I make it work. Here is my code block: def cache(request): client = Client("127.0.0.1:11211") cache_key = '123' # needs to be unique cache_time = 86400 # time in seconds for cache to be valid data = client.get(cache_key) # returns None if no key-value pair if not data: print("setting cache") #data contains unicode characters - Throws an error datafromdb = Subject.objects.all() #unicode characters - Throws an error unicodestr="abçüıö" #encoded unicode characters - Working fine encodedunicodestr=str.encode("abçüıö") client.set(cache_key,unicodestr , cache_time) else: print("getting from cache") return HttpResponse(data) So If I use str.encode on text values It works fine and data can be cached. But If I retrieve data from database(postgres) and this data contains unicode memcached throws an error. I'm wondering if is there a way to use str.unicode on my queryset/list etc that returned from database or something else may be. -
Unit Test pipeline - Django Unit tests
I am working on a django project and it has 20+ apps in it which means i have to run tests of 20+ apps which includes 3000+ tests. So I decided to make subjobs in my pipeline and now running 20 jobs for the unit tests on commit. But the issue is that when more than 1 developer commits and tests runs for both, pipeline get stucks. Pipeline runners are registered on a VM of 32 CPU cores and 24 GB of RAM. CPU utilization becomes 100% and jobs stuck(deadlock). How can I optimize my pipeline subjobs so that if multiple devs work it didnt stuck. unit_test: stage: test rules: - changes: - backend/ tags: - workstream-unit-test when: manual allow_failure: false parallel: matrix: - APP_NAME: - apps.app1 - apps.app2 - . - apps.app20 before_script: - apt-get update - apt-get install -y unixodbc unixodbc-dev - pip install virtualenv - virtualenv venv - source venv/bin/activate - pip install -r requirements.txt script: - COVERAGE_FILENAME=$(echo "$APP_NAME" | tr '.' '_')_coverage.xml - coverage run --source=$APP_NAME ./manage.py test $APP_NAME --settings=hrdb.test_settings --keepdb --noinput - coverage xml -i -o $COVERAGE_FILENAME - coverage report -m --fail-under=90 --skip-covered coverage: '/(?i)TOTAL.*? (100(?:\.0+)?%|[1-9]?\d(?:\.\d+)?%)$/' artifacts: expire_in: 2 hour paths: - $CI_PROJECT_DIR/$APP_NAME_coverage.xml I am … -
Find Template in django
My code is like below. {% if request.path != '/login/' %} {% include "/hospital/templates/header.html" %} {% endif %} I am getting error TemplateDoesNotExist at /dashboard/ /hospital/templates/header.html How to include a template ? -
Django Rest Framework APIClient login is not working
I have test function to test whether user can login or not. I am using DRF's APIClient and logging in. When I do a get request to a protected API endpoint I get 401 response. I tried to print: print(client.login(username='instructor', password='asdf')) And it is returning True, which means user is found and logged in. But still when I do: response = client.get(reverse('recommend-list')) I am getting 401. Here is my test function: ` def test_user_authentication(self): client = APIClient() user_data = { 'username': 'instructor', 'email': 'myemail@example.com', 'password': 'asdf' } client.post(reverse('user-list'), user_data, format='json') self.assertTrue(User.objects.filter(username='instructor').exists()) print(client.login(username='instructor', password='asdf')) response = client.get(reverse('recommend-list')) self.assertEqual(response.status_code, 200) ` Here is how I create a new user: `class UserViewSet(viewsets.ViewSet): def create(self, request): serializer = UserSerializer(data=request.data) User = get_user_model() if serializer.is_valid(): validated_data = serializer.validated_data try: user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'] ) return Response({'id': user.id, 'username': user.username}, status=status.HTTP_201_CREATED) except IntegrityError: return Response({'error': 'Username is already taken.'}, status=status.HTTP_400_BAD_REQUEST) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ` Making get request to here: `class RecommendViewSet(viewsets.GenericViewSet): authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] def list(self, request): user_id = request.user.id movies = recommend_movies_for_user(user_id) return Response({"message": movies}, status=status.HTTP_200_OK) ` -
I want to add social links to my template in django
<ul class="list-unstyled d-flex"> <li class="ms-3"><a class="link-body-emphasis" href="#" ><i class="fa-brands fa-square-github fa-lg" ></i></a></li> <li class="ms-3"><a class="link-body-emphasis" href="#"><i class="fa-brands fa-facebook fa-lg" ></i></a></li> <li class="ms-3"><a class="link-body-emphasis" href="#"><i class="fa-brands fa-linkedin fa-lg" ></i></a></li> </ul> i want to add social links of my facebook , github and linkedin how can i do that in django without writing a view or url path just pasting my social links in href did'nt working -
how to save image in Django project
when i try to create new employee in my project the instance has been save but image not. here is my model,view and form from my django project my model- `class Emp(models.Model): emp_first_name=models.CharField(max_length=20,null=False) emp_last_name=models.CharField(max_length=20,null=False) emp_father_name=models.CharField(max_length=15,blank=False,default='') emp_mother_name=models.CharField(max_length=15,blank=False,default='') emp_photo=models.ImageField(null=True,blank=True,upload_to='static/image/emp',)` my view- `def EmpAdd(request): if request.method=='POST': form=EmpForm(request.POST,request.FILES) if form.is_valid(): form.save() messages.success(request,'New Employee has been added') else: messages.error(request,'There has been error') else: form=EmpForm() return render(request,'emp/emp_crt.html',{'form':form})` my form - `class EmpForm(ModelForm): class Meta: model=Emp fields='__all__' widgets={ 'emp_id':TextInput(attrs={'class':'form-control',}), 'emp_bod':DateInput(attrs={'type':'date','class':'form-control',}), 'emp_first_name':TextInput(attrs={'class':'form-control',}), 'emp_last_name':TextInput(attrs={'class':'form-control',}), 'emp_father_name':TextInput(attrs={'class':'form-control'}), 'emp_mother_name':TextInput(attrs={'class':'form-control'}), 'emp_photo':FileInput(attrs={'class':'form-control'}), }` when i try to creat new employee in my django project, new employee has been created but image has not been saved.what should i do? -
type error in api profile in django rest framework
typeError at /api/profile/ init() got an unexpected keyword argument 'write only' Request Method: GET Request URL: http://127.0.0.1:8000/api/profile/ Django Version: 3.2.25 Exception Type: TypeError Exception Value: init() got an unexpected keyword argument 'write only' Exception Location: /home/vagrant/env/lib/python3.6/site-packages/rest_framework/fields.py, line 738, in init Python Executable: /home/vagrant/env/bin/python3 Python Version: 3.6.9 Python Path: ['/vagrant', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/vagrant/env/lib/python3.6/site-packages' everything in the code was correct, can't able to access the api/profile page in django server. -
How to fetch all the API urls from django project in Python?
I have a django project, where some API URLs are present in urls.py in urlpatterns path and some are registered as routers(rest_framework_extensions.routers). ref: # urls.py urlpatterns = [ path("healthcheck/", health_check_view, name="healthcheck"), path("something/", include(router_something.urls)) ] here, router_something is being used to register further urls like: router_something = DefaultRouter(trailing_slash=False) router_something.register(r"path1/(?P<pk>\d+)/roles", SomeViewSet) I want to fetch all the urls in the django project with their complete path, for example: healthcheck/ something/path1/1/roles # here i am replacing the placeholder pk with 1, this is something I can do ... -
triggers error in admin default not showes. Why?
InternalError at /admin/entities/branch/add/ The type of building does not match the expected type: 'Branch' CONTEXT: PL/pgSQL function check_outlet_type_consistency() line 9 at RAISE How show in default django admin this error? googled, :( but no info -
I can't import TinyMCE
HELLO. No matter what I did, I couldn't import Tinyemc. I don't just get this error on Tinyemc; This problem exists in everything that is similar. [enter image description here](https://i.sstatic.net/5GjZoaHO.png) [enter image description here](https://i.sstatic.net/BHWlmsFz.png) [enter image description here](https://i.sstatic.net/65a3OvdB.png)your text` I couldn't find a solution to the problem in any way.`your text`` -
Text with Image Django Admin
i'd like to know how can i have a fancy editor in django admin, that can add images inside the content, like ckeditor, but when it saves, it converts all in base 64 and store it in the database istead uploading the files to a media folder. Thanks. I've tried to use ckeditor 5, but it stores the images appart the content in a separated folder. -
default datetime value at django form
i'm trying to use a default value class MSeguimientoEtnicoForm(forms.ModelForm): ... fecha_reporte = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class': 'form-control'})) ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Establece la fecha y hora actuales como valor inicial para fecha_reporte self.fields['fecha_reporte'].initial = timezone.now() template: <div class="col-sm-4"> <div class="form-group"> <label for="fechaReporte">Fecha Reporte: </label> <input class="form-control" id="fechaReporte" type="datetime-local" name="fecha_reporte" required> </div> </div> but doesn't take the timezone.now() value at the view template view and default value don't working i was searching for aroud but i didn't found nothing