Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Print all attributes from an object with Django templates
I am a novice programmer, I am learning python and Django on my own. I got stuck in a part of my application: I have many models with many attributes, and I have a window and a template for each of them. The idea is to show in each one, a table with all its content with an sql query in the file view.py objects.all () My code: MODELS.PY from django.db import models class MFuel(models.Model): marca = models.TextField(db_column='Marca', blank=True, null=True) # Field name made lowercase. modelo = models.TextField(db_column='Modelo', blank=True, null=True) # Field name made lowercase. potencia_electrica_kw = models.BigIntegerField(db_column='Potencia_electrica_kW', blank=True, null=True) # Field name made lowercase. fecha_oferta = models.DateTimeField(db_column='Fecha_oferta', blank=True, null=True) # Field name made lowercase. pais_proyecto = models.TextField(db_column='Pais_Proyecto', blank=True, null=True) # Field name made lowercase. proyecto = models.TextField(db_column='Proyecto', blank=True, null=True) # Field name made lowercase. uds = models.FloatField(db_column='Uds', blank=True, null=True) # Field name made lowercase. precio_eur = models.FloatField(db_column='Precio_EUR', blank=True, null=True) # Field name made lowercase. precio_usd = models.FloatField(db_column='Precio_USD', blank=True, null=True) # Field name made lowercase. precio_unitario_eur = models.FloatField(db_column='Precio_Unitario_EUR', blank=True, null=True) # Field name made lowercase. ratio_eur_kw = models.FloatField(db_column='Ratio_eur_KW', blank=True, null=True) # Field name made lowercase. largo_mm = models.FloatField(db_column='Largo_mm', blank=True, null=True) # Field name made lowercase. ancho_mm = models.FloatField(db_column='Ancho_mm', blank=True, null=True) … -
How to list only active users in dropdown menu
I want to list all active users in dropdown list. But all users are listed in the dropdown How can I do it? template <form method="post"> {% csrf_token %} {{ form|crispy }} <input type="hidden" name="customer_id" value="{{ customer.id }}"> <button type="submit" class="btn btn-primary btn-sm">Assign</button> </form> forms class AssignForm(forms.ModelForm): class Meta: model = Customer fields = ('user',) views form = AssignForm(request.POST or None) if request.POST: customer_id = request.POST.get('customer_id', None) customer = Customer.objects.get(id=customer_id) user = UserProfile.objects.get(id=request.POST.get('user', None)) customer.user = user customer.save() # form.save() return redirect('user:customer_list') models class UserProfile(AbstractUser, UserMixin): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) ... -
unable to Send compressed gzip data using Django Rest framework
I am sending JSON file in Django Rest APIView framework. I want to reduce the size of the file. Implemented below code but Receving below error: @api_view(['GET','POST']) def myMethod(request): from rest_framework.response import Response if request.method == 'POST': import gzip # ****Some code lines here to generated small json*** myJson = json.dumps(parsed, indent=4) compressedContent = gzip.compress(myJson.encode('utf-8'), 5) # compressedContent is byte format return Response(compressedContent, status=status.HTTP_200_OK) As mentioned in this link, I implemented middleware too. Django rest framework, set the api response Content-Encoding to gzip MIDDLEWARE = [ 'django.middleware.gzip.GZipMiddleware', ... ] Trying to call from Postman and it is showing below error. UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte. 500, Internal server error. Is there a way I can setup Accept-Encoding somewhere. I cannot figureout this. Please note postman has Accept-Encoding to gzip, deflate, br Could you please answer what is the problem? Thanks -
Problem this deploy django project to Heroku
I try deploy django app to heroku and get errors: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to tandt-online-webchat. remote: To https://git.heroku.com/tandt-online-webchat.git ! [remote rejected] master -> master (pre-receive hook declined) error: не удалось отправить некоторые ссылки в «https://git.heroku.com/tandt-online-webchat.git» I done all what need: git add . git commit -m "releze heroku vers 1" and when i do git push heroku master i get this error I have all needs files: Procfile and requirements.txt In Procfile i have: web: gunicorn web_chat.wsgi and to requirements.txt I input pip freeze, and i shure what i have gunicorn her. What I do wrong? -
Select2 working incorrectly with Formsets
I have script like this and this working with only first form, others are frozen and did not work at all. $(document).ready(function() { $('#id_membership-0-company').select2(); }); I'm not able to change # to . because of every new form have new id like id_membership-0-company, id_membership-1-company and so on, and all my forms have same class (this field don't have separate class) I'm not able to just add all id's inside this function because of it works only when the page is loaded so only id 0 will work this way I was try to do something like this: add onclick="addRow()" inside "Add form" button html tag and this code in script. Without Timeout function it doesn't work because script executes too fast. It works for two forms (if I press "Add form" button) but not working if I adding more id's (in this scenario after the second form many more incorrect forms created for this field) function addRow() { function activateForms(){ $('#id_membership-0-company').select2(); $('#id_membership-1-company').select2(); } setTimeout(activateForms, 1000); } How to fix that? I need select2 widget for first field of every form? -
Django + postgreSQL : why migrating did work even though I hadn't given my db info?
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } It's my settings.py. DATABASE 'test' has password, but I did not enter it. and for testing, I tried migrating: creating superuser did work, too. but in psql, postgres-# \dt Did not find any relations. I thought this message means DB not connected with Django, is it right? If so, how could migrating work w/o error messages like no connection? Is there no relationship between migration and DB? -
How to connect django-allauth user with custom user model
I made a socialmedia application which i use django signup and login form,,,also i use django allauth. I added a editprofile option for user editing,, with django login user can edit their profile but with google login user cannot able to edit his/her profile. Then it gives ( UserProfile matching query does not exist.) this error. please help me to solve this problem models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') full_name = models.CharField(max_length=200,blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) bio = models.TextField(blank=True) cover_pic = models.ImageField(upload_to='cover_pics',blank=True) dob = models.DateField(blank=True,null=True) facebook = models.URLField(blank=True) def __str__(self): return str(self.user) views.py @login_required def edit_profile(request): currunt_user = UserProfile.objects.get(user=request.user) form = EditProfile(instance=currunt_user) if request.method == "POST": form = EditProfile(request.POST, request.FILES, instance=currunt_user) if form.is_valid(): form.save(commit=True) form = EditProfile(instance=currunt_user) return HttpResponseRedirect(reverse('login_app:profile')) context = { 'title': 'Edit Profile - FriendsBook', 'form':form } return render(request,'login_app/edit_profile.html',context) Error message: DoesNotExist at /accounts/edit_profile/ UserProfile matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/edit_profile/ Django Version: 3.2.5 Exception Type: DoesNotExist Exception Value: UserProfile matching query does not exist. Exception Location: C:\Users\admin\Desktop\djangoclass\social media\socialenv\lib\site-packages\django\db\models\query.py, line 435, in get Python Executable: C:\Users\admin\Desktop\djangoclass\social media\socialenv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\admin\\Desktop\\djangoclass\\social media\\socialmedia', 'c:\\program files\\python39\\python39.zip', 'c:\\program files\\python39\\DLLs', 'c:\\program … -
Django Dict Filter several AND OR Condition
i try to make a filterdict dynamicaly. As Result i get for example such a filterdict: filterdict {'price_from__lte': Decimal('120000.00'), 'price_till__gte': Decimal('120000.00'), 'wc': True, 'balcony_count_from__lte': 1, 'balcony_count_till__gte': 1} So i can filter searchcriterialist = Searchcriteria.objects.filter(**filterdict) But i want from every field a OR Condition where all items with Null are include. So i need a dict like this: filterdict {('price_from__lte': Decimal('120000.00') OR 'price_from__lte': NULL), ('price_till__gte': Decimal('120000.00') OR 'price_till': 0), ('wc': True OR 'wc': NULL), ('balcony_count_from__lte': 1 OR 'balcony_count_from':0), ('balcony_count_till__gte': 1 OR 'balcony_count_till':0)} How can i build dynamical i dict with a mixture of OR and AND Contitions? Regards -
Django Admin save_model() creating duplicate objects
While clicking on save button multiple times. Multiple entries are getting created in db. How can i put a check there. -
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 …