Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
converting a string to list of lists in java script
i have a list that i made using django and i passed it to index.html the problem is that i need to use it in the java script content but it is passed as a string to it and i tried JSON.parse but i got error message(Uncaught SyntaxError: Unexpected token 'F', "[[0, False], [0"... is not valid JSON) and here is the list:[[0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [2, True], [2, True]] here is the html line: <div class="like-component" data-post-id="{{post.id}}" data-likes="{{likes}}"></div> and here is the java script part: function renderlikeposts(){ const likeComponents = document.querySelectorAll('.like-component'); likeComponents.forEach(component => { const postId = component.dataset.postId; const list = JSON.parse(component.dataset.likes); const likes = component.dataset.likes[postId-1][0]; const liked = Boolean(component.dataset.likes[postId-1][1]); ReactDOM.render(<Like postId={postId} likes={likes} liked={liked} list={list} />, component); }); } -
function on django object - server side
I have a django application and a corresponding API. Within the code for the application I have some functions and some computed fields that I am not exposing in the json returned through the API. If I am working locally, in the same location as the code, I can do something like this: from pythonfile.models import ModelClass pk = 'model-class-uuid' mc = ModelClass.objects.get(pk=pk) mc.the_function() My question is, can I do this on the server side? -
Django Celery Beat Periodic Tasks Running Twice
I trying to send scheduled emails to users but my Django celery periodic tasks running 2 times within a half-hour span. Every day I scheduled my email task at 7.00 AM but it is running 1st task at 7.00 AM and the same task is running at 7.30 AM also. Here is my celery app # coding=utf-8 from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings") app = Celery("app_name") app.config_from_object("app_name.celeryconfig") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print ("Request: {0!r}".format(self.request)) Celery app config # coding=utf-8 import os PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__)) # Celery Config BROKER_URL = 'redis://redis_server:6379' CELERY_RESULT_BACKEND = 'redis://redis_server:6379' CELERY_TASK_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['application/json'] # Ignore other content CELERY_RESULT_SERIALIZER = 'json' CELERY_ENABLE_UTC = True CELERY_TASK_RESULT_EXPIRES = 0 # Never expire task results CELERY_IGNORE_RESULT = True CELERY_TRACK_STARTED = True CELERY_IMPORTS = ( "module.tasks" ) Periodic Tasks scheduled in Django admin panel Functionality working fine but these tasks are running twice daily for 2 to 3 days and after that, it will run once but if I restart celery then It will start running tasks again twice for some days. Please let me know If I'm missing in celery configuration. -
How can I connect the mayanedms api to my django project?
I would like to connect MayanEdms api to my Django project. Note that mayan is running on different port from my Django container (both are running Docker). The problem I'm having is because, if I navigate to the api link, it works for me, but if I do it through code it doesn't. I don't know why that is? I attach below the error that I get both in the browser and in the command console. I also attach the function that should connect to the API. What I want this function to do is to list all the documents that arrive to my email (it is read with MayanEdms). Once the documents are saved in Mayan, I want to show the information of the emails, including the attached files, in the independent interface that I have made with django. views.py: @login_required def f_facturaspendientes(request): # URL de tu API externa que proporciona las facturas pendientes api_url = 'http://127.0.0.1/api/v4/documents/' # Datos de autenticación auth = ('admin', 'jehK4XvBGp') # Realiza una solicitud GET a la API con autenticación response = requests.get(api_url, auth=auth) # Verifica si la solicitud fue exitosa if response.status_code == 200: data = response.json() # Convierte la respuesta JSON en … -
How to write unit tests with django-tenants and django-graphene to test graphql APIs?
i have written below code following the django-tenants documentation but it is not working and i am getting the error. I know i am not the first one doing this will appreciate any kind of lead..Thanks! I have added the following code which is very simple in use case in which we create organization and that's it import string, random from django_tenants.test.cases import TenantTestCase from django_tenants.test.client import TenantClient from app.tenant.models import Organization, Domain from ..utility import utils, constants def generate_token(user): # sourcery skip: inline-immediately-returned-variable """ this function generates a token for the user :param user: :return: token generated """ from strobes.app.serializers import TwoFactorAuthenticationSerializer t = TwoFactorAuthenticationSerializer() return t.get_token(user).access_token class TenantGraphQLTestCase(TenantTestCase): def setUp(self): alphabet = string.ascii_lowercase random_name = ''.join(random.choice(alphabet) for _ in range(10)) self.user = utils.generate_fake_superuser() self.tenant = Organization.objects.create(name="Clear Org",industry="Dummy",referer="Direct",employee_size=100,strobes_customer=True) domain = Domain() domain.tenant = self.tenant domain.domain = "client.co" domain.save() self.authentication_headers = { "HTTP_AUTHORIZATION": f"JWT {generate_token(self.user)}", "Content-Type": "application/json", } def tearDown(self): # Delete tenant and domain self.tenant.delete() self.domain.delete() def test_tenant_clients_query(self): client = TenantClient(self.tenant, **self.authentication_headers) response = client.post('/graphql/', {'query': '{ clients { name } }'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['data']['clients'][0]['name'], 'make') error i am getting: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django_tenants/test/cases.py", line 38, in setUpClass cls.tenant.save(verbosity=cls.get_verbosity()) File "/usr/local/lib/python3.8/site-packages/django_tenants/models.py", line 107, in save super().save(*args, … -
Django return render/httpresponse and Json into a single Jsonresponse
I'm new to Django and try to understand how to return 2 different kind of response type inside one return Jsonresponse : view.py def article_filter_mobile(request): # Here I'm trying to get the total records number of my DB number_of_rec = Record.objects.count() # Need to access {{number_of_rec}} in test.html count = render(request, 'test.html', {'number_of_rec': number_of_rec}) # here I'm listing all datas of my DB data = dict() locations = Record.objects.raw("SELECT * FROM myDb") available_lessons = [model_to_dict(l) for l in locations] # Need to access {{available_lessons|safe}} in a JS script inside grid_mobile.html data['html_table'] = render_to_string('grid_mobile.html', {'available_lessons': available_lessons},request=request) # I think my problem is here as data and count are not in the same format return JsonResponse(data,count) Can someone help me to understand what is wrong in this code ? Thanks -
Page not found (404) No comments found matching the query
views,py: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comments fields = ['content'] template_name = 'blog/comment_create.html' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user messages.success(self.request, 'You have made a comment') return super().form_valid(form) class CommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comments fields = ['content'] template_name = 'blog/comment_update.html' def test_func(self): comment = self.get_object() if self.request.user == comment.author: return True else: return False def form_valid(self, form): messages.success(self.request, 'You have updated the post') return super().form_valid(form) urls.py: from django.contrib import admin from django.urls import path from blog.views import home, about, PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, CommentCreateView, CommentUpdateView 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>/create_comment/', CommentCreateView.as_view(), name='comment_create'), path('post/<int:pk>/update_comment/<int:comment_id>', CommentUpdateView.as_view(), name='comment_update'), path('about/', about, name='blog_about'), ] models.py: 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('post_detail', kwargs={'pk': self.post.pk}) that is fom post template: {% for comment in post.comments.all %} <article class="media content-section"> <div class="small text-muted">Comment by {{ comment.author }}</div> <a href="{% url 'comment_update' pk=object.pk comment_id=comment.pk %}">{{ comment.content }}</a> <div class="small text-muted"> Posted on {{ comment.date_posted }}</div> </article> {% endfor %} that is an error: enter image … -
Django: convert dropdowns created with Html pages in Django forms (project already working)
I have a small fully functional project where there are 3 dropdowns, however created with manual Html pages. I'm a beginner and I realized that it's better to use the classic Django Forms (and not create dropdowns manually with html pages). Can you show me how I can convert this little project to Django forms? Thank you **CODE PYTHON ** models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class FullRecord(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) city_departure = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_departure") city_destination = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_destination") @property def departure_destination(self): return f"{self.city_departure}-{self.city_destination}" def __str__(self): return self.country.name views.py **from django.shortcuts import render from .models import FullRecord, Country def trip_selector(request): if "Hx-Request" in request.headers: trips = FullRecord.objects.none() if request.headers["Hx-Trigger"] == "id_trip": country_id = request.GET.get("country") if country_id != "": trips = FullRecord.objects.filter(country_id=country_id) return render(request, "trips.html", {"trips": trips}) elif request.headers["Hx-Trigger"] == "id_extract_single_city": selected_trip = request.GET.get("trips") extracted_cities = [] if selected_trip != "": trip = FullRecord.objects.get(id=int(selected_trip)) trip_with_combined_names = trip.departure_destination split_trip = trip_with_combined_names.split("-") extracted_cities = split_trip return render(request, "extract_single_city.html", {"options": extracted_cities}) else: countries = Country.objects.all() return render(request, "form.html", {"countries": countries})** urls.py **from django.urls import path from . import views urlpatterns … -
Creating a Custom Choices Field in Django Model
I'm working on a Django project and need to implement a charfield field "Custom" in the dropdown menu in the UserProfile model. The requirements are as follows: Users should be able to select their gender from predefined options (Male or Female). Additionally, there should be an option to select "Custom" if the user's gender is not represented by the predefined options. If a user selects "Custom," a text field should appear, allowing them to enter their gender description. I've already created the UserProfile model with predefined gender choices, but I'm not sure how to dynamically show or hide the text field based on the user's selection of "Custom." Note: I want this to be done in both Django Admin and DRF API. Feature should look like this: a screenshot of a custom field taken from Instagram Here's my UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) FEMALE = 'FEMALE' MALE = 'MALE' CUSTOM = 'CUSTOM' NONE = 'NONE' GENDER = [ (FEMALE, "Female"), (MALE, "Male"), (CUSTOM, "Custom"), (NONE, "Prefer not to say"), ] gender = models.CharField( max_length=20, choices=GENDER, default=NONE, ) custom_gender = models.CharField( max_length=255, blank=True, # Allow it to be optional null=True, # Allow it to be null ) …