Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to connect oracle db to the django application using wallet.zip file
I'm configuring my Oracle database to the django application using wallet.zip file in the following way. Note: This wallet.zip file contains tnsnames.ora file. In settings.py file: DATABASES = { "oracledb": { "ENGINE": "django.db.backends.oracle", "NAME": "dummyemployee", "USER": "dummyuser123", "PASSWORD": "dummypass123", "OPTIONS": { "wallet_location": "C:\\Users\\Administrator\\Desktop\\Wallet_Location" } } } But when I try to execute the API. It's returning the following error: "wallet_location is an invalid keyword argument for this function" -
Persist list inside a object Django Rest Framework
I'm trying to persiste list of a python object (dico) like this but it's difficult { "leader": { "nameLastname": "AAAAA" }, "employeeRemun": { "grossSalaryBase": 111, "bonuses": 222, "travellingExpenses": 333, "noRemuneration": false }, "abandonmentCurrentAccount": { "abandonDate": "2023-10-20", "partner": "BBB", "amount": 444, "recoveryDate": "2023-10-04", "recoveryAmount": 5555, "abortTime": "-16 jours" }, "commentReviewDuring": { "review": "COMMENT DURING" }, "commentReviewAfter": { "review": "COMMENT AFTER" }, "list_benefits": [ { "natureAvantage": { "actualAmount": 42354, "previousAmount": 53234 }, "leaderAvantage": { "nameLastname": "AAAAA" }, "typeAvantage": { "benefitType": "Private Jet" } }, { "natureAvantage": { "actualAmount": 43532, "previousAmount": 4324 }, "leaderAvantage": { "nameLastname": "AAAAA" }, "typeAvantage": { "benefitType": "Rolls Royce" } } ] } Patch Methode: At beginning i try to do this but i don't find how to access index of list ('HERE') : I try to acces element inside the request with request.data.get(...) but for the natureAvantage it's not a {} but a [] need to be acces by a index for indexLls in llsByIdSerialized.data['naturalBenefits']: benefitTypeById = AvantageNatureDirigeant.objects.get(id=indexLls) benefitRefresh = LeaderBenefeitTypeSerilizer(instance=benefitTypeById, data=request.data.get('remSection', {}).get('list_benefits', {}).get('natureAvantage', {})) if benefitRefresh.is_valid(): benefitRefresh.save() So i try to do this one : Create a seperated object for index, benefit_data in enumerate(request.data.get('remSection', {}).get('list_benefits', [])): actual_amount = benefit_data.get('natureAvantage', {}).get('actualAmount') previous_amount = benefit_data.get('natureAvantage', {}).get('previousAmount') data_to_serialize = { … -
Fetching Data from a .sql file in a Django Project
I have a django project. I have a dump of the data from a Mysql database in a .sql file and want to query some data from this file into my django project and display it. I am fairly new to django. Need some help My settings.py looks like this : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '3306', } } -
DLL load failed while importing _rust: The specified procedure could not be found
I am trying to hit an API that is of POST type, it generates access and refresh tokens which can be used to access other APIs. It takes the username and password in the body, which we generate while creating a superuser (admin) in Django. This is the detailed error I'm encountering while hitting the API in Postman: Internal Server Error: /api/token/ Traceback (most recent call last): File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework_simplejwt\views.py", line 44, in post serializer.is_valid(raise_exception=True) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\serializers.py", line 223, in is_valid self._validated_data = self.run_validation(self.initial_data) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework\serializers.py", line 445, in run_validation value = self.validate(value) File "C:\Users\kalash bhagwat\Desktop\Copods\Cloned Repos\leave-tracking-tool-backend\.venv\lib\site-packages\rest_framework_simplejwt\serializers.py", line 77, in validate data["refresh"] = str(refresh) File … -
How can I fix my blacklist token at Django rest framework simple JWT? Error: Given token not valid for any token type"
Im using rest framework simple_jwt to login, everything works to register, login im having the access and refresh token. When I check on the website of JWT Web tokens, It says that the token has type "refresh", the same that I should pass to the Bearer Authorization on postman. But I'm facing this error if the fresh token after login that im passing: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token has wrong type" } ] } My code: LogoutSerializer: class LogoutUserSerializer(serializers.Serializer): refresh_token = serializers.CharField() default_error_message = {"bad_token": ("Token is invalid or has expired")} def validate(self, attrs): self.token = attrs.get("refresh_token") # Corrected accessing the attribute try: # Ensure the token is not empty if not self.token: raise serializers.ValidationError("Token is required") # Check if the token is valid token = RefreshToken(self.token) # Ensure the token is a refresh token if token.token_type != "refresh": raise serializers.ValidationError( "Given token not valid for refresh token type" ) except TokenError: raise serializers.ValidationError("Token is invalid or has expired") return attrs def save(self, **kwargs): try: token = RefreshToken(self.token) token.blacklist() except TokenError: return self.fail("bad_token") LogoutView: class LogoutUserView(GenericAPIView): serializer_class = LogoutUserSerializer permission_classes = [IsAuthenticated] def post(self, … -
`I am trying to build a registration form in Django, using Django form
i put {{form.username}} {{ form.email }} {{ form.password }} in my html code instead of text boxes and i can't see them, i also made a forms.py file and views.py this is register.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>User Registration</title> <link rel="stylesheet" href="{% static "register.css" %}"> </head> <body> <div class="container"> <h2>User Registration</h2> <form action="" method="post"> {% csrf_token %} <div class="form-group"> <label for="username">Username:</label> {{form.username}} </div> <div class="form-group"> <label for="email">Email:</label> {{ form.email }} </div> <div class="form-group"> <label for="password">Password:</label> {{ form.password }} </div> <div class="form-group"> <button type="submit">Register</button> </div> </form> </div> </body> </html>` this is forms.py `from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CreateUserForm(UserCreationForm): class Meta: model = User fields =[ 'username', 'email', 'password']` this is views.py `def register(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return render(request, 'register.html')` I tried debugging, wathing a tutorial and asking chat gpt and i couldn't fix it -
Django guest user cart functionality? Is it safe?
Creating an e-commerce website project to try and learn Django and more about Javascript, so I have been going over a tutorial for the past week. In the tutorial, there is a guest user cart feature. It works by storing user and product data into the cookies. Though, I am having trouble getting it to add multiple of the same item. If I were to login as a user the website works fine. The remove feature works fine for deleting an item out of the cart as guest. In the JavaScript console, the items in the cart get deleted, but the cookies retain the same information before the website reloads. Don't know the cause for this issue. I would really like this feature to work out. JavaScript Console Log cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function() { //sets variable to add to the dictionary. var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) //checks to see if the user is logged in. console.log('USER:', user) if (user === 'AnonymousUser') { addCookieItem(productId, action) } else { updateUserOrder(productId, action) } }) } function addCookieItem(productId, action) { console.log('Not logged in.') //add quantity … -
TokenObtainPairSerializer override
i'am using django-otp and Django-rest-jwt my goal is I want to check if user has enable 2fa if yes I will give him the refresh and access token i would like to change my top file to not required . class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['otp'] = OtpField() def validate(self, attrs: Dict[str, Any]) -> Dict[str, str]: data = super().validate(attrs) user_logged_in.send(sender=self.user.__class__,request=self.context['request'],user=self.user) if self.user is None: user_login_failed.send(sender=self.user.__class__,request=self.context['request'],user=self.user) return data -
Deployed Django Application on PythonAnywhere: Connection Refused Error When Controlling Raspberry Pi Robot Remotely
I am trying to deploy a Django web application on PythonAnywhere that controls a Raspberry Pi robot remotely. The application worked flawlessly locally using ngrok to establish a connection, but after deploying it to PythonAnywhere, I encountered the following error: 2024-04-17 07:49:53 Connection refused: The server is not accepting connections. I tried: Added localhost to the ALLOWED_HOSTS in Django settings. Tried running the server on a different port. Disabled the firewall on the Raspberry Pi. Added corsheaders to the Django project. -
Foreign Key dropdown in Admin returns __str__, can I change it so some other column? [duplicate]
Here is my setup: # myapp.models class Country(models.Model): alpha2 = models.CharField(primary_key=True, max_length=2), name = models.CharField(max_length=64, def __str__(self): return "%(alpha2)s %(name)s" % {"alpha2": self.alpha2, "name", self.name} class Address(models.Model): id = models.BigAutoField(primary_key=True) province = models.CharField(max_length=64) country = models.ForeignKey(Country, on_delete=models.PROTECT) # myapp.admin from django.contrib import admin from .models import Address, Country admin.site.register(Address) admin.site.register(Country) When I go to http://localhost:8000/admin, and go to add a new Address, the country dropdown shows the output of Country().__str__ (i.e. IN India). I have 2 questions: I believe I would be able to choose what I want to show in the dropdown if I was writing my own form (without changing __str__). Is this correct? Can I change what I want to show in admin panel without changing __str__? -
Django project not fetching static files
I am developing a small app for my course in Django. Now, I am trying to bring my project to a cloud system, in this case using Heroku, however it seems that I have an issue with fetching my static files when running the collectstatic command. I get the following error: Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "/Users/mlopez/journal_project/manage.py", line 22, in <module> main() File "/Users/mlopez/journal_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/management/base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/management/base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() ^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect handler(path, prefixed_path, storage) File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 368, in copy_file if not self.delete_file(path, prefixed_path, source_storage): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 278, in delete_file if self.storage.exists(prefixed_path): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/core/files/storage/filesystem.py", line 165, in exists return os.path.lexists(self.path(name)) ^^^^^^^^^^^^^^^ File "/Users/mlopez/anaconda3/lib/python3.11/site-packages/django/contrib/staticfiles/storage.py", line 39, in path raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. Here are my settings.py: import os from pathlib import Path # Build paths inside the … -
Python Django ASGI - saving image to a model with django-storages to S3 bucket results in memory leak
First of all I've been looking for a solution for a couple of days and tried various code snippets found here. The problem: hosted web app consumes more and more memory everytime image is saved to a Django model ImageField set up with S3 via django-storages. What I tried or observed: no matter which ASGI server I used, result was the same (Daphne, Uvicorn, Hypercorn, Granian). I checked memory allocation line by line in cricital places with tracemalloc and the memory consumption rised specifically after saving images. async def upload_image(content_img, content_thumbnail): lf1 = tempfile.NamedTemporaryFile() for chunk in content_img.chunks(): lf1.write(chunk) lf2 = tempfile.NamedTemporaryFile() for chunk in content_thumbnail.chunks(): lf2.write(chunk) uploaded_image = await UploadedImage.objects.acreate(user=request.user, type=type, app_name=app_name) def upload_image_sync(): uploaded_image.image.save(content_img.name, lf1) uploaded_image.thumbnail.save(content_thumbnail.name, lf2) await sync_to_async(upload_image_sync)() In above code invoking 'uploaded_image.image.save' or 'uploaded_image.thumbnail.save' shows higher memory usage with tracemalloc, pointing 'json/decoder.py' as the file which occupies memory. And here's the interesting part. Saving image to model shows ~10MB more memory used and jumps from ~45MB to ~55MB. If I save lots of images in short period of time, I saw spikes up to ~400MB, but after that the current usage lowered and it looked like memory was released. Not always going back to 45MB but … -
Django admin site not loading in localhost
I am running python manage.py runserver on my django project but my django admin site is not loading locally. All the other urls apart from http://127.0.0.1:8000/ are functional. I am using Django==4.2.11 and Python 3.9 This is my urls.py from django.contrib import admin --- from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(("api.urls", "api"), namespace="v1")), ] and my settings.py ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", "api", "authentication", ] 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", "simple_history.middleware.HistoryRequestMiddleware", ] SITE_ID = 1 I don't know where else to look. -
how to show embeded video on home page from blog page in wagtail?
As shown i can embed the video via URL. but it save videos as url and text as whole body. i an unable to extract videos only and show in home page. https://docs.wagtail.org/en/v4.0.3/editor_manual/new_pages/inserting_videos.html# i tried using from wagtail.core.rich_text import RichText register = template.Library() @register.filter(name='extract_videos') def extract_videos(body): videos = [] # Check if the body content is RichText if isinstance(body, RichText): # Iterate through each block in the RichText for block in body: # Check if the block is of type 'embed' if block.block_type == 'embed': # Append the value (which should be the embedded video URL) to the videos list videos.append(block.value) return videos -
Django filter objects using two fields
I have a Django model looks like this class Product(models.Model): product_type_id = models.IntegerField() product_sub_id = models.IntegerField() ... Where a product can be defined as name product_type_id product_sub_id toy cars 13 8 toy planes 13 11 cheese 2 1 bread 2 4 chocolate cake 2 8 With a list of (product_type_id, product_sub_id), is there an easy way to filter out products rather than pulling all matched objects and compare them with the list afterwards? For example I have [(13, 8), (2, 1)] for retrieving product "toy cars" and "cheese" My current solution is my_list = [(13, 8), (2, 1)] filtered_products = Products.objects.filter( product_type_id__in = [i[0] for i in my_list], product_sub_id__in = [i[1] for i in my_list] ) matching_products = [p for p in filtered_products if (p.product_type_id, product_sub_id) in my_list] -
Why Django Admin static doesn't work in nginx and docker?
The problem is when I make docker-compose up and enter my website at localhost/admin in ngnix I don't see the default django admin styles. nginx.conf location /static/ { autoindex on; alias movies_admin/staticfiles/; } components/static.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = 'movies_admin/staticfiles/' docker-compose.yml version: '3.8' services: django: build: context: . volumes: - "./movies_admin:/movies_admin" - "./movies_admin:/movies_admin/staticfiles/" environment: - DB_HOST=database - DB_NAME=movies_database - DB_USER=app - DB_PASSWORD=123qwe - SECRET_KEY='django-insecure-8h%wg+drqmqjkw$8wm7#)#%*fb3b%(-e!-kbdth^#9u)23u!48' command: sh -c "uwsgi --ini /movies_admin/uwsgi.ini" depends_on: - database database: image: postgres:16 environment: - DB_NAME=movies_database - DB_USER=app - DB_PASSWORD=123qwe volumes: - $HOME/postgresql/data:/var/lib/postgresql/data nginx: image: nginx:latest volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./movies_admin:/movies_admin/staticfiles/ ports: - "80:80" depends_on: - django Dockerfile FROM python:3.10.0-alpine RUN apk add postgresql-client build-base postgresql-dev linux-headers pcre-dev WORKDIR /movies_admin COPY requirements.txt . RUN pip install -r requirements.txt --no-cache-dir EXPOSE 8000 COPY movies_admin . RUN python3 manage.py collectstatic --no-input I read all available tutorials and understand the algorithm: Setup staticfiles in settings.py In Dockerfile collectstatic Mount staticfile path in nginx and django containers volumes Pass the path to the staticfiles in nginx.conf to setup routing if static was requested Despite all this I don't see the styles in django admin. What might … -
Django merge two m2m_change signals
i have a post model which has category m2m field and tag m2m field, on post post_save i want to retrieve the category ids and tag ids from that post model instance, but after some research i found out, m2m fields arnt save at that time and i want to use m2m_changed signal, but since i have two m2m fields, how can i merge two signals or in posts post_save is there a way to wait for the creation of m2m fields, or do i have to create custom signal class Category(models.Model): description = RichTextField(null=True, max_length=10000) name = models.CharField(max_length=300, null=False, blank=False) slug = models.CharField(max_length=400, null=True, blank=True, unique=True) parent = models.ForeignKey("Category", on_delete=models.CASCADE, null=True, blank=True) # readonly fields wp_category_id = models.CharField(max_length=10, null=False, editable=False) total_posts = models.CharField(max_length=10, null=True, editable=False) category_link = models.CharField(max_length=600, null=True, editable=False) def __str__(self) -> str: return f"{self.name}" class Meta: verbose_name_plural = "Categories" class Tags(models.Model): description = RichTextField(null=True, max_length=10000) name = models.CharField(max_length=300, null=False, blank=False) slug = models.CharField(max_length=400, null=True, unique=True, blank=True) # readonly fields wp_tag_id = models.CharField(null=False, editable=False, max_length=10) tag_link = models.CharField(null=True, editable=False, max_length=400) def __str__(self) -> str: return f"{self.name}" class Meta: verbose_name_plural = "Tags" class Posts(models.Model): wp_post_id = models.CharField(max_length=200, null=True, editable=False) slug = models.CharField(max_length=1000, null=True, unique=True, blank=True) status = models.CharField(choices=status_choices, max_length=200) … -
How can celery use Django ORM?
How can celery use Django ORM? Celery and django are diffent processes. But, Celery worker can use Django Application code.(ORM, Model..) I think celery process have django application code. Is it right? What should I do setting when django and celery on another server physically? I was wondering how Celery can use the code in the django. -
How to make href point to a django template and pass context to it?
I have a django template listing mails/messages from a sql database. I am trying to make those messages clickable by using an <a> tag, as to open a page displaying the content of the message. Part of my template listing the messages : <table> <th>ID</th> <th>DATE</th> <th>SUJET</th> <th>SENDER</th> {% for message in messages %} <tr> <td>{{message.id}}</td> <td>{{message.date}}</td> <td><a href="">{{message.subject}}</a></td> <td>{{message.sender.address}}</td> </tr> {% endfor %} </table> Is there a way to fill this href such that it calls a views.py function while passing it the correct message instance ? I tried to write <a href={% url 'show_message' {{message}} %}> Where show_message would be a url name in my app_urls.py, but it doesn't seem to work. The doc seems to point to something similar though. Thank you ! -
drf allauth google signup sign in
Im using django allauth for google signup sign in after successfully sign in, all the functions which need authentication will be performed after user is authenticated but i dont know how to authenticate the user in backend after sign in sign up using customuser inheriting abstractbaseuser and a user with additional required field tried google sign in but want to authenticate the user -
Problem with Django template inheritance, i had tried referring Django docs and everything with the code is correct but the expected out is wrong
trying to extend base.html so that my home.html will be visible in base.html body I think i have missed something, can anyone take a look and suggest me. once check this code https://github.com/Pav125/portfolio/tree/main/portfo/skills/templates/skills or see parts of the code base.html <div> {% block template %}{% endblock template %} </div> home.html: {% extends "skills/base.html" %} {% block template %} Code here {% endblock template %} views.py from django.shortcuts import render def home(request): return render(request, 'skills/base.html') the content of the home.html file was not visible on web when i run the server -
How do I start a django project with uvicorn in pycharm and debug
I want to debug a django project using pycharm, but this django project uses uvicorn blogs.asgi: application --host 0.0.0.0 --port 8000 starts. How do I configure pycharm so that it starts a normal django project by clicking the Debug button in the upper right corner of pycharm The following is the normal django project startup configuration: enter image description here I tried to search various documents for configuration, but was unsuccessful。 I want to know how to set it up, can you give me some Pointers? Thank you My English is not good, if the description is inappropriate, please forgive me -
Error when using cms.api.create_page "UserWarning: No user has been supplied when creating a new PageContent object."
When I use the Django CMS API "create_page" function I get the following error: UserWarning: No user has been supplied when creating a new PageContent object. No version could be created. Make sure that the creating code also creates a Version objects or use PageContent.objects.with_user(user).create(...) page_content = PageContent.objects.with_user(user).create( When the "create_page" function is run it creates a page and then runs the "create_page_content" function which throws an error at the following line of code: user = getattr(_thread_locals, "user", "unknown user") page_content = PageContent.objects.with_user(user).create( language=language, title=title, menu_title=menu_title, page_title=page_title, redirect=redirect, meta_description=meta_description, page=page, created_by=created_by, changed_by=created_by, soft_root=soft_root, in_navigation=in_navigation, template=template, limit_visibility_in_menu=limit_visibility_in_menu, xframe_options=xframe_options, ) This is part of Django CMS' inbuilt API so I can't really change it. I could copy the "create_page" and "create_page_content" functions and use the edited copies but that seems like a fairly brute force solution and I'm probably just missing something. My relevant code: from cms.api import create_page from cms.constants import TEMPLATE_INHERITANCE_MAGIC new_page = create_page(title='Example', template=TEMPLATE_INHERITANCE_MAGIC, language='en') -
Django puts AND clause to lookup "in"
Django 4.2 together with graphene-django filters is making my query use AND operation class ExampleFilterSet(FilterSet): tags__name__in = StringInFilter(method="filter_tags_and_categories") class Meta: model = Example fields = {"users__email": ["in"]} Ideally, here it should have been OR query - where users__email in ['abc@gmail.com' , 'xyz@gmail.com'] but on debugging its doing an AND operation It was working well with django3.1 and graphene-django 2.9.9 -
Nginx[emerg] "map" directive is not allowed here in /etc/nginx/sites-enabled/default:1
This is my /etc/nginx/sites-enabled/default file map $sent_http_content_type $expires { default off; text/html epoch; text/css 30d; application/javascript 30d; ~image/ max; } server { listen 80 default_server; listen [::]:80 default_server; expires $expires; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /home/ubuntu/ask-local-django; # Add index.php to the list if you are using PHP #index index.html index.htm index.nginx-debian.html; server_name api.example.in admin.example.in; #location /favicon.ico { access_log off; log_not_found off; } location /media { autoindex on; alias /home/ubuntu/ask-local-django/media/; } location /static { access_log off; log_not_found off; alias /home/ubuntu/ask-local-django/staticfiles; } # location /.well-known { # alias /home/ubuntu/ask-local-django/well-known; # } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } #location /.wellness/assetlink.json { # root /home/ubuntu/ask-local-django/static/; # } access_log /home/ubuntu/logs/ask_local_access.log; error_log /home/ubuntu/logs/ask_local_error.log; # pass PHP scripts to FastCGI server # #location ~ \.php$ { # include snippets/fastcgi-php.conf; # # # With php-fpm (or other unix sockets): # fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; # # With php-cgi (or …