Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF Token missing when it's there
I have a form, containing different form objects inside from the forms.py. However, when I try to submit the form, it says, "csrf verification failed" Here is the full template (sorry for the mess I'll structure the js later before launch) <!DOCTYPE html> {% load static %} {% load widget_tweaks %} <html lang="en"> <head> <head> <title>{{app.name}}</title> <!-- Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="author" content="Webestica.com"> <meta name="description" content="Bootstrap 5 based Social Media Network and Community Theme"> <!-- Dark mode --> <script> const storedTheme = localStorage.getItem('theme') const getPreferredTheme = () => { if (storedTheme) { return storedTheme } return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'light' } const setTheme = function (theme) { if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) { document.documentElement.setAttribute('data-bs-theme', 'dark') } else { document.documentElement.setAttribute('data-bs-theme', theme) } } setTheme(getPreferredTheme()) window.addEventListener('DOMContentLoaded', () => { var el = document.querySelector('.theme-icon-active'); if(el != 'undefined' && el != null) { const showActiveTheme = theme => { const activeThemeIcon = document.querySelector('.theme-icon-active use') const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`) const svgOfActiveBtn = btnToActive.querySelector('.mode-switch use').getAttribute('href') document.querySelectorAll('[data-bs-theme-value]').forEach(element => { element.classList.remove('active') }) btnToActive.classList.add('active') activeThemeIcon.setAttribute('href', svgOfActiveBtn) } window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (storedTheme !== 'light' || storedTheme !== 'dark') { setTheme(getPreferredTheme()) } }) showActiveTheme(getPreferredTheme()) document.querySelectorAll('[data-bs-theme-value]') .forEach(toggle => … -
Django not appening "/" on urls in a production server
I have a website written in Django. The website for production or development is deployed in a docker container. It is served over nginx that is also deployed in a docker container. On a development computer when the website is deployed and an address is input without a trailing "/" it is automatically appended and then redirected to the correct page. In a production server, this isn't happening. No redirection commences and the server returns 404. The only difference between development and production is that the production instance is run with SSL and a domain name. Here are my NGINX configs for both situations. Development: upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } } Production: upstream django { server django_gunicorn:8000; } server { listen 443 ssl; ssl_certificate /ssl/live/fullchain.pem; ssl_certificate_key /ssl/live/privkey.pem; server_name website.mydomain.com; location / { proxy_pass http://django; } location /static/ { alias /static/; } } What is the issue, why production server is not redirecting? -
Django: static file serve does not work only when the url is "static/"
I have the following urls.py - urlpatterns = [ path('admin/', include("admin.urls")), path('accounts/', include("accounts.urls")), path('blogs/', include("blogs.urls")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In the settings.py I have - STATIC_URL = 'static/' STATIC_ROOT = 'static/' Here my static files in the static folder are showing a "Page Not Found (404)" error. But ifI change settings.STATIC_URL to anything else, it works. For example, if I do - static("anything/", document_root=settings.STATIC_ROOT), then it works, only the strings that start with 'static' does not work. Can anyone shed some light on this behaviour? -
JavaScript does not work when running Django on the local network. In 2024
My project ( https://github.com/Aleksandr-P/django-audio-recorder2024 ) works well on a local computer under Windows 10. If I run python manage.py runserver . After making changes: ..\web_project\settings.py ALLOWED_HOSTS = [] on the: ALLOWED_HOSTS = ['*'] And python manage.py runserver on python manage.py runserver 0.0.0.0:80 JavaScript stops working. How to fix it? I checked in the browser, the file audio_recorder\static\audio_recorder\recorder.js available. But it doesn't work. -
Python social auth and drf social oauth
I need help of community. In my Django project with django-rest-framework, we use JWT authentication and want to implement the social login by google. So, I installed and configured drf-social-oauth2 with backend google-oath2 in the project as shown in docs. settings.py INSTALLED_APPS = [ ... "social_django", "oauth2_provider", "drf_social_oauth2", ... ] ... TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ... ], }, } ] REST_FRAMEWORK = { ... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "drf_social_oauth2.authentication.SocialAuthentication", ), } AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "drf_social_oauth2.backends.DjangoOAuth2", "social_core.backends.google.GoogleOAuth2", ) SOCIAL_AUTH_REQUIRE_POST = True ACTIVATE_JWT = True SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ] SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env( "SOCIAL_AUTH_GOOGLE_OAUTH2_KEY", default="SOCIAL_AUTH_GOOGLE_OAUTH2_KEY" ) SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env( "SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET", default="SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET" ) urls.py urlpatterns = [ ... path("", include("social_django.urls", namespace="social")), path("auth/", include("drf_social_oauth2.urls", namespace="drf")), ] And now the question itself. How to implement redirection with the necessary data after user authorization on an external resource? I have a user's entry point with a redirect to google authorization path( "sign_in/google", views.AuthViewSet.as_view({"post": "sign_in_google"}), name="sign_in_google", ), method @extend_schema(request=None, responses={302: None}) def sign_in_google(self, request, *args, **kwargs): strategy = load_strategy(request) backend = load_backend( strategy=strategy, name="google-oauth2", redirect_uri=f"{self.request.scheme}://{self.request.get_host()}/complete/google-oauth2/", ) return do_auth(backend, REDIRECT_FIELD_NAME) And if I follow as per our requirements we need the user to redirect to google-oauth2 page and … -
Django App fails to deploy on AWS ElasticBeanstalk with pywin32==306
I am stuck here since 2 days. Someone please help. Django App works fine locally but fails to deploy on AWS ElasticBeanstalk with pywin32==306. Platform: Python 3.11 running on 64bit Amazon Linux 2023/4.0.8. I am using windows 11. Python Version : 3.12.2. PIP version : 23.3.2. Please find below requirements.txt: asgiref==3.7.2 awsebcli==3.20.10 beautifulsoup4==4.12.3 botocore==1.31.85 cement==2.8.2 certifi==2024.2.2 charset-normalizer==3.3.2 colorama==0.4.3 distlib==0.3.8 Django==4.2.10 django-bootstrap-v5==1.0.11 filelock==3.13.1 idna==3.6 jmespath==1.0.1 pathspec==0.10.1 platformdirs==4.2.0 psycopg-binary==3.1.17 psycopg2-binary==2.9.9 pypiwin32==223 python-dateutil==2.8.2 pywin32==306 PyYAML==6.0.1 requests==2.31.0 semantic-version==2.8.5 setuptools==69.0.3 six==1.16.0 soupsieve==2.5 sqlparse==0.4.4 termcolor==1.1.0 tzdata==2023.3 urllib3==1.26.18 virtualenv==20.25.0 wcwidth==0.1.9 whitenoise==6.6.0 Getting the following error: 2024/02/15 13:12:10.274129 [ERROR] An error occurred during execution of command [self-startup] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 1. Stderr:ERROR: Could not find a version that satisfies the requirement pywin32==306 (from versions: none) ERROR: No matching distribution found for pywin32==306 Complete AWS Log : https://drive.google.com/file/d/1ZbS3aVnHS2fg8-e9QDihnhzuHxB_CPDf/view?usp=sharing I upgraded the PIP and also tried pywin32==306;platform_system == "Windows" but in vain. -
How works super().get_queryset() in Django?
I am trying to get a queryset of questions that have publication date before today's date, but I am getting an error in get_queryset raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: IndexView is missing a QuerySet. Define IndexView.model, IndexView.queryset, or override IndexView.get_queryset(). My code: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return super().get_queryset().filter(pub_date__lte=timezone.now()) But this code works: def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) What I am doing wrong? Thanks in advance -
django-tailwindcss integration image not displayed
I already have a Django project with template file index.html but my image is not displaying I try everything including {% load static %} but still it is not working may be because i used {% load tailwind_tags %} and {% tailwind_css %} and i also created file as mentioned in Django official website for static file but still it is not working. -
can't run cron file with docker -compose what i can do?
I use Django and postgres to them, I wrote a script that scrapes data and writes to the database and another that dumps. And these scripts should run at a certain time, as if in the logs I see that it is raised, but when I run it, it does not work PS C:\Users\komar\django-scraper-6> docker exec -it scrap bash root@0296ba2fb7f3:~/django_scraper# supervisorctl status cron RUNNING pid 9, uptime 0:09:37 server EXITED Feb 15 10:26 AM root@0296ba2fb7f3:~/django_scraper# supervisorctl start server server: started root@0296ba2fb7f3:~/django_scraper# supervisorctl status cron RUNNING pid 9, uptime 0:11:02 server EXITED Feb 15 10:37 AM dockerfile FROM python:latest WORKDIR /root/django_scraper/ RUN apt-get update && apt-get install -y cron supervisor COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./app ./app COPY configs/supervisord.conf /etc/supervisor/conf.d/supervisord.conf COPY configs/cronfile /etc/cron.d/cronfile RUN crontab /etc/cron.d/cronfile ENTRYPOINT /usr/bin/supervisord cronfile # START CRON JOB LIST 0 12 * * * python /root/django_scraper/app/scrap_file.py >> /tmp/postgres_dump.log 2>&1 0 13 * * * python /root/django_scraper/app/db_dump.py # END CRON JOB LIST my repo https://github.com/yurakomarnitskyi/django-scraper dockerfile FROM python:latest WORKDIR /root/django_scraper/ RUN apt-get update && apt-get install -y cron supervisor COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./app ./app COPY configs/supervisord.conf /etc/supervisor/conf.d/supervisord.conf COPY configs/cronfile /etc/cron.d/cronfile RUN crontab /etc/cron.d/cronfile ENTRYPOINT /usr/bin/supervisord cronfile # … -
Embedded link displays when hardcoded but not when passed as variable
I have the following problem in my django project when trying to display an embedded google maps link in my page. This works (renders the Google Maps iframe with a populated map) when I hardcode the src URL but not when I pass it in my context even though they result to the same text string. This is my html detailview.html: {% if maps_link is not None %} <iframe src="https://maps.google.com/maps?q=-28.4457436,21.268374&hl=en&z=14&amp;output=embed" loading="lazy" referrerpolicy="no-referrer-when-downgrade" ></iframe> {% endif %} The src URL as it is shown above displays as I want it to, but when I do the following: {% if maps_link is not None %} <iframe src="{{ maps_link }}" <!-- This gets blocked --> loading="lazy" referrerpolicy="no-referrer-when-downgrade" ></iframe> {% endif %} then my browser gives me the following warning: To protect your security, www.google.com will not allow Firefox to display the page if another site has embedded it. To see this page, you need to open it in a new window. This is my views.py where the context is generated. I tried to get around it by applying xframes exemptions but that made no difference: from django.views.decorators.clickjacking import xframe_options_exempt from django.http import Http404, HttpResponse @xframe_options_exempt def detail(request, database_reference): context = { "content" : … -
Is there a way to upload file in django database from reactjs form
I have a problem with the form data. It says the submitted data is not a file type when I want to post data from React to Django models. I try to upload file with form .I used multipart/form-data in react component and also tried append file, and post it with axios. -
Django-nested-admin has no classes
I installed django-nested-admin, but it doesn`t work. I did it correctly first of all i added to settings py to INSTALLED APPS. then i imported it to admin py. but it didn`t work. What I have to do to solve this problem. does anyone help me? -
Django DRF not releasing memory after large response data is send to the front end
I am using Django rest framework in our application's backend. In one of the api end points we have to send a large data as response. So the orm and serialization functionalities takes about 400mb to send the data to the front end. I am using memory_profiler and when we call another api or the same api it shows 400mb at start and then an additional 400mb is used if the same endpoint is called. So total 800mb. It keeps on adding whenever we call the api till it crashes. This is my code ---> **views.py ** @api_view(["GET"]) @hasValidToken def get_all_session_messages(request, user, identity_data, *args, **kwargs): try: return chat_services.get_all_session_messages( user.id, kwargs["session_id"], ) except Exception as exc: return error(message=str(exc)) **services.py ** def get_all_session_messages(user_id, chat_session_id): try: query_responses = chat_repository.get_all_query_response_given_chat_id( chat_session_id ) return ok( message="Successfully retrieved all chat session messages", response_data=query_responses, ) except Exception as exc: raise Exception( "Error retreiving chat session messages in repository " + str(exc) ) **repository.py** def get_all_query_response_given_chat_id( chat_id, limit=None, order_by_created_at=False ): if not order_by_created_at: if limit is not None: query_responses = QueryResponseTracking.objects.filter(chat_id=chat_id)[ :limit ] else: query_responses = QueryResponseTracking.objects.filter(chat_id=chat_id) else: if limit is not None: query_responses = QueryResponseTracking.objects.filter( chat_id=chat_id ).order_by("-created_at")[:limit] else: query_responses = QueryResponseTracking.objects.filter( chat_id=chat_id ).order_by("-created_at") return QueryResponseTrackingSerializer(query_responses, many=True).data **serializers.py** … -
ThreadPoolExecutor from concurrent.futures module of Python for DRF appliction
I have simple GET Project API, The following is my code approach ` class ProjectListCreateView(generics.ListCreateAPIView): queryset = Project.objects.filter(is_deleted=False) serializer_class = ProjectSerializer def convert_to_json(self, state): return State.convertProjectObjectToJSON(self, state=state) def get(self, request, *args, **kwargs): try: objects = self.get_queryset() with ThreadPoolExecutor(max_workers=8) as executor: json_response = list(executor.map(self.convert_to_json, objects)) response = response_body(status_code=status.HTTP_200_OK, data=json_response) return Response(response, status=status.HTTP_200_OK) except Exception as e: response = response_body(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, data={str(e)}) return Response(response, status=status.HTTP_500_INTERNAL_SERVER_ERROR)` This APIs taking 970ms for 200 Projects. My question is Is this depends on the Threads so What should I need to deploy it on azure, do I have to make any changes regarding server configs or something else? -
react+django questions about https(SSL certificate)
I created a website using react and django. React was used as a front-end, Django was used as a back-end.(React uses S3, and Django uses EC2 server.) I was asked to adapt the website to HTTPS. I know I need to use SSL certificate. However, the front-page running on S3 can use and SSL certificate, so HTTPS is applicable, but the server running on EC2 can't use an SSL certificate. Because EC2 uses IP address, not useing Domain address. There are times when I need to make an API call to "http://my_ip_address/~" on the my website, but it keeps getting blocked. Please help me. How should I solve it? Do I need to add another Domain address to the EC2 server......? Or Is there a way to make a request from HTTPS to HTTP using CORS? I really need your help....! I applied SSL certificate to S3(front-page). But EC2 server is still HTTP. Django "settings.py" file : ... CORS_ALLOW_ALL_ORIGINS = True ... I also applied the above settings. -
How to run django celery tasks with persistent event loop and asyncio calls with proper DB reconnections?
I have a django and celery, postgresql with psycopg2 driver and an external dependency with heavy setup calls which is hard to modify and which saves and reuses asyncio event loop after first invocation. I also have an asyncio call which I need to run in the celery task. This method uses this external dependency internally. It seems that I can't use async_to_sync django call because it doesn't allow me to preserve the loop. Therefore, subsequent tasks executions raise Event loop is closed when I invoke dependency lib calls. I used the following way to handle that: class ExampleModel(models.Model) name = models.CharField() async def my_method(): example_entry = await ExampleModel.objects.aget(id=1) # external async dep call here return example_entry @shared_task(name="example_task", bind=True) def example_task(self): asyncio.get_event_loop().run_until_complete(my_method()) It has worked perfectly for a few months, until we had a restart of the database and connection was lost. All further tasks had django.db.utils.InterfaceError: connection already closed error. Digging in, I created a set of test tasks: @shared_task(name="debug_task_async_to_sync") def debug_task_async_to_sync(self): import asgiref.sync res = asgiref.sync.async_to_sync(my_method)() print("async_to_sync", res) @shared_task(name="debug_task_loop") def debug_task_loop(self): res = utils.get_event_loop().run_until_complete(my_method()) print("loop", res) @shared_task(name="debug_task") def debug_task(): res = models.ExampleModel.objects.get(id=1) print("sync", res) and restarted the database in the time of their execution. Both sync debug_task and … -
Why do Django custom validation messages not display on the HTML page?
I have the following custom username validation method. This method is executed when I submit the form, but it does not display the error message. However, other default field validations are working fine. def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError("This username already taken. please choose another.") return username Here is the HTML code for the username input: <input type="text" name="username" class="form-control" id="username" required> <span class="invalid-feedback" role="alert"> {{ form.username.errors.0 }} </span> -
Django Integrity Error instead of Bad Request Error
So I have DRF project using a custom user that extend the AbstractUser, and I want to make the email unique. I tried to change the AbstractUser like this. class AbstractUser(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username and password are required. Other fields are optional. """ username_validator = UnicodeUsernameValidator() username = models.CharField( _("username"), max_length=150, unique=True, help_text=_( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[username_validator], error_messages={ "unique": _("The username already exists."), }, ) first_name = models.CharField(_("first name"), max_length=150) last_name = models.CharField(_("last name"), max_length=150) email = models.EmailField(_("email address"), unique=True, error_messages={ "unique": _("A user with that email already exists."), }) It verified the duplication of the email, but I got Integrity Error, but I want to get Bad Request for my frontend What's wrong, why fields in AbstractUser produce different error for unique constraint? Please help me, thanks in advance. -
Django redirect is not passing keyword parameters
I am redirecting from a view in one app, to a view in another. Its finding the view just fine but not passing the arguments. I've tried passing it as positional and keyword but cant get the thing to work. if request.method == 'POST': username = request.POST['username'] pass1 = request.POST['pass1'] user = authenticate(username=username, password=pass1) if user is not None: login(request, user) print(user.username, type(user.username), file=sys.stderr) return redirect(reverse('homepage'), user.username) else: messages.error(request, "Bad Credentials!") return redirect('index') @login_required() def homepage(request, username=None): print(username, file=sys.stderr) try: user = userAttribute.objects.get(username=username) except userAttribute.DoesNotExist: return redirect("index") [14/Feb/2024 18:15:18] "GET /signin HTTP/1.1" 200 824 Kane <class 'str'> [14/Feb/2024 18:15:23] "POST /signin HTTP/1.1" 302 0 None -
Using django test fixtures without signals
I am writing code for a web app in python/ django. In the app there is a User model and other models with a OneToOne key to the User model. I want entries in these other models to be created when the user signs up, so I have been using signals. The problem is I am using test fixtures. Some of these fixtures trigger the signal and mean other fixtures are overridden/ not used/ cause integrity errors in the database. How can I make it so that I do not clal signals for these tests, so the database is set up with only my fixtures? (I want to do separate tests while using signals later, but tests with fixtures are non negotiable in my case, so that takes priority). I need to upkeep code quality aswell. Do I change my approach? Error recieved: Integrity error for UNIQUE constraint I have tried Using post_save.disconnect and hten manually loading fixtures with loaddata Overriding the signals using 'with post_save' and then loading fixtures with loaddata -
Error while integrating google OAuth with superset
To integrate Google authentication into my Superset application, which is running on a specific IP address, I followed these steps: Created an OAuth client ID on the Google Cloud Platform. To create it, a JavaScript Authorized Origin is required, which is basically the application's URL. Since my Superset application does not have a domain, I masked the <superset-IP> with a random domain (http://localtesting.com) in my local etc/hosts file. I used this masked domain in the Google Console for creating the client ID. Updated the superset_config.py file with the client ID, client secret, and app domain. Here is the file for your reference: from flask_appbuilder.security.manager import AUTH_OAUTH ENABLE_PROXY_FIX = True AUTH_TYPE = AUTH_OAUTH OAUTH_PROVIDERS = [ { "name": "google", "icon": "fa-google", "token_key": "access_token", "remote_app": { "client_id": "<ClientId", "client_secret": "<ClientSecretKey>", "api_base_url": "https://www.googleapis.com/oauth2/v2/", "client_kwargs": {"scope": "email profile"}, "request_token_url": None, "access_token_url": "https://accounts.google.com/o/oauth2/token", "authorize_url": "https://accounts.google.com/o/oauth2/auth", "authorize_params": {"hd": "http://locatesting.com"} }, } ] AUTH_ROLE_ADMIN = 'Admin' AUTH_ROLE_PUBLIC = 'Public' Restarted the VM where superset is hosted. After completing these steps, I encountered a 502 Bad Gateway error. My Superset application is using an Nginx server. Is this issue somehow associated to nginx or anything wrong in masking of IP in my local machine -
fcm-django add badge to Aps for ios platform
I use fcm-django library def get(self, request, *args, **kwargs): user = request.user devices = FCMDevice.objects.filter(user=user) body_data = { "title": "Title text", "body": "Click to explore more", } extra_data = {"type": "some information", "link": "https://google.com", "badge": str(10)} for device in devices: try: if device.type == "ios": device.send_message(Message(notification=FCMNotification(**body_data), data=extra_data)) else: device.send_message(Message(data={**body_data, **extra_data})) except Exception as e: return Response({'error_message': str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_200_OK) I need add badge value to Aps for ios. I've tried apns = { "badge": 10, } device.send_message(Message(notification=FCMNotification(**body_data), data=extra_data, apns=Aps(apns))) But got error and no PN. How can I do it correctly? -
Django- getting the value of 'models.DateField(default=datetime.datetime.today)' in view
I have this model: models.py: class myModel(models.Model): a = models.ForeignKey(P,on_delete=models.CASCADE) ... **date = models.DateField(default=datetime.datetime.today)** In the views.py, I get the data of "date" field: views.py from appX.models import myModel from datetime import datetime ... def my_items(request): ... got_date = myModel.objects.get(id = 1).date got_date_2 = datetime.strptime(got_date, "%YYYY-%MM-%d") But python throws the following error: time data '"2024-02-14"' does not match format '%YYYY-%MM-%d' What "format" should I use ? Thanks. -
Different outputs between Django Server and PyCharm
I am facing an issue that I get different outputs running the same code throw PyCharm and throw the Django Server. PyCharm gives the output expected and needed, so it is an issue to fix. Because I only use PyCharm for testing. The input string: # HTML HTML is a markup language that can be used to define the structure of a web page. HTML elements include * headings * paragraphs * lists * links * and more! The most recent major version of HTML is HTML5. The Code is: # A list of simple markdown and there html aquvalents. # First element is the inner html/markdown second is the whole markdown, third is the starting html tag and fourth the closing html tag regex_hugging_html = [ [r"(?<=^#{1})[^#][^\n]*$", r"^#{1}[\s]*[^#][^\n]*$", "<h1>", "</h1>"], # heading first level (#) [r"(?<=^#{2})[^#][^\n]*$", r"^#{2}[\s]*[^#][^\n]*$", "<h2>", "</h2>"], # heading second level (##) [r"(?<=^#{3})[^#][^\n]*$", r"^#{3}[\s]*[^#][^\n]*$", "<h3>", "</h3>"], # heading third level (###) [r"(?s)\*\*(.*?)\*\*", r"(?s)\*\*.+?\*\*", "<b>", "</b>"], # boldface (** **) [r"(?s)__(.*?)__", r"(?s)__.+?__", "<b>", "</b>"], # boldface (__ __) [r"(?s)\n{2}(.+?)(?=\n{2}|\Z)", r"(?s)(\n{2}.+?)(?=\n{2}|\Z)", "<p>", "</p>"], # paragraphs (blank line) ] def markdown_to_html(markdown): html = markdown for replacer in regex_hugging_html: # Find all occurances of the markdown expression for substr in re.compile(replacer[0], … -
How to save data from CKEditor via Django Rest Framework using javascript (vanilla)
Im writing an application that has a function for adding a document. For this reason i needed some rich text editor for formatting the documents. so here is my views.py for rendering my html: def add_document_view(request): if request.user.is_authenticated: categories = Category.objects.all() languages = get_language_choices() context = {"allCategories":categories, "form":PostForm, "languages":languages} return render(request, "documents/add-document.html", context) return JsonResponse({"status":"500 Auth Error"}) add-document.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add Document</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> </head> <body> <div class="container mt-5"> <h1>Add Document</h1> <hr> <form method="POST" action="#"> {% csrf_token %} <div class="form-group"> <label for="title">Header:</label> <input type="text" class="form-control" id="header" name="header" placeholder="Enter document header" required> </div> <div class="form-group"> <label for="category">Category:</label> <select class="form-control" id="category" name="category" required> <option value="" disabled selected>Select category</option> {% for category in allCategories %} <option value="{{ category.id }}">{{ category.title }}</option> {% endfor %} </select> </div> <div class="form-group"> {{form.media}} {{form.as_p}} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <script src="https://cdn.ckeditor.com/ckeditor5/38.0.0/classic/ckeditor.js" defer></script> </body> </html> models.py from django.db import models from ckeditor.fields import RichTextField from simple_history.models import HistoricalRecords from .utils import get_language_choices class Category(models.Model): title = models.CharField(max_length = 64, unique = True) def __str__(self): return self.title class Document(models.Model): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' …