Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed on Amazon LM2
I am trying to deploy a webapp made on django to AWS Elastic BeanStalk but it is showing the following error: cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed Traceback: 2021-08-04 09:49:56,443 [ERROR] -----------------------BUILD FAILED!------------------------ 2021-08-04 09:49:56,443 [ERROR] Unhandled exception during build: Command 01_migrate failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 135, in build Contractor(metadata).build(configSets, self) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 561, in build self.run_config(config, worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 573, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 273, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed db-migrate.config on LM1 was: container_commands: 01_migrate: command: "django-admin.py migrate --noinput" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: packsapp.settings for LM2 I tried this: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: packsapp.settings and also tried this as well container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && django-admin.py migrate --noinput" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: packsapp.settings But it still fails. What do I need to change? -
TypeError: __init__() got an unexpected keyword argument 'choices' in django project
i'm getting the above error on cmd for the line: continent = forms.CharField(max_length='20', choices=CONTINENT_CHOICES, default='as') class CustomUserCreationForm(UserCreationForm): CONTINENT_CHOICES = [ ('as', 'Asia'), ('af', 'Africa'), ('eur', 'Europe'), ('aus', 'Australia'), ('na', 'North America'), ('sa', 'South America'), ('an', 'Antarctica'), ] continent = forms.CharField(max_length='20', choices=CONTINENT_CHOICES, default='as') ... class Meta(UserCreationForm.Meta): fields = UserCreationForm.Meta.fields + ('continent') -
ImportError: cannot import name 'urllib' from 'moves' (unknown location)
hi if anyone facing this issue and you solved then please suggest me. I am using openedx. docker-compose exec studio env TERM=xterm-256color /edx/app/edxapp/devstack.sh open root@studio:/edx/app/edxapp/edx-platform# paver updatTraceback (most recent call last): File "/edx/app/edxapp/venvs/edxapp/bin/paver", line 8, in sys.exit(main()) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/paver/tasks.py", line 890, in main _launch_pavement(args) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/paver/tasks.py", line 858, in _launch_pavement exec(compile(source, environment.pavement_file, 'exec'), mod.dict) File "pavement.py", line 14, in from pavelib import * File "/edx/app/edxapp/edx-platform/pavelib/init.py", line 6, in from . import assets, bok_choy, database, docs, i18n, js_test, prereqs, quality, servers, tests File "/edx/app/edxapp/edx-platform/pavelib/quality.py", line 13, in from openedx.core.djangolib.markup import HTML File "/edx/app/edxapp/edx-platform/openedx/core/djangolib/markup.py", line 7, in import bleach File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/bleach/init.py", line 7, in from bleach.linkifier import ( File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/bleach/linkifier.py", line 6, in from bleach import html5lib_shim File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/bleach/html5lib_shim.py", line 24, in from bleach._vendor.html5lib import ( # noqa: E402 module level import not at top of file File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/bleach/_vendor/html5lib/init.py", line 25, in from .html5parser import HTMLParser, parse, parseFragment File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/bleach/_vendor/html5lib/html5parser.py", line 6, in from . import _inputstream File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/bleach/_vendor/html5lib/_inputstream.py", line 4, in from six.moves import http_client, urllib ImportError: cannot import name 'urllib' from 'moves' (unknown location) Traceback (most recent call last): File "/edx/app/edxapp/venvs/edxapp/bin/paver", line 8, in sys.exit(main()) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/paver/tasks.py", line 890, in main _launch_pavement(args) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/paver/tasks.py", line 858, in _launch_pavement exec(compile(source, environment.pavement_file, … -
How to fix the websocket connection fail in django channels 3 on Heroku
I am trying to deploy my Django channels app on Heroku. Problem: Websocket fails to connect. Looking at the Heroku logs, this is what I find. 2021-08-04T09:24:47.080386+00:00 app[web.1]: AttributeError: 'RedisChannelLayer' object has no attribute 'groups' The app runs fine locally, and all the problems are caused when deploying. I have followed the docs and searched for the solutions, but I've been unable to find a solution for it. I am using django 3.2.5, channels 3.0.4, channels-redis 3.3.0. Full requirements.txt file below. Full Log 2021-08-04T09:24:47.080383+00:00 app[web.1]: return func(*args, **kwargs) 2021-08-04T09:24:47.080384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/channels/consumer.py", line 125, in dispatch 2021-08-04T09:24:47.080384+00:00 app[web.1]: handler(message) 2021-08-04T09:24:47.080385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/channels/generic/websocket.py", line 59, in websocket_receive 2021-08-04T09:24:47.080385+00:00 app[web.1]: self.receive(text_data=message["text"]) 2021-08-04T09:24:47.080386+00:00 app[web.1]: File "./game/consumers.py", line 46, in receive 2021-08-04T09:24:47.080386+00:00 app[web.1]: response["players_connected"] = len(self.channel_layer.groups.get(self.room_group_name, {}).items()) 2021-08-04T09:24:47.080386+00:00 app[web.1]: AttributeError: 'RedisChannelLayer' object has no attribute 'groups' 2021-08-04T09:24:47.332491+00:00 app[web.1]: 10.47.153.32:29310 - - [04/Aug/2021:09:24:47] "WSDISCONNECT /ws/game/4a676965" - - 2021-08-04T09:24:47.335311+00:00 heroku[router]: at=info method=GET path="/ws/game/4a676965" host=blackjack-django.herokuapp.com request_id=8a46781c-ee66-4c63-bbef-cb1c6e2bf7a2 fwd="146.196.34.235" dyno=web.1 connect=2ms service=1243ms status=101 bytes=145 protocol=https Requirements.txt aioredis==1.3.1 asgi-redis==1.4.3 asgiref==3.4.1 async-timeout==3.0.1 attrs==21.2.0 autobahn==21.3.1 Automat==20.2.0 cffi==1.14.6 channels==3.0.4 channels-redis==3.3.0 constantly==15.1.0 cryptography==3.4.7 daphne==3.0.2 dj-database-url==0.5.0 Django==3.2.5 django-heroku==0.3.1 hiredis==2.0.0 hyperlink==21.0.0 idna==3.2 incremental==21.3.0 msgpack==1.0.2 msgpack-python==0.5.6 psycopg2==2.9.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 pyOpenSSL==20.0.1 pytz==2021.1 redis==2.10.6 service-identity==21.1.0 six==1.16.0 sqlparse==0.4.1 Twisted==21.7.0 txaio==21.2.1 typing-extensions==3.10.0.0 whitenoise==5.3.0 zope.interface==5.4.0 asgi.py import os import django … -
How to change name ot "+ add another Model_name" button in Django admine inline?
I have a model "application Profile" and one other model "Other Income" inline to profile model. I want to change the "add another other income" button name in django inline like shown in picture.Ignore two button shown here consider only one button is visible. Admin.py code `class OtherIncomeAdminInline(admin.StackedInline): model = OtherIncome extra = 0 formset = OtherIncomeInlineFormset fields = (("other_income", "source"), ("amount",),)` here is code of admin.py `admin.register(ApplicantProfile, site=besol_admin_site) class ApplicantProfileAdmin(admin.ModelAdmin): inlines = [AddressAdminInline, EmployerInformationAdminInline,OtherIncomeAdminInline, ReferencesInformationAdminInline] list_display = ["applicant_name", "id", "ssn", "us_citizen", "is_cosigner", "email", "driver_license_no", "created_at"] list_filter = ("first_name", "is_cosigner", "ssn", "us_citizen") search_fields = ("first_name", "ssn", "last_name", "id", "driver_license_no", "email") fieldsets = ( (_('Personal Information'), {'fields': (('first_name', 'middle_name'), ('last_name', 'suffix'), ('email','ssn'), ('home_phone_number', 'cellular_phone_number'), ('date_of_birth', 'us_citizen'), 'driver_license_no', 'license_revoked', 'revoke_reason')}, ), ) form = ApplicantProfileForm queryset = ApplicantProfile.objects.all()` -
Django TypeError at admin: expected str, bytes or os.PathLike object, not PosixPath
Currently I just moved my django project to a new ubuntu server. But when I tried to access the admin website, it always return "TypeError at /admin/: expected str, bytes or os.PathLike object, not PosixPath". The environment of my previous server is: Python3.6.9 and django 3.0.4. The current versions are Python 3.8 and Django 3.2.5. Are there any changes after the version update? The settings.py is: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True 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', 'MyBlog', ... ] 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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'MyBlog.context_processor.Alert_stat', ], }, }, ] WSGI_APPLICATION = 'MyBlog.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myweb', 'USER':'root', 'PASSWORD':'112321', 'HOST':'localhost', 'PORT':'3306', 'OPTIONS':{'charset':'utf8mb4'}, } } ... STATIC_URL = '/static/' STATICFILES_DIRS = … -
input_file_parameters = subject_parameters[input_filename_without_an] KeyError: 'CITI ExcelOutput'
def city_process(sql_params,subject_parameters,list_files, mail_params, out_params): # for file in list_files: email_attachment_file_name=list_files print(email_attachment_file_name) extract_directory = subject_parameters["ZIPFILE_EXTRACT_DIRECTORY"] email_download_directory=subject_parameters['DOWNLOAD_DIRECTORY'] print("Check download directory"+email_download_directory) #this is to added to set the pipeline with zipfile.ZipFile(email_attachment_file_name, 'r') as file: # printing all the information of archive file contents using 'printdir' method print(file.printdir()) # extracting the files using 'extracall' method print('Extracting all files...') file.extractall(extract_directory) print('Done!') # check your directory of zip file to see the extracted files file.close() to_send_files = [] # print(os.listdir()) for file in os.listdir(extract_directory): print(file) servername = 'SQLSERVER' trusted = 'yes' dbconn=connect_db_server(servername,trusted,sql_params) filename = os.fsdecode(file) print(filename) fn_split = filename.split('_') filename_without_an = fn_split[0] try: account_number=fn_split[1].split('.')[0] except IndexError: print("account no is not availbale") account_number = str(0000) print('****',filename) print(account_number) # This is just to get the unique search names df=pd.read_csv(Path(extract_directory,file),header=None, keep_default_na=False) df.columns= df.iloc[0] a = df['SearchNumber'].unique() a = a.tolist() a.remove('SearchNumber') print(a) for i in a: batch_num = i print('batch to be processed-------------') print(batch_num) input_filename, ext = os.path.splitext(filename) input_filename_without_an= input_filename.split('_')[0] input_file_parameters = subject_parameters[input_filename_without_an] table_name = input_file_parameters["TABLENAME"] pfile=generate_readcsv_parameters_fortable(servername,dbconn,table_name) pfile_string=pfile.read() pfile.close() print("accessing load csv parameter file from main") csvparameters_dict=literal_eval(pfile_string) -
Why Image is not being served by django?
I am trying to display image from the django database. in database image link of directories is also given correct. but when I opens that link it gives an error "TemplateDoesNotExist at /media/categories/abc.png" even image is availabe at that link. Models.py from django.db import models def upload_path(instance,filename): return 'categories/{filename}'.format(filename=filename) class Categories(models.Model): name = models.CharField(max_length=255, unique=True) description = models.CharField(max_length=500) image_url = models.ImageField(blank=True, null = True, upload_to= upload_path) REQUIRED_FIELDS = ['name','description','image_url'] Settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' CORS_ALLOW_ALL_ORIGINS = True STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') Views.py class CategoriesListCreateAPI(GenericAPIView, ListModelMixin , CreateModelMixin): queryset = Categories.objects.all() serializer_class = CategoriesSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request , *args, **kwargs): return self.create(request, *args, **kwargs) # Retrieve, update and delete (pk required) class RUDCategoriesAPI(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin): queryset = Categories.objects.all() serializer_class = CategoriesSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request , *args, **kwargs): return self.update(request, *args, **kwargs) def put(self, request , *args, **kwargs): return self.partial_update(request, *args, **kwargs) def delete(self, request , *args, **kwargs): return self.destroy(request, *args, **kwargs) here please look at my API API after uploading image when I … -
Django Channels Daphne Maximum Simultaneous Connection
What is the maximum number of simultaneous connections for Daphne? I use nginx + daphne. I wrote a test on the Client side. Client.py import asyncio import json import websockets async def hello(uri, num): print(num) try: async with websockets.connect(uri) as websocket: await websocket.send(json.dumps({'msg': num})) print(f"(client) send to server: {num}") while True: name = await websocket.recv() print(f"(client) recv from server {name}") except BaseException as error: print(f'{"*" * 20} error: {error} {"*" * 20}') async def test(): tasks = [] for num in range(1024): tasks.append(asyncio.create_task(hello('ws://192.168.0.151:20212/test/', num))) await asyncio.sleep(0.01) if tasks: await asyncio.wait(tasks) await asyncio.sleep(0) asyncio.run(test()) nginx.conf server { listen 20212; server_name 192.168.0.151; client_max_body_size 1024M; access_log /var/log/nginx/nginx.vhost.access.log; error_log /var/log/nginx/nginx.vhost.error.log; root /home/user/Daniel/Python/GitLab/django-signalserver; location / { proxy_set_header Host $http_host; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://192.168.0.151:8500; } } daphne daphne project.asgi:application -b 192.168.0.151 -p 8500 When the number of test connections reached 381, an error is reported server rejected WebSocket connection: HTTP 500. Is it because my settings have not been handled properly, or the maximum number of simultaneous connections can only be done like this? -
How make a reservation system in django
I am making a delivery date and time reservation system in django and there I need to implement a reservation system of time and date for the users. see this UI image here for better understanding I have to make such a kind of thing that if a user reserves a specific time lets say 9 AM on a specific date and places an order, then that particular time related to that particular date that the user placed an order on will get disabled so that no other user can place an order on that same date and time. Now, the problem is I am not very sure how to design the database relationships for this feature. Initially I'm thinking of this model design below but I'm sure that it's not that much efficient. class Date(models.Model): date = models.DateField() class Time(models.Model): time = models.TimeField(auto_now=False, auto_add_now=False) date = models.ForeignKey('Date', on_delete=models.CASCADE) Let's assume that one of my users placed an order on 3rd of the month with a delivery time of 10 AM. So according to the system the time '10 AM' on 3rd of the month should get disabled for other users. But the time '10 AM' on other days of … -
Firebase Social Auth + Django
I am now creating a mobile app with Flutter + Django as backend. I am planning to use Firebase Authentication with FlutterFire, what I understand is that the user logged in/logged out information will then be at the Firebase database. What is the common practice to notify the other backend (in this case is Django) that the user has logged in? And then give access to certain feature in the app? Is it that we use callback given from FlutterFire and then use the generated token from Firebase as the token between our Frontend (Flutter) and Backend (Django)? Thank you -
How to run a function after adding an element to ManyToManyField in django
I'm writing an app which has users functionality, each user can follow another user to see his posts on a main view. My question is. Is there any clever way to trigger a notification when a new entry is added to followed_users? The code of a field that stores users that are followed by a user: followed_users = models.ManyToManyField( "self", verbose_name=_("followed users"), blank=True, symmetrical=False, related_name="followers", ) and a corresponding method in view to follow a user: def follow(self, request: Request, **_kwargs): followed_user = self.get_object() if request.user.followed_users.filter(id=followed_user.id).exists(): return Response({"detail": _("You already follow this user.")}, status=400) request.user.followed_users.add(followed_user) return Response() I know I can invoke a function which creates a notification in follow() function but it's not very elegant for me. -
Filter Model Object using Wild-Chars
I need to be able to filter using wildchars, for example: Surnames.objects.filter(surname="GR%FF%N") should return objects with the following surnames: GRIFFIN, GREFFTEN, GRAFFAIN, and so on. Now obviously filter doesn't recognise % as a wildchar but the code above should demonstrate what I need to do. I also wish to limit the number of results returned. How would you recommend I do this? -
How refresh a table in django-admin without page reload?
I'm trying to create a template of the django-admin wich can refresh the table without reload page. How I can do that? I found that answers, but that does not help me. https://tutsocean.com/questionsbank/question/django-update-a-page-without-reloading/ https://exceptionshub.com/how-to-update-a-django-page-without-a-page-reload.html Django: update a page without reloading I wasted one day and found nothing, please help me. -
destructure dictionary entries inside django templates
view to mark menu items who have been added to cart and alternative approach would be appreciated my view def products(request): if request.method == 'GET': query = request.GET.get('category') user=Customers.objects.get(user=request.user) try: cartitem = list(CartItem.objects.filter(cart__user=user).values_list('id',flat=True)) except ObjectDoesNotExist: pass products={ 'item':[], 'is_added':[] } if query: menus = MenuItem.objects.filter(category__name=query).order_by('-date_added') else: menus = MenuItem.objects.all().order_by('-date_added') for item in menus: products['item'].append(item) if item.id in cartitem: products['is_added'].append(True) else: products['is_added'].append(False) print(products) restaurants = Restaurants.objects.all() categories= Category.objects.all() return render(request,'store/store.html',context={ 'product':products, 'restaurants':restaurants, 'categories':categories }) I am trying to iterate through both item and is_added in parallel, but finding trouble to achieve it in Django templates, I have checked the list approach but I want to achieve it in a parallel way ... <div class="row"> {% for menu in product.menus %} <--- how to modify this line <div class="col-md-4"> <figure class="card card-product-grid"> <div class="img-wrap"> <img src="{{item.image_url}}"> </div> <!-- img-wrap.// --> <figcaption class="info-wrap"> <div class="fix-height"> <a href="{% url 'menus:item' item.id %}" class="title">{{item.item_name}}</a> <div class="price-wrap mt-2"> <span class="price">{{item.price}}</span> <del class="price-old">${{item.price}}</del> </div> <!-- price-wrap.// --> </div> {% if status %} <a href="#" class="btn btn-block btn-success">Added ! </a> {% else %} <a href="#" class="btn btn-block btn-primary">Add to cart </a> {% endif %} </figcaption> </figure> </div> <!-- col.// --> {% endfor %} </div> <!-- row end.// --> -
Edited Image is not saving in Admin ( following Toast-tui-image editor )
I am building a Blog App and I am following Toast tui Image editor - Toast tui Image Editor Github. I am editing image on browser with tui Image editor and saving in database. BUT Image is adding but not edited image is adding. I mean selected image is saving without edit effects. forms.py class ImageForm(forms.ModelForm): class Meta: model = Profile fields = ("image",) def save(self): photo = super(ImageForm,self).save() return photo template.html <link type="text/css" href="https://uicdn.toast.com/tui-color-picker/v2.2.6/tui-color-picker.css" rel="stylesheet" /> <link type="text/css" href="/static/e/css/service-basic.css" rel="stylesheet" /> </head> <body> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> <b>Dreams</b> <input type="file" id="input-image-file" name='photu'> </table> <button type="submit">Save Changes</button> </form> </div> <div class="body-container"> <div class="tui-image-editor-controls"> <div class="header"> <img class="logo" src="img/TOAST UI Component.png" /> <span class="name"> Image Editor</span> <ul class="menu"> <li class="menu-item border input-wrapper"> Load </li> <li class="menu-item border" id="btn-download">Download</li> </ul> </div> <label> <input type="radio" name="input-check-fill" id="input-check-transparent" value="transparent" /> transparent </label> <label> <input type="radio" name="input-check-fill" id="input-check-filter" value="filter" /> filter </label> <script type="text/javascript" src="https://api-storage.cloud.toast.com/v1/AUTH_e18353c4ea5746c097143946d0644e61/toast-ui-cdn/tui-image-editor/v3.11.0/example/fabric-v4.2.0.js" ></script> <script type="text/javascript" src="https://uicdn.toast.com/tui.code-snippet/v1.5.0/tui-code-snippet.min.js" ></script> <script type="text/javascript" src="https://uicdn.toast.com/tui-color-picker/v2.2.6/tui-color-picker.min.js" ></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js" ></script> <script type="text/javascript" src="/static/e/dist/tui-image-editor.js"></script> There are so many functionalities so i uploaded few of them. I also tried super().save() method to return image but still not saving the edited … -
Page not found (404) (Django)
I got an error message while clicking [Delete] option/link in post_detail.html: Page not found (404) No comment found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/post/7/comment/delete/ Raised by: blog.views.CommentDeleteView Here is my files: post_detail.html file {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} {% if not post.comments.all %} No Comments Yet... <a href="{% url 'post-comment' post.pk %}">Add Comment</a> <br/><br/><br/><br/><br/><br/> {% else %} <a href="{% url 'post-comment' post.pk %}">Add Comment</a> <br/><br/> {% for comment in post.comments.all %} <strong> {{user}}, </strong> <small> {{comment.date_added}} </small> <br/> {{comment.body}} <br/> {% if request.user == user %} <a href="{% url 'comment-delete' post.pk %}">[Delete]</a> {% endif %} <br/><br/> {% endfor %} {% endif %} {% endblock content %} models.py file from django.db import models from django.urls.base import reverse_lazy from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(default=timezone.now) date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Meta: ordering = ['-date_added'] views.py file from django.contrib.messages.api import success from django.urls.base import reverse_lazy from users.forms import CommentForm from django import forms from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( … -
The function can't return callable object from it
I created a function to return a list of categories from data base, however, Django just doesn/t see categories and as a result says it a syntax error in the statement and doen't return it. But on the other funtion which I used it sees the list so my program can see it from data. @register.inclusion_tag('news/list_categories.html') def show_categories(): categories = Category.objects.all() return ("categories": categories) Unexpected expression syntax -
Celery crontab on daily basis
I have run the celery tasks based on crontab for every minutes and 12.30 pm on every day. every minute is working perfectly. But the daily tasks of every day 12.30 pm is not working. Any suggestions ? from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-second': { 'task': 'app1.tasks.add_schedular', 'schedule': crontab(minute='*/1'), }, 'mail-check': { 'task': 'app1.tasks.mail_schedular', 'schedule': crontab(hour=12,minute=25), } } -
Django default arguments in URL
I have a url path that looks like this: path("asset_app/asset/<str:location>/", views.AssetListView.as_view(), name="asset_app_asset_list"), I want that if location is not set that it sets location = "all" How do I do that? -
Django simplejwt: How to add refresh token to dict?
I am using simplejwt to get an access and refresh tokens. In a view I need to create a dict, where the both will be stored as well as access token claims and another additional data. Everything works but by some reason when the refrsh token is added to dict, it returns its decoded value, but not the token. my views.py @csrf_exempt #@api_view(('GET',)) def check_token(request): token_refresh = RefreshToken.for_user(request.user) print('REFRESH', token_refresh) token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1] data = {'token': token, 'refresh_token': token_refresh} try: valid_data = TokenBackend(algorithm='HS256').decode(token, verify=False) data['uui'] = valid_data['user_id'] data['validUntil'] = valid_data['exp'] data['clientId'] = 'default' print(data) return JsonResponse(data) except ValidationError as v: print("Validation error", v) print('REFRESH', token_refresh) returns the token: 'REFRESH eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI...' but data object returns: {'token': 'eyJ0eXAiOiJKV1QiLCJhbGci...', 'refresh_token': {'token_type': 'refresh', 'exp': 1628664751, 'jti': '38f0e3a4d7bb452681834a6b149aa496', 'user_id': 'None'}, 'uui': 1, 'validUntil': 1628059131, 'clientId': 'default'} my ideal result: {'token': 'eyJ0eXAiOiJKV1QiLCJhbGci...', 'refresh_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI...', 'uui': 1, 'validUntil': 1628059131, 'clientId': 'default'} -
Can I use the same @property on multiple models in django?
I want to define an @property once and use it on two different models. Is this possible? Example: Suppose I have two models, seller and buyer: class seller(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class buyer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) And I wish to add a property for the django admin interface to display both models: @property def display_name(self): return f"{first_name} {last_name}" Is there a way to define this property once, but use it for both models? -
Use Django ORM in multiprocess spawn process
i need to use the Django ORM in some spawned process using python multiprocess module. At this moment, this how i spawn the process: import multiprocessing with multiprocessing.get_context('spawn').Pool() as pool: pool.map(insert_to_db, args) Now, here is the issue: the function insert_to_db uses the django ORM to get some objects, check data consistency and save the new collected result to DB. Actually, i can't start the spawned process using fork context due to some unidentified deadlocks. My initial idea is to start a the process, inject the Django dependencies, and before doing the execution of the insert_to_db function execute the django.setup() to load all django things. Anyone is able to give me a solution? -
Run cron job with curl to execute django command management
I have a command management that I should run daily at midnight, I usually execute it from my pc, I want to create a cronjob that can do this automatically here the command that I execute from my local environment: env=application; kubectl exec -ti $(kubectl get pods| grep $env| awk '{print $1}') -c "application" -- ./manage.py daily_job and here the corn job yml file that I wrote: apiVersion: batch/v1beta1 kind: CronJob metadata: name: update-client-tasks labels: environment: application spec: schedule: "0 0 * * *" jobTemplate: spec: template: spec: restartPolicy: OnFailure containers: - name: update-client-tasks image: gcr.io/application-156608/application:v0.5.32 args: - /usr/bin/curl --data "key=$CRON_KEY" http://application/code/ | env=application; kubectl exec -ti $(kubectl get pods| grep $env| awk '{print $1}') -c "application" -- ./manage.py daily_job env: - name: CRON_KEY valueFrom: secretKeyRef: name: application-secrets key: cronKey when running this corn job I got this error: 2021-06-22 09:00:24.184 JSTTraceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], … -
How to configure django standalone app to install automatically all sub apps?
Problem description I have django standalone app named django_codeserver. It can be loaded from my private package registry as a pip-package. My app contains about twenty sub-apps for example django_codeserver.headers, django_codeserver.genders etc. Current behaviour To register all models in my project which uses django_codeserver, I have to register all the sub applications in the parent project INSTALLED_APPS such as: INSTALLED_APPS = [ ... 'django_codeserver.headers', 'django_codeserver.genders' ... ] Preferred behaviour I would want all the sub apps being registred in the parent project when I only: Install the standalone django app as pip-package (pip install django-codeserver) Register only the parent app in parent project installed apps: INSTALLED_APPS = [ 'django_codeserver ]