Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Neovim unable to detect Django packages: Getting 'Unable to import 'django.*' error
I've recently configured Neovim for my development workflow, but I'm encountering an issue with Django packages not being detected properly. Whenever I try to import any Django package or use Django functions within Neovim, I receive an error message like this: Unable to import 'django.conf' I've ensured that Django is properly installed and working outside of Neovim, but within Neovim, it seems to have trouble locating the Django packages. I've checked my Neovim configuration and paths, but I'm not sure where the problem lies. Has anyone encountered a similar issue with Neovim and Django packages? How can I troubleshoot and resolve this problem to get Neovim to properly detect Django packages? Any help or suggestions would be greatly appreciated. Thank you! -
How to log in an user coming from an external link into django application
I have a Django application using the out-of-the-box Django authentication system. I need to make an integration with another web app. The users in the other web app will click a button that should take them to my web application and give them access. The other web app will send me the user's email and other data. I should create the user if it doesn't exist without asking for any credentials. I'm not sure what approach I should take. I want something simple but not too insecure. Is SSO or OAuth the way to go? I think this is generally used to sign in with Google or Facebook, etc, but in this case, we don't want to depend on Google/Facebook accounts, the users use business emails. I'm thinking of having the third-party app use a secret key to encrypt an API Token, when the user clicks the button on their app, they will send a redirect to my app with the user data and the encrypted token. I will use the secret key to validate the Token and give the user access. I want guidance on what approach is more convenient, the responsibilities of each app, and how to implement … -
React + Docker: Failed to resolve import
I've been beating my head against a wall here trying to solve this, but I keep getting the following error that I can't resolve whenever I try to yarn add something and then use it: PM [vite] Internal server error: Failed to resolve import "@mui/x-data-grid" from "src/components/formSubmit.tsx". Does the file exist? Could I be somehow screwing up my node_modules? I think my docker script is correct, and I've checked that it exists in node_modules on the image, but I still seem to be getting this issue. My folder structure is: --Myapp |--frontend -node_modules -package.json -index.html - public - src - App.tsx - index.tsx - components - formsubmit.tsx - tsconfig.json - vite.config.js - vite-env.d.ts |--compose |--local |--react |--django |--djangobackend Docker-compose: version: '3' volumes: myapp_local_postgres_data: {} myapp_local_postgres_data_backups: {} services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: myapp_local_django container_name: myapp_local_django depends_on: - postgres volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - '28000:8000' command: /start react: build: context: . dockerfile: ./compose/local/react/Dockerfile image: myapp_react container_name: myapp_react depends_on: - postgres - django volumes: - ./frontend:/app - /app/node_modules/ ports: - 28001:3000 environment: - NODE_ENV=development command: yarn start Frontend dockerfile: ARG BUILD_ENVIRONMENT=local FROM node:lts-bookworm-slim WORKDIR /app COPY ./frontend/package.json . #COPY ./frontend/yarn.lock . COPY ./frontend/src . COPY … -
Reducing docker image size: multistage build or other suggestions
I am trying to deploy my Django app with docker. This is my original docker file FROM python:3.10.5-slim ENV DockerHOME = /app WORKDIR $DockerHOME COPY requirements.txt . RUN pip install --upgrade pip COPY . $DockerHOME RUN pip install --nocache-dir -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver"] After it build however, the image size was 300MB which was too big. I then tried doing a multi stage build as follow (which according to google can help reduce the image size significantly): FROM python:3.10.5-slim as base ENV DockerHOME = /app WORKDIR $DockerHOME COPY requirements.txt . RUN pip install --upgrade pip RUN pip install --nocache-dir -r requirements.txt FROM python:3.10.5-slim COPY --from=base $DockerHOME $DockerHOME COPY . $DockerHOME WORKDIR $DockerHOME EXPOSE 8000 CMD ["python", "manage.py", "runserver"] But this also resulted in an image that was 300MB. Could someone help me with this? I have 2 questions: Is the multistage Dockerfile logical? I feel that there is something wrong which would explain why there was no significant reduction in the image size. Are there any other ways to reduce the image size? I was originally using 'FROM python:3.10.5' instead of 'FROM python:3.10.5-slim' and that gave me 600MB image size. I changed to slim and it … -
Django, form/widgets/input.html problems
I'm tryning to change the django input dault,in teory i just need to copy the path from the github django project, but form some reason is not using mine, is just using the default input Django path my path. i really don't know whats the matter, i already try with another browser, and deleting the browser cache -
CSV file not coming through on submission of html form via POST method (in the context of using Django)
I am building a very simple application which includes one page where a user submits a list of zip codes and then is returned a file with zip codes in a certain radius of the original list. My problem is that my function for processing the file that is contained in the views.py file is not able to retrieve the '.csv' file after the post form. The FILES metadata on the request is missing and I cannot figure out why. More details below: Error I am seeing: Internal Server Error: /zip_app/ Traceback (most recent call last): File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/utils/datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'csvFile' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) File "/home/louis/Documents/github/zip_radius_tool/zip_radius_app/zip_app/views.py", line 30, in index f = request.FILES['csvFile'] File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/utils/datastructures.py", line 86, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'csvFile' HTML for the index page where the user submits the .csv file: <!DOCTYPE html> <html lang="en"> <head> <title>W3.CSS Template</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" … -
Need help addressing cors issue on server
I have a django backend with react frontend. I am trying to deploy my application on cpanel hosting. I have created subdomain for backend (api.example.com/) and main domain (example.com/) is for frontend. PS: mentioned fake URL. Following is what my settings.py looks like, INSTALLED_APPS = [ # Custom Installed "corsheaders", ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... ALLOWED_HOSTS = [ 'www.example.com', 'example.com', 'xxx.yyy.208.227', ] # ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = False # CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'https://www.example.com', 'https://example.com', 'https://xxx.yyy.208.227', ] I am seeing error as mentioned below, Access to XMLHttpRequest at 'https://api.example.com/api/products/' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Am I missing something? -
OSError: [WinError 127] after gdal installation
I have just finished installing gdal 3.6 on Windows, and it looks like my django project is getting the file correctly. But when I run django manage.py check, it gives me the following output: File "C:\users\rodri\dev\mymap\.mymap\Lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 69, in <module> lgdal = CDLL(lib_path) ^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.752.0_x64__qbz5n2kfra8p0\Lib\ctypes\__init__.py", line 379, in __init__ self._handle = _dlopen(self._name, mode) ^^^^^^^^^^^^^^^^^^^^^^^^^ OSError: [WinError 127] Não foi possível encontrar o procedimento especificado Did someone already get through it, or knows how to fix it? -
why am I not able to pass token correctly in my Djano views?
I have below code class ProxyAPI(CreateAPIView): serializer_class = DummySerializer def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.org = None self.ent = None self.linkde = None def post(self, request, *args, **kwargs): org = request.data.get("org") ent = request.data.get("ent") erpid = request.data.get("erpid") self.org = org self.ent = ent self.erpid = erpid combined_response = [] post_api_views = [ abc, xyz ] linkdetl = self.get_queryset() if not linkdetl: return Response("Link token not found.", status=status.HTTP_404_NOT_FOUND) token = linkdetl[0] for index, api_view_class in enumerate(post_api_views, start=1): try: api_instance = api_view_class(token) response = api_instance.post(request) if response.status_code == status.HTTP_200_OK: return Response("success") except Exception as e: error_message = f"Anddd error occurred while calling API {index}: {str(e)}" return Response({'error': error_message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(combined_response, status=status.HTTP_200_OK) class Info(APIView): token = None # def __init__(self): # self.token = token # super().__init__() # @staticmethod def get_info(self): comp_client = create_client(self.token) print(comp_client) try: organization_data = comp_client.accounting.company_info.list(expand=something) return organization_data except Exception as e: api_log( msg=f"Error retrieving organizations details: {str(e)} \ - Status Code: {status.HTTP_500_INTERNAL_SERVER_ERROR}: {traceback.format_exc()}") def get(self, request, *args, **kwargs): organization_data = self.get_info() formatted_data = self.build_response_payload(organization_data) return Response(formatted_data, status=status.HTTP_200_OK) class abc(APIView): token = None # def __init__(self): # self.token = token # super().__init__() @staticmethod def post(request): authorization_header = request.headers.get('Authorization') if authorization_header and authorization_header.startswith('Bearer '): token = authorization_header.split(' ')[1] token = … -
Django CSS not loading even though configuration is set correctly
I linked my static files to base.html in my Django app my index.html is inheriting from my base.html I linked my css file to my base.html so all other html files will inherit from it I have configured all settings but anytime I runserver my css doesn't load, it used to work before then it just suddenly stopped working This is how my html loads Please I need a fix -
Getting total count of the iteration in multiple for loops: django template
I am working on a project using django I have 2 lists classes and students I need to iterate in these and print the s.no , class.name and class.student.name using django template the code snippets looks something like: {% for class in classes %} {% for student in class.students %} <tr> <td>#{{ count }}</td> <td>{{ student.name }}</td> <td>{{ class.name }}</td> </tr> {% endfor %} {% endfor %} I am not able to get the correct count as we have either the parentloop counter of for loop counter but i need the count of total iteration i tried something like {% with count=0 %} {% for class in classes %} {% for student in class.students %} {% with count=count|add:1 %} <tr> <td>#{{ count }}</td> <td>{{ student.name }}</td> <td>{{ class.name }}</td> </tr> {% endwith %} {% endwith %} {% endfor %} {% endfor %} but this always give the count as 1 changing the position of the for loop also did not worked. Do we have a solution to this? Regards -
axios django 403 (forbidden): CSRF Failed: CSRF token missing
I have a Django-React Project. I can't POST or PUT APIs from the front; I get a 403 forbidden error every time I make a request, only works when I request from the back. I keep getting the same 'CSRF Failed: CSRF token missing.' message. It was working before completely until I ran 'npm i' to update dependencies that were missing. After that, everything broke. So I'm pretty certain my code is correct since it was working before, does anyone know if any node dependencies break stuff? There is csrftoken being generated under request headers cookies, not sure what would cause the issue. This is how I am declaring my axios on the front: constructor() { // Necessary Credentials axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.withCredentials = true; // Establish Axios Client this.client = axios.create({ baseURL : "http://127.0.0.1:8000" }); }; This is some of my settings.py that may be helpful: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'API.apps.UserApiConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://127.0.0.1:3000', ] CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:3000'] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), } Tried … -
I have a view issue in django the file is not working properly
File "C:\Users\Zeeshan Alvi ( BUH )\Desktop\Python\Webitewithdjango\ebookbackend\ebookbackend\urls.py", line 26, in path('login/', views.login_view, name='login'), # Corrected URL pattern for login ^^^^^^^^^^^^^^^^ AttributeError: module 'myapp.views' has no attribute 'login_view' I make my website fronted complete using HTML , CSS & Java Script . I also connect my contact page to my database and also get data , but I did a mistake a make a backend using a single file index.html only after I try to connect my login page with my database but it gives some error and that of my backend of contact page is also ruined and right now I try for many hours but cant fix the bug. Is there anyone to help me. I need a person some to have a chat with him/her to discuss it . -
Django ALLOWED_HOSTS not changing
I have a django app hosted on a DO linux droplet running nginx and gunicorn. I am trying to point the domain to the IP. But I get the below error when I try to open the webapp in browser DisallowedHost at / Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS. Request Method: GET Request URL: http://example.com/ Django Version: 4.2.1 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS. But in my settings.py, I already have the domain added as below (x.x.x.x is the IP): ALLOWED_HOSTS = ['x.x.x.x' ,'example.com', 'www.example.com'] In the error message in browser, when I look at local vars allowed_host, I can only see the IP (which was the earlier setting before I added the domain): Variable Value allowed_hosts ['x.x.x.x'] domain 'example.com' host 'example.com' msg ("Invalid HTTP_HOST header: 'example.com'. You may need to add " "'example.com' to ALLOWED_HOSTS.") port '' self <WSGIRequest: GET '/'> I restarted the gunicorn but still nothing changes. sudo systemctl restart gunicorn Why is the change in allowed_hosts not reflecting ? -
How to default the external link tab in RichTextBlock link modal in Wagtail admin?
I'm using Wagtail CMS and noticed that when I try to add a link in a RichTextBlock in the Wagtail admin interface, the link modal defaults to the internal link tab. However, I want it to default to the external link tab instead. I've explored some of the Wagtail source code and found client/src/entrypoints/admin/page-chooser-modal.js, which seems to handle the switching of tabs in the link modal. However, I'm unsure how to modify this to make the external link tab the default. I've also looked at the templates wagtailadmin/chooser/_link_types.html and wagtailadmin/chooser/browse.html. It seems like browse.html renders content for internal links by default. While I could potentially modify this template to render external links, it seems like the data for external links needs to be passed from a view, so simply changing the template might not be sufficient. Am I looking in the right places to achieve this customization? If not, where should I be looking, and how can I default the link modal to the external link tab? -
Used 1 item in Ajax
don't be tired I wrote a program to register the user, for example, the user came and made a mistake in both passwords, show the error using Ajax, of course, it will only happen once, and if the password is wrong again, the error will not show up, which means it will be used only once. Infinite use in Ajax, of course, the page does not load -
Django User View Affects current_user
I have url for viewing all info about specific user: blog/urls.py urlpatterns += path('user/<int:pk>/', UserDetailView.as_view(), name='user-detail'), that uses this UserDetailView View: blog/views.py class UserDetailView(DetailView): model = User template_name = 'blog/user_detail.html' that inherits from DetailView and uses Django's User model. I have navbar in base html file that displays current user nickname with link to their page attached to it: base.html(which all other html files inherit from)``` {% if user.is_authenticated %} New Post {{ user.username }} Logout Now, when I'm logged in and looking any page except `'user/<int:pk>/'`, nickname with link shows as it should, but when I'm looking some specific user's page, {{ user ]} changes from current user to user who's page I'm looking at: [images](https://imgur.com/a/0tWKXQg). ListView with Post model that calls User by its nickname does not affect current user: blog/urls.py urlpatterns += path('user/str:username', UserPostListView.as_view(), name='user-posts') blog/views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # /_.html # blog/post_list.html context_object_name = 'posts' paginate_by = 2 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') ['user/<str:username>'](https://i.stack.imgur.com/6XM4a.png). Is there a way for me to prevent DetailView with User model from changing {{ user }} from current user to one who's page I'm looking at? -
Can't connect to Grafana via running via docker-compose
I recently started to get into docker. I am coding an application using Django 5.0.2 and want to add Dashboard from grafana and prometheus. Prometheus works, but i can't seem to be able to connect to grafana via localhost:3050 (3000 was already taken) here is my docker-compose.yml file: version: '3.8' services: prometheus: image: prom/prometheus:latest ports: - "9090:9090" # This example maps host port 8080 to container port 9090 (Prometheus default) volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro grafana: image: grafana/grafana environment: GF_INSTALL_PLUGINS: "grafana-clock-panel,grafana-simple-json-datasource" restart: 'no' volumes: - grafana_data:/var/lib/grafana ports: - 3050:3050 depends_on: - prometheus network_mode: bridge volumes: prometheus_data: {} grafana_data: {} prometheus.yml: # my global config global: scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute. evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute. # scrape_timeout is set to the global default (10s). # Alertmanager configuration alerting: alertmanagers: - static_configs: - targets: # - alertmanager:9093 # Load rules once and periodically evaluate them according to the global 'evaluation_interval'. rule_files: # - "first_rules.yml" # - "second_rules.yml" # A scrape configuration containing exactly one endpoint to scrape: # Here it's Prometheus itself. scrape_configs: # The job name is added as a label `job=<job_name>` … -
How the Session works in browsers
I have this Django code which get the "msg" from the session and save it to a variable msg then check if the msg is true if true it will delete it from the session but still the msg variable contains the old value. I know i can set the msg to False in the if block but is there another way of doing this def get(self, request): msg = request.session.get("msg", False) if msg: del request.session["msg"] context = {"message": msg} return render(request, "guess_form.html", context) def post(self, request): guess = request.POST.get("guess") msg = checkGuess(guess) request.session["msg"] = msg return redirect(request.path) I Want to make the msg to be empty when the app runs for the first time the msg meaning the variable -
Nested objects in Django REST Framework when a field is required for POST and not for DELETE
I'm using serializers while dealing with nested objects. Similar to the example by Django REST framework I have: class UserSerializer(serializers.Serializer): email = serializers.EmailField(required=True) #Not required for POST (see following) username = serializers.CharField(max_length=100, required=True) #Not required for DELETE (see following) class PostCommentSerializer(serializers.Serializer): user = UserSerializer(required=True) class DeleteCommentSerializer(serializers.Serializer): user = UserSerializer(required=True) I'm in a situation where I want only username to be required (validated) when PostCommentSerializer is used, and only email to be required when DeleteCommentSerializer is used. What options do I have? in my current setting, both email and username are required for both POST and DELETE. -
Rending a separate page dynamically using django and htmx
Am working on a simple task app using Django and HTMX. I want when a user clicks on a button in the navbar to add a task, the add task page should be displayed dynamically without causing a page reload. Yes the task page gets displayed dynamically but when i try to reload my page Some content of the page gets lost. Checkout below the code snippets navbar.html {% load static %} <div class="flex justify-between pt-10 pb-3"> <div class="w-6/12"> <div class="font-bold text-gray-700 text-2xl" style="cursor: pointer;">Task Manager</div> </div> <div class="w-1/12 text-gray-500" style="cursor: pointer;">Home</div> <div class="w-1/12 text-gray-500" style="cursor: pointer;">Pending</div> <div class="w-1/12 text-gray-500" style="cursor: pointer;">Complete</div> <div class="w-1/12 text-gray-500" style="cursor: pointer;">Pricing</div> <div class="w-1/12 text-gray-500"> <div class="flex justify-center items-center"> <a role="button" class="bg-blue-700 rounded text-white font-bold text-sm px-4 py-1" href="{% url "create_todo" %}" hx-get="{% url "create_todo" %}" hx-push-url="true" hx-target="#main">Add Task</a> </div> </div> <div class="w-1/12 text-gray-500"> <div class="flex justify-center items-center"> <img src="{% static 'images/me.jpg' %}" alt="Profile" srcset="" class="rounded-full w-12 h-12"> </div> </div> </div> <hr> home.html {% extends "../base.html" %} {% block title %}Home Board{% endblock title %} {% block content %} {% include "./navbar.html" %} <div class="px-20" id="main"> <div class="flex justify-between"> <h3 class="mt-5 text-center text-xl text-gray-500 font-bold my-8">Today's Tasks</h3> <div class="flex justify-center items-center"> <button class="bg-blue-700 rounded text-white … -
Django 5.1 models with fields using db_default throw on full_clean
Trying to implement Django 5's new db_default attribute for fields Using the following field as an example: editable = models.BooleanField(db_default=True) Would expect that if editable not specified when creating a new instance, that ORM would not throw error but would still save instance, and that the value of editable would be set to True at the database level. So executing the following to create a new object: product_obj = models.Product( id=id, name=name, is_active=is_active, inventory_type=inventory_type, leadtime=leadtime, ) product_obj.full_clean() product_obj.save() would be expected to succeed. Instead full_clean() raises a ValidationError: django.core.exceptions.ValidationError: {'editable': ['“<django.db.models.expressions.DatabaseDefault object at 0x151db1c70>” value must be either True or False.']} and similar behavior occurs throughout my codebase for any field for which db_default is set (CharField with choices, IntegerField, etc) Clearly I'm not understanding how db_default should be used. -
Read JSON Data from an incoming Django Request and Displaying the Data to HTML
I'm a month old of using Django and I want to create a Registration Form where the data will came from a POST Request (from a microreader that will throw a JSON data going to the Django View Endpoint). Once I received the response, I need to get the data_id and the user must input the name and its department, and displaying it as a form in the HTML that will be pushed to my database, once submitted. However, I'm having a hard time crafting this thing in views.py and its template. This is the thrown JSON Response: {"station":"XXXXXXXX","type":"TYPE-XXX","data_id":"9198491920"} This is the views.py @csrf_exempt def registration_form(request): if request.method == "POST": # Process the JSON data json_data = json.loads(request.body) dataid = json_data.get('data_id') # Initialize the form with the received dataid form = RegistrationForm(initial={'data_id': dataid) if form.is_valid(): name = form.cleaned_data['name'] department = form.cleaned_data['department'] return render(request,'registration.html',{'form':form}) else: # If GET request, initialize form form = RegistrationForm() return render(request, 'registration.html', {'form': form}) This is my registration.html. Although, you may not expect some things in my HTML since I'm trying all forms of displaying but there's no success. {% extends 'base.html' %} {% load static %} {% load widget_tweaks %} {% block content %} <form … -
Django i18n get_language_info_list and get_available_languages provide different language code
With {% get_current_language as CURRENT_LANGUAGE %} , {{ CURRENT_LANGUAGE }} shows nl-nl With {% get_available_languages as AVAILABLE_LANGUAGES %} , {{ AVAILABLE_LANGUAGES }} shows [('nl-NL', 'Nederlands'), ('en', 'Engels')] With {% get_language_info_list for AVAILABLE_LANGUAGES as LANGUAGES %} , {{ LANGUAGES }} shows [{'bidi': False, 'code': 'nl', 'name': 'Dutch', 'name_local': 'Nederlands', 'name_translated': 'Nederlands'}, {'bidi': False, 'code': 'en', 'name': 'English', 'name_local': 'English', 'name_translated': 'Engels'}] Settings: # https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = "nl-NL" # https://docs.djangoproject.com/en/dev/ref/settings/#languages LANGUAGES = [ ('nl-NL', _('Dutch')), ('en', _('English')), ] In {{ LANGUAGES }} I expect code to be nl-NL and not nl. Anyone that can explain this discrepancy? Django version: Django==4.2.10 -
Temporal Workflow Issue in python: Response Not Returned, Queueing/Deadlock Occurs, Unable to Trigger New Workflow Unit Until Current One Finishes
I've created a workflow with 4 activity which runs one after another using temporalio, When my one workflow starts it not giving response, it is queued/Deadlock Occurs, Unable to trigger new workflow unit current one finishes. import asyncio import random import concurrent import multiprocessing from datetime import timedelta from temporalio.client import Client from temporalio.worker import Worker from temporalio import activity, workflow from temporalio.worker import SharedStateManager, Worker async def get_client(): client = await Client.connect("localhost:7233") return client @activity.defn async def activity1(params) -> dict: print("Inside activity 1") count = 1 while True: if count == 10000000000: break count = count + 1 return params @activity.defn async def activity2(params) -> dict: print("Inside activity 2") return params @activity.defn async def activity3(params) -> dict: print("Inside activity 3") return params @activity.defn async def activity4(params) -> dict: print("Inside activity 4") return params @workflow.defn class TestTemporalWorkflow: @workflow.run async def run(self, params) -> dict: response_1 = await workflow.start_activity( activity1, params, start_to_close_timeout=timedelta(seconds=100), ) response_2 = await workflow.start_activity( activity2, response_1, start_to_close_timeout=timedelta(seconds=100), ) response_3 = await workflow.start_activity( activity3, response_2, start_to_close_timeout=timedelta(seconds=100), ) response_4 = await workflow.start_activity( activity4, response_3, start_to_close_timeout=timedelta(seconds=100), ) async def main(params): task_queue = "demo-temporal-workflow-queue" workflows = [TestTemporalWorkflow] activities = [activity1, activity2, activity3, activity4] # Start client client = await get_client() async with …