Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ajax to trigger a view not working
I'm trying to trigger a view by clicking a html button in a template. template (test.html) <div id="test_count"></div> <input type="button" value="Get number of records in DB" onclick="numberec()" /> <script> function numberec() { $.ajaxSetup( {data: {csrfmiddlewaretoken: '{{ csrf_token }}'}, }); $.ajax({ type: "POST", url: "../number_of_rec/", success: function (data) { $("#test_count").html({{number_of_rec}}); } }) } </script> View.py def number_of_rec(request): number_of_rec = Record.objects.count() data2 = render(request, 'test.html', {'number_of_rec': number_of_rec}) return (data2) def test(request): return render(request, 'test.html') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('number_of_rec/', views.number_of_rec, name='number_of_rec'), path('test/', views.test,name='test'), ] When I go to https://my_web_app.com/test in the web browser, the button doesn't trigger the number_of_rec view and the div is not filled with the result. BUT if I trigger the view by going to https://my_web_app.com/number_of_rec in web browser, the button is working and fill the div with the expected result. What should I do for my Ajax to trigger the number_of_rec view from the test.html page or any other page ? I'm a bit lost ... Thanks -
Rotation of the sphere in the photo with CSS
I want this hemisphere in the photo related to Wikipedia to rotate inward with only HTML and CSS codes (like the movement of the earth). The code that I sent below rotates the entire image, and it is also a 360-degree rotation, not an inward rotation. <img src="{% static "wiki.jpg"%}" alt="wiki.jpg"> img{ border-radius: 100px; margin-top: 400px; } @keyframes img { 0%{ transform: rotate(0deg); } 100%{ transform: rotate(360deg); } } img{ animation: img 20s ease-in-out infinite; } IMAGE If it is not possible to do this with this image, how can I design a similar image? -
PermissionError: [Errno 13] Permission denied: '/app/core/migrations/0005_recipe_image.py'
when i am trying makemigrations on dockerised django application, got this permissionError Here is Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt requirements.txt RUN pip install --upgrade pip && \ apk add --update --no-cache jpeg-dev && \ apk add --update --no-cache --virtual musl-dev zlib zlib-dev && \ pip install -r requirements.txt &&\ adduser \ --disabled-password \ --no-create-home \ django-user && \ mkdir -p /vol/web/media && \ mkdir -p /vol/web/static && \ chown -R django-user:django-user /vol && \ chmod -R 755 /vol USER django-user COPY . . Here is docker-compose.yml: version: "3.9" services: app: build: . volumes: - ./app:/app - dev_static_data:/vol/web ports: - 8000:8000 image: app:django container_name: django_container command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db environment: - DB_HOST=db - DB_NAME=postgres - DB_USER=postgres - DB_PASS=postgres db: image: postgres volumes: - postgres_db:/var/lib/postgresql/data/ environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db volumes: postgres_db: dev_static_data: When i run: docker-compose run --rm app sh -c "python manage.py makemigrations", the error message is: [+] Creating 1/0 ✔ Container postgres_db Running 0.0s Migrations for 'core': core/migrations/0005_recipe_image.py - Add field image to recipe Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() … -
How to add inline form to Inline form in django admin?
how do i make 2 nesting levels with default django admin methods (i want include C fields to form) models.py example Example: class A(models.Model): title=models.CharField(max_length=100) class B(models.Model): title=models.CharField(max_length=100) block_a=models.OneToOneField(A,on_delete=models.CASCADE,related_name="block_b") class C(models.Model): title=models.CharField(max_length=100) block_b=models.ForeignKey(B,on_delete=models.CASCADE,related_name="block_c") page example how i can create django admin model with inline form in inline form form example: title(class A) other_fields B: title(class B) other_fields C: title(class C) other_fields C: title(class C) other_fields C: title(class C) other_fields admin.py #its work class AInline(admin.StackedInline): model = A form = AForm class B(admin.ModelAdmin): model = B form = BForm but how do i make 2 nesting levels with default django admin methods (i want include C fields to form) -
I was trying to implement SOLID Principles. this time Dependency inversion in Python - Django
TypeError: SignInView.init() missing 1 required positional argument: 'api_response_factory' I try to use abstract methods but it failed. I'm new about SOLID implementation and new in python too, can someone give me an advice or idea about how to deal with this kind of erros? I have to add that this is my first time asking in stackoverflow from abc import ABC, abstractmethod from rest_framework.views import APIView from django.http import JsonResponse from rest_framework import status class ApiResponseFactoryAbstract(ABC): @abstractmethod def success(self) -> str: pass class ApiResponseFactory(ApiResponseFactoryAbstract): def success(self) -> str: print("Testing") return "Testing" class SignInView(APIView): def __init__(self, api_response_factory: ApiResponseFactoryAbstract): self.api_response_factory = api_response_factory def post(self, request): data = self.api_response_factory.success() return JsonResponse(data=data, status=status.HTTP_200_OK) This is app/urls.py: from django.urls import path from . import views router_auth = [ path("sign-in/", views.SignInView.as_view(), name="sign-in"), ] -
Saving a image with blob type on mysql using django and ReactJS
I would like to save a blob in mysql using django , but I have the following problem sometimes the image is saved as none and sometimes it gives a bad request problem, how can I solve this? Here my view.py: class RegiaoAPIView(APIView): serializer_class = RegiaoSerializer def get(self, request, pk=None, format=None): try: if pk is None: regioes = Regiao.objects.all() serializer = self.serializer_class(regioes, many=True) return Response(serializer.data) else: regiao = Regiao.objects.get(pk=pk) childs = Regiao.objects.filter(id_regiao_superior=regiao) serializer = self.serializer_class(regiao) serializer_apontando = self.serializer_class(childs, many=True) response_data = { "regiao": serializer.data, "childs": serializer_apontando.data if pk else None } return Response(response_data) except Regiao.DoesNotExist: return Response({"detail": "No Regioes found"}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"detail": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def post(self, request): try: # print("Dados binários da imagem:", request.data.get('imagem')) print("Entrou na view de criação") imagem_base64 = request.data.get('imagem', None) new_data = request.data.copy() if imagem_base64: print("Entrou no tratamento de imagem") imagem_bytes = base64.b64decode(imagem_base64) new_data['imagem'] = imagem_bytes poligono_valor = request.data.get('poligono', None) extend_valor = request.data.get('extend', None) poligono_resultante = createPolygon(poligono_valor) if extend_valor is not None: new_data['extend'] = json.dumps(extend_valor) new_data['poligono'] = poligono_resultante print("Dados antes da serialização:", new_data) serializer = self.serializer_class(data=new_data) if serializer.is_valid(): print("Dados válidos, criando objeto...") serializer.save() print("Objeto criado com sucesso") return Response(serializer.data, status=status.HTTP_201_CREATED) else: print("Erros de validação:", serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as e: … -
Django/CSS static files not loading
I am using a template to make a customized website. However some static files are loading and some are not. I get a red underline in my text editor in these locations: <section class="dento-service-area section-padding-100-0 bg-img bg-gradient-overlay jarallax clearfix" style="background-image: url({% static 'website/img/bg-img/13.jpg' %});"> <div class="container"> Any help in CSS formatting is appreciated. -
How to do mobile notifications with Django backend and flutter frontend? [closed]
I have a Flutter front-end mobile (iOS) app with a Django backend. I have a feature where I create posts and tag people. So when a creator publishes the post, the data is stored in the backend, Django. And also reflects on the tagged people's homepages when they reopen or refresh their app. Now I am planning to add a notification system in the app, where the post publishing should also alert the tagged people with a notification that they have been tagged. With a quick google seems like there are 2 ways to do it and I am confused about which one is feasible: Approach 1: When the creator publishes the post, have a concurrent command to send FCM notifications to the invited mobiles. Here, I won't be dealing with the backend at all. This ‘frontend-originating’ notifications seem easy as I don't have to deal with backend Django at all. Approach 2: Once the data is stored in the backend, send a django-fcm notification to alert the devices. This seems like a robust solution, as I think, in the future, IF I add backend computations and want to alert the user, I will have a ‘backend-originating’ notification already set … -
Django ManyToMany get error 'Object of type QuerySet is not JSON serializable'
i have this issue on my application. Object of type QuerySet is not JSON serializable In fact, i creating an application in which we have a relationship of the type several Products inone or more Orders. Here is my code : models.py # model Product class Products(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=500) class Meta: db_table ="products" # model Order class Orders(models.Model): order_id = models.AutoField(primary_key=True) order_number = models.CharField(max_length=500) supply = models.ForeignKey(Supplies, on_delete = models.CASCADE) statut = models.CharField(max_length=500, default="validé") date_of_order = models.DateField() products = models.ManyToManyField(Products, through='OrderProduct') class Meta: db_table ="orders" # model OrderProduct class OrderProduct(models.Model): Order = models.ForeignKey(Orders, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) product_quantity = models.PositiveIntegerField(default=1) class Meta: db_table ="ordersproducts" views.py # OrderGetAllApi @csrf_exempt def order_list(request): orders = Orders.objects.select_related('supply').all # orders = Orders.objects.select_related('products').all() order_list = [] for order in orders: order_list.append({ 'order_id': order.order_id, 'order_number': order.order_number, 'date_of_order': order.date_of_order, 'supply_id': order.supply.supply_id, 'supply_name': order.supply.supply_name, 'supply_address': order.supply.supply_address, 'products': order.products.all() }) return JsonResponse(order_list, safe=False) serializers.py class OrderProductSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = OrderProduct fields = ['product_id', 'product_name', 'product_quantity'] # fields = '_all_' class OrderSerializer(serializers.ModelSerializer): supply = SupplySerializer() products = OrderProductSerializer(many=True) class Meta: model=Orders fields=('order_id', 'order_number', 'date_of_order', 'statut', 'supply', 'products') I want to get the list of order with their respective products. when i enter … -
I got this error while making migration . module got error and for frozen importlib
I like to get file in postgreSQL . so i want to do migration so i got these error. there is more than model error like frozen importlib like error so help me to clear the error. I Expect the code and migrate successfully. File "J:\good\mainone\manage.py", line 22, in <module> main() File "J:\good\mainone\manage.py", line 18, in main execute_from_command_line(sys.argv) File "J:\good\test\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "J:\good\test\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "J:\good\test\Lib\site-packages\django\core\management\base.py", line 425, in run_from_argv connections.close_all() File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 84, in close_all for conn in self.all(initialized_only=True): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 76, in all return [ ^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 73, in __iter__ return iter(self.settings) ^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 45, in settings self._settings = self.configure_settings(self._settings) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\db\utils.py", line 148, in configure_settings databases = super().configure_settings(databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 50, in configure_settings settings = getattr(django_settings, self.settings_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 128, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", … -
Django Heroku /GET Favicon.Ico when running heroku logs --tail
My Heroku build is complete, but the application is not booting for some reason. When I run heroku logs --tail, 2023-09-04T13:32:07.484629+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=3515dc4d-fb0c-4ccb-bbdc-cb81a1ae5a31 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:07.768182+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=8c703a21-5109-4f0a-af7a-22c0e2687c8a fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:14.000000+00:00 app[api]: Build succeeded 2023-09-04T13:32:35.613845+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=6c9caf84-4fb9-4a08-96ea-ee41bae09184 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:35.808771+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=cd6e61e2-ee17-4f5e-abb4-c2ca33636d17 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:45.705631+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=5d813e56-e116-4432-86f5-1ba43ba9227b fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:45.899516+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=14f662de-7547-40d0-bee9-522e847922c4 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https`` these are the issues that pop up. This is my Procfile and req.txt. web gunicorn journallove.wsgi:application --log-file - ` asgiref==3.6.0 blind==0.0.1 blinker==1.6.2 certifi==2023.5.7 charset-normalizer==3.1.0 click==8.1.3 cloudpickle==2.2.1 Cython==0.29.35 distlib==0.3.6 dj-database-url==2.1.0 Django==4.2.1 entrypoints==0.4 filelock==3.12.2 Flask==2.3.2 gitdb==4.0.10 GitPython==3.1.31 greenlet==2.0.2 gunicorn==20.1.0 django-heroku==0.3.1 idna==3.4 itsdangerous==2.1.2 Jinja2==3.1.2 joblib==1.3.1 MarkupSafe==2.1.2 mysql-connector-python==8.0.33 mysqlclient==2.1.1 nltk==3.8.1 numpy==1.24.3 package-json==0.0.0 pandas==2.0.1 platformdirs==3.8.1 protobuf==3.20.3 psycopg2-binary==2.9.7 PyMySQL==1.0.3 pytz==2023.3 PyYAML==6.0 querystring-parser==1.2.4 regex==2023.6.3 requests==2.31.0 six==1.16.0 smmap==5.0.0 SQLAlchemy==2.0.15 sqlparse==0.4.4 templates==0.0.5 tqdm==4.65.0 typing_extensions==4.6.2 tzdata==2023.3 urllib3==2.0.2 views-py==2.0.0 virtualenv==20.23.1 Werkzeug==2.3.4` I tried to move … -
Connecting Django Application in One Docker Container to MySQL in Another Container
Title: "Connecting Django Application in One Docker Container to MySQL in Another Container" I have a setup with two Docker containers: mysql-container: This container runs a MySQL image. my-django-container: It hosts a functional Django application. My objective is to establish a connection between the Django application running in my-django-container and the MySQL server in mysql-container. However, I'm encountering a database connection error: django.db.utils.OperationalError: (2002, "Can't connect to server on '36.253.8.13' (115)") Here are my Django settings for the database: "default": { "ENGINE": "django.db.backends.mysql", "NAME": "name", "USER": "username", "PASSWORD": "password", "HOST": "172.18.0.2", # What should I put here? The actual IP of the server `36.253.8.13` or the IP of the SQL container `172.18.0.2`? "PORT": "3306", # Is this the default port for SQL? } I've also placed both containers in the same Docker network, and I can confirm that both containers are visible when I inspect the network using the docker network inspect command. As a Docker novice, I would greatly appreciate any assistance in resolving this issue. -
How to use or work with fileshare.aio library?
I have been trying to implement the azure.storage.fileshare.aio Python SDK to upload files to my Azure File Share. I tried using the asyncio class and its functions to implement the directory_client.upload_file() function, that seems to be not working as expected and the control directly jumps to the return statement. I have provided the code snippet below. Please excuse any of the knowledge gap regarding async implementation, I have just started off with it. def some_other_func(): ..... directory_client = get_directory_client_aio(base_url=file_dir_url) response = asyncio.run(save(directory_client, new_file_with_changes, tasks=tasks)) ..... return response async def save(directory_client, new_file_with_changes, tasks : list): async with directory_client: tasks.append(asyncio.create_task(directory_client.upload_file(file_nam=new_file_with_changes.name, data=new_file_with_changes, length=new_file_with_changes.size))) asyncio.gather(*tasks) return Response.send_response(code=55) It will be appreciated if I get some assistance, Do's and Don'ts on the same. Thank you. -
Django and React authentication with Axios failing
I am building a web app with React and Django (frontend and backend resp.) and I am struggling to do user authentication. The urls in Django in my setup are basic, I will commit them for now. The views should be straightforward (feel free to suggest a more idiomatic approach as I am struggling with getting the right request response flow) basically, you can get a user with /users/int:id/ which returns either a private or public user object depending on whether the id is also the id of the authenticated user, login sends the id of the current user when successful. The issue I have is that login on it's own works just fine, though, when I refresh the page, react seems to have forgotten that the user was logged, it would be really annoying to ask the user to log in every time the page reloads. Therefor I made the authenticate view (and url users/authenticate/) which is supposed to return the private user object based on the session id. It is at this stage that things go wrong, the view does not recognise the user as authenticated (i.e., is_authenticated would fail). Some of the react: Home.js export const Home … -
malfuncting of python 3.11.5
while working on Django and I got to the point of installing Django with pipenv it refused to install Django saying it is neither an internal file nor external file. I tried deleting python and installing it i was expecting it to create a virtual environment. -
Django app stopped working after installing django-graphql-auth
I was working on a Django application with GraphQL. I installed few required libraries. Everything seems to be working fine until I installed django-graphql-auth. Immediately after installing that, I'm getting below error. /Users/sukumar/IntellijProjects/venvs/plotcare_be/bin/python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/core/management/init.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) File "/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", … -
How to pass arguments to get_success_url
views.py: class CommentDeleteView(DeleteView): model = Comments context_object_name = 'delete_comment' template_name = 'blog/comment_delete.html' def test_func(self): comment = self.get_object() if self.request.user == comment.author: return True else: return False def form_valid(self, comment): messages.success(self.request, 'You have deleted the comment') return super().form_valid(comment) def get_success_url(self): post_pk = self.get_object().post.pk return reverse('post_detail', args=(self.kwargs['pk': post_pk])) models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(to=User, on_delete=models.CASCADE) def __str__(self): return f'{self.title} by {self.author}' def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) class Comments(models.Model): content = models.CharField(max_length=100) date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(to=User, on_delete=models.CASCADE) post = models.ForeignKey(to=Post, related_name='comments',on_delete=models.CASCADE) def __str__(self): return f'Comment by {self.author} for {self.post.title}' def get_absolute_url(self): return reverse('comment_detail', kwargs={'pk': self.pk}) urls.py: urlpatterns = [ # path('', home, name='blog_home'), path('', PostListView.as_view(), name='blog_home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post_detail'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post_update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post_delete'), path('post/create/', PostCreateView.as_view(), name='post_create'), path('post/<int:pk>/comments/create/', CommentCreateView.as_view(), name='comment_create'), path('comments/<pk>/', CommentDetailView.as_view(), name='comment_detail'), path('comments/<pk>/update/', CommentUpdateView.as_view(), name='comment_update'), path('comments/<pk>/delete/', CommentDeleteView.as_view(), name='comment_delete'), path('about/', about, name='blog_about'), ] I cant understand how to pass Post primary key to get-successurl function. Comment model is a foreignkey to Post model. enter image description here *I have tried to get post pk with get_*object function but it doesnt seem to work. I cant really uderstand how it works and if you can give me some resources where to … -
How to host a Flask Application on KingHost?
KingHost has a tutorial page for hosting this type of application, but it is not in the same scenario as mine, in which it has more files and folders like "static", in addition to not being clear and explanatory. I would very much like some help. I already spoke with their support, but they say they don't have programming support and don't even know the solution to my problem. I need to know the correct directory, where I should put the .wsgi, virtualenv, app.py, static and templates. Can anyone help me, please? Follow my .wsgi: # vim: syntax=python import sys activate_this = '/home/tvconstruai/apps_wsgi/source/venv/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) sys.path.append('/home/tvconstruai/apps_wsgi/') from source.app import app as application KingHost has a tutorial page for hosting this type of application, but it is not in the same scenario as mine, in which it has more files and folders like "static", in addition to not being clear and explanatory. I followed their tutorial, and on my page web says they can't find the files since I put them where they asked. -
how webpack config file handle logo path when bundling frontend
I have a django project already build and running and i need to change its logo. I have updated the logo path in /static/js/header.jsx but change is not showing up in browser. I have cleared the browser cache. I am new to django and I am wondering if it has anything to do with webpack config file or something like that. Any one with any idea would help alot. Thanks Below is just code from /node/webpack.config.js not necessary related to my problem: var path = require('path'); var nodeExternals = require('webpack-node-externals'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var DeepMerge = require('deep-merge'); var nodemon = require('nodemon'); var fs = require('fs'); var deepmerge = DeepMerge(function (target, source, key) { if (target instanceof Array) { return [].concat(target, source); } return source; }); class WatchRunPlugin { apply(compiler) { compiler.hooks.watchRun.tap('WatchRun', (compilation) => { console.log('Begin compile at ' + new Date()); }); } } class CleanOldAssetsOnBuildPlugin { apply(compiler) { compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => { const newlyCreatedAssets = compilation.assets; const unlinked = []; console.log(path.resolve(buildDir + 'client')); fs.readdir(path.resolve(buildDir + 'client'), function (err, files) { if (typeof files === 'undefined') { return; } // we've started to see cases where files is undefined on cloudbuilds. adding this here as … -
Django async with AppConfig.ready sync/async
I am running Django version 4.2.4 in async mode. For one of my apps I have some code to run on ready like this: class CoreConfig(AppConfig): name = 'demo.core' def ready(self): from .utils import my_sync_func my_sync_func() When I run this code, I get the warning "RuntimeWarning: coroutine 'CoreConfig.ready' was never awaited" When I use sync_to_async like this: class CoreConfig(AppConfig): name = 'demo.core' async def ready(self): from .utils import my_sync_func await sync_to_async(my_sync_func)() I get the warning "RuntimeWarning: coroutine 'CoreConfig.ready' was never awaited" What is the correct way of doing this? Thanks a lot -
Filter using model field and reverse look up
I have two models Business: credit_officer Loan: Business disbursed() active() I want to get business who belong to a given credit_officer and have business.loan_set.active().count() == 1 This is how I was getting business for the given credit_officer but I don't know how to add the other condition business.loan_set.active().count() == 1 cro_businesses = ( Business.objects.filter(credit_officer=credit_officer_id) .values("id", "name", "credit_officer__id") .order_by("_created_at") ) -
Change the sort order with the dash being at the end of the query param
Instead of sorting like this /product/list/?sort=-price, I wish to sort like this /product/list/?sort=price-, where the dash character is placed at the end of the field name in the query param. In my views.py: from rest_framework.filters import OrderingFilter from rest_framework.generics import ListAPIView from rest_framework.response import Response from django.db.models import F from django_filters import rest_framework as filters from app.filters import ProductFilterSet from app.models import Product from app.serializers import ProductSerializer class ProductViewSet(ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter,) filterset_class = ProductFilterSet ordering_fields = ("date_updated", "price") def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def get_queryset(self): return super().get_queryset().annotate(date_updated=F("updated")) And in filters.py: from django_filters import rest_framework as filters from app.models import Product class ProductFilterSet(filters.FilterSet): class Meta: model = Product fields = { "category_id": ["exact"], "price": ["lt", "gt"], "is_available": ["exact"], } I tried adding a custom ordering filter, like this: class CustomOrderingFilter(OrderingFilter): def remove_invalid_fields(self, queryset, fields, view, request): # Remove the dash character from the end of the field name fields = [field.rstrip('-') for field in fields] return super().remove_invalid_fields(queryset, fields, view, request) class ProductViewSet(ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer pagination_class = … -
Send email using Django and Gmail backend
I'm struggling sending emails with a custom domain using Gmail backend. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"] EMAIL_HOST_PASSWORD = os.environ["EMAIL_HOST_PASSWORD"] EMAIL_PORT = 587 EMAIL_USE_TLS = True email = EmailMessage( subject, content, "myaccount@mydomain.com", [customer.email] ) email.send() I've created a Google account with the custom domain and generated an app password, but when using custom domain for EMAIL_HOST_USER, I get (535, b'5.7.8 Username and Password not accepted. Learn more at https://support.google.com/mail/?p=BadCredentials'): EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"] # myaccount@mydomain.com Then I tried with a Google account using a gmail.com domain, and this time it works: EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"] # myaccount@gmail.com So I need the sender's mail to be different than myaccount@gmail.com. I've tried to add a secondary mail address in Google, and used DEFAULT_FROM_EMAIL = "myaccount@mydomain.com" but it doesn't seem to change anything. I've also tried the solution from this post, same issue. -
Content Security Policy is set, but not detected
I have django-csp version 3.7 (https://pypi.org/project/django-csp/). It is added to the middleware section: MIDDLEWARE = [ 'csp.middleware.CSPMiddleware', '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', ] And here's my settings: CSP_DEFAULT_SRC = ["'none'"] CSP_IMG_SRC = ["'self'"] CSP_STYLE_SRC = ["'self'", "'unsafe-inline'"] CSP_STYLE_SRC_ELEM = ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"] CSP_SCRIPT_SRC_ELEM = ["'self'", "'unsafe-inline'"] CSP_FONT_SRC = ["'self'", "data:", "https://fonts.googleapis.com", "https://fonts.gstatic.com"] I know that the above settings work because first I had lots of errors in the browser console and then all gone and the site works correctly. However, two sites checking the host headers (this one and this one) both report that my site is missing Content Security Policy. What I'm missing here? -
Django- filtering on ManyToMany field with exact matches
I have the following models: class Hashtag(models.Model): title = models.CharField(...) class Annotation(models.Model): ... hashtags = models.ManyToManyField(Hashtag) I want to get the Anntoations that have all [hashtag_1, hashtag_2, hashtag_3] as their hashtag. Following is my query: annotations = Annotation.objects.filter( hashtags__title__in=["hashtag_1", "hashtag_2", "hashtag_3"] ) This queryset, returns all annotation that have at least one of ["hashtag_1", "hashtag_2", "hashtag_3"] but I want to receive the annotations that have only these 3 hashtags (not more than and not less than these hashtags). How can I do that? I also tried the following query: annotations = Annotation.objects.annotate( hashtag_count=Count("hashtags") ).filter( hashtags__title__in=["hashtag_1", "hashtag_2", "hashtag_3"], hashtag_count=3 ) if an annotation has [hashtag_1, hashtag_2, hashtag_n], this query will return it (that is not what I want)