Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CKEditor Can't install emoji plugin
I can't install emoji plugin correctly with CKEditor 4. I follow the documentation and install dependancies too. Emoji seems to be here somewhere but it is not displayed in the toolbar. Notice I use django-ckeditor but that works the same. There is no error in log console from my browser. Here is my config : CKEDITOR_CONFIGS = { 'default': { # 'toolbar': 'full', 'codeSnippet_theme': 'monokai_sublime', 'toolbar': 'Custom', 'toolbar_Custom': [ ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', 'RemoveFormat', '-', 'Undo', 'Redo'], ['Find', 'Replace', '-', 'SelectAll'], ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language'], ['Link', 'Unlink'], ['Image', 'Table', 'HorizontalRule', 'CodeSnippet', 'Code'], ['emoji', 'SpecialChar', 'Youtube'], ['Styles', 'Format', 'Font', 'FontSize'], ['TextColor', 'BGColor'], ['Maximize', 'ShowBlocks'], ], 'extraPlugins': 'codesnippet,youtube,codeTag,emoji', 'removePlugins': 'flash,anchor,iframe,forms,div,exportpdf,templates', 'removeButtons': 'Anchor', 'width': '100%', 'tabSpaces': 4, } } Notice that youtube, codeTag and codesnippet work perfectly and I do the same for emoji which doesn't work. Please, someone can help me? -
How to filter order with today and yesterday date in django?
I want to get total sales of order by today, yesterday, quarterly and yearly. And here is my code: today = Order.objects.filter(created_at__date=request.data['today']).aggregate(Sum('total_price')) yesterday = Order.objects.filter(created_at__date=request.data['yesterday']).aggregate(Sum('total_price')) quarterly = Order.objects.filter(created_at__range=[request.data['quarterly'], request.data['today']]).aggregate( Sum('total_price')) yearly = Order.objects.filter(created_at__range=[request.data['yearly'], request.data['today']]).aggregate( Sum('total_price')) response_data = { "today_sales": today, "yesterday_sales": yesterday, "quarterly_sales": quarterly, "yearly_sales": yearly } return Response(response_data) But this code give errors for today and yesterday date. But I can successfully retrieve quarterly and yearly sales. So please help me with today and yesterday sales to retrieve. -
Can't connect .env file of smtp details to django
settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') .env export EMAIL_HOST_PASSWORD=<> export EMAIL_HOST_USER = <> export EMAIL_HOST=<> 3.Termial (Carealenv) E:\atom data\mywebsite>source .env 'source' is not recognized as an internal or external command, operable program or batch file. I am having error of SMTPserverdisconnected .. please run connect first I want to connect my .env file to django so that SMTPServer get connected and i can send verfication email to users. It will be great help.. Thank you -
How to take multiple order items at once from frontend (single api call) and save in a single order id
In the picture shown above, all 3 different items with different quantities are sent in a single API call as createorder when the proceed to checkout is clicked. I am not sure how to save all those objects at once in DB. What I have written is as follows: My models: class OrderItem(models.Model) : user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} items of {self.item} of {self.user.email}" class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) items = models.ManyToManyField(OrderItem,blank=True, null=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_details = models.ForeignKey('BillingDetails',on_delete=models.CASCADE,null=True,related_name="order") def __str__(self): return self.user.email My view: ( although it doesn't work with the business logic) #class AddtoOrderItemView(APIView): #permission_classes = [IsAuthenticated] # def post(self, request, pk): # item = get_object_or_404(Product, pk=pk) # order_item, created = OrderItem.objects.get_or_create( # item=item, # user=self.request.user, # ordered=False # ) # order_qs = Order.objects.filter(user=self.request.user, ordered=False) # # if order_qs.exists(): # order = order_qs[0] # # if order.items.filter(item__pk=item.pk).exists(): # order_item.quantity += 1 # order_item.save() # return Response({"message": "Quantity is added", # }, # status=status.HTTP_200_OK # ) # else: # order.items.add(order_item) # return Response({"message": " Item added to your cart", }, # status=status.HTTP_200_OK, # ) # else: # … -
how to UUID create and call?
I am making an app, how can I issue and call UUID when first running the app? I'm using Python, Django . And I have to make a call to the URL for the front. import uuid print uuid.uuid4() 2eec67d5-450a-48d4-a92f-e387530b1b8b How to make it is like this. Need to create a model? -
command "python .setup.py egg _info" failed with error code 1
hellow i'm new to python and django. Currently i'm trying to run a project made in django 1.10.2 and python 2.7 in ubuntu 16.04. The project uses a module called python-social-auth, which causes me the following error when I try to install. enter image description here Hopefully you can help me in detail to solve this problem because as I told you I am new to using these tools. -
Set maximum payload size to POST request in django rest framework api
I am using DRF for mobile application. now I want to set the maximum data limit that client side can sent to POST api. How can i set that limit in DRF (django rest framework)? I found this post but i need in more details. -
Why django DateTimeField store One day before date than current date in mysql auto_now_add filed?
This is the code in my settings.py file, but still i cannot get accurate date when i create any entry in database, it always shows date with time less than 5:30 hours from the current time. Why? LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True -
Django admin access error after deploying on Heroku
When I try to access admin sitename.herokuapp .com/admin , then it shows this Programming Error Views.py file from django.shortcuts import render from . serializers import apiserializer from rest_framework import viewsets from .models import apimodel class apiview(viewsets.ModelViewSet): queryset = apimodel.objects.all() serializer_class = apiserializer API's fully works fine on localhost and I can POST & GET data even by django admin or via postman models.py file from django.db import models # Create your models here. class apimodel(models.Model): name = models.CharField(max_length=30) age = models.IntegerField(default=0) city = models.CharField(max_length=20) def __str__(self): return self.name admin.py file from django.contrib import admin from . models import apimodel admin.site.register(apimodel) serializers.py file from rest_framework import serializers from .models import apimodel class apiserializer(serializers.ModelSerializer): class Meta: model = apimodel fields = ('id', 'name', 'age', 'city') project/urls.py file from django.contrib import admin from django.urls import path, include from apiapp import urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('apiapp.urls')) ] app/urls.py file from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('api', views.apiview) urlpatterns = [ path('', include(router.urls) ) ] I am unable to access django admin page after getting it deployed on herokuapp. I have already created superuser and also I have deployed by changing DEBUG=True … -
can't source .env file in django
1.settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('EMAIL_HOST') EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') .env export EMAIL_HOST_PASSWORD=<> export EMAIL_HOST_USER = <> export EMAIL_HOST=<> Termial (Carealenv) E:\atom data\mywebsite>source .env 'source' is not recognized as an internal or external command, operable program or batch file. I want to connect my .env file to django so that SMTPServer get connected and i can send verfication email to users. It will be great help.. Thank you -
How to compare 2 fields in Django Forms
I have 2 fields on my Model: class MyModel(models.Model): min= models.PositiveIntegerField(null=True) max= models.PositiveIntegerField(null=True) How to compare if max is gte to min them when I click save or register? -
python - How to UUID create and call?
I am making an app, how can I issue and call UUID when first running the app? I'm using Python, Django .And I have to make a call to the URL for the front. import uuid print uuid.uuid4() 2eec67d5-450a-48d4-a92f-e387530b1b8b How to make it is like this. -
How can I make chart day to day objects count in Django?
My question is I need to make a dashboard page. In that, I need to make a chart on day to day created objects by the specific user in Django like the image below. -
View in PostgreSQL is not showing newly inserted records
When I insert new rows in tables, my view does not reflect changes. On the other hand, if I delete rows, it is reflected in view. Why is it so? I'm using PostgreSQL 13.2. CODE create_query = "CREATE OR REPLACE VIEW view_contact AS" create_query += " SELECT" create_query += " per.prefix, CONCAT(per.first_name, ' ', per.middle_name, ' ', per.last_name) AS contact_full_name, per.suffix," create_query += " con.personal_mobile, con.personal_alternate_mobile, con.personal_email, con.personal_alternate_email," create_query += " FROM contact_mgmt_personalinfo per" create_query += " INNER JOIN contact_mgmt_contactinfo con" create_query += " ON per.id = con.person_id;" select_query = "SELECT * FROM view_contact;" -
Result management in python Django
I am designing a web application in python Django with postgres as database, for multiple schools. Every school will have a separate login and only the owner data is displayed. The main problem I am facing in this design is that these schools conduct exams based on books not on subjects (Like: English, Hindi, Maths, Science, Social, …) like in regular schools. These schools follow different book. Every school has their own syllabus. These books (as syllabus) might change almost every year. Which means that the syllabus is not a permanent syllabus, might change as and when required. enter image description here In the above example the school has a syllabus based on book in the Academic year 2019-20 which was changed in academic year 2020-21 as they introduced New Book7 and New Book 8. And the same is with other schools. Syllabus for each school is different and in different academic years. enter image description here The other challenge is the result management of these schools. Since the books (syllabus) changes almost every year, how to maintain the results of student of that particular academic year in the database. Can any one help me is structuring this task please. -
django serve apache24 windows 10
[Thu Feb 25 09:14:28.216513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] mod_wsgi (pid=5048): Failed to exec Python script file 'C:/Apache24/htdocs/Queue/app/app/wsgi.py'. [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] mod_wsgi (pid=5048): Exception occurred processing WSGI script 'C:/Apache24/htdocs/Queue/app/app/wsgi.py'. [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] Traceback (most recent call last):\r [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] File "C:/Apache24/htdocs/Queue/app/app/wsgi.py", line 27, in \r [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] application = get_wsgi_application()\r [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] File "c:\python39\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application\r [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] django.setup(set_prefix=False)\r [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] File "c:\python39\lib\site-packages\django\init.py", line 24, in setup\r [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] apps.populate(settings.INSTALLED_APPS)\r [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] File "c:\python39\lib\site-packages\django\apps\registry.py", line 83, in populate\r [Thu Feb 25 09:14:28.217513 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] raise RuntimeError("populate() isn't reentrant")\r [Thu Feb 25 09:14:28.218512 2021] [wsgi:error] [pid 5048:tid 1296] [client ::1:50711] RuntimeError: populate() isn't reentrant\r [Thu Feb 25 09:14:28.258486 2021] [wsgi:error] [pid 5048:tid 1288] … -
How to filter a queryset of CharField as Int in Django?
I have a model as a CharField but all values are int. salary_amount_min = models.CharField(max_length=10, default='', null=True) salary_amount_max = models.CharField(max_length=10, default='', null=True) How to do a Filter to get Less Than Equal and Greater Than Equal on these fields? My current filter: search_salary_min = hr_form.cleaned_data['search_salary_min '] search_salary_max = hr_form.cleaned_data['search_salary_max '] salaryMinQS = Q(salary_amount_min__gte=search_salary_min ) salaryMaxQS = Q(salary_amount_max__lte=search_salary_max ) If I display on terminal the QS: MIN (AND: ('salary_amount_min__gte', '2100000')) MAX (AND: ('salary_amount_max__lte', '2600000')) -
cant upload files through DRF
my model.py class HNUsers(models.Model): USERTYPE = ( ... ) GENDER = ( (u'M', u'Male'), (u'F', u'Female'), (u'O', u'Other'), ) f_name = models.CharField("Full Name", max_length=100, null=True, blank=True) first_name = models.CharField("First Name", max_length=100, null=True, blank=True) last_name = models.CharField("Last Name", max_length=100, null=True, blank=True) my views.py @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def user_api_v2(request): """ This method returns ..... """ if request.method == 'POST': data = JSONParser().parse(request) print(data) try: user = HNUsers.objects.get( Q(username=data['username']) | Q(email=data['email']) | Q(mobile_number=data['mobile_number'])) return Response({"message": "User exists" }, status=status.HTTP_400_BAD_REQUEST) except HNUsers.DoesNotExist : serializer = UserSerializer_v2(data=data) if serializer.is_valid(): serializer.save() #return Response({'success': True, 'id': user.id, 'username': user.username, 'city': user.city, 'country': user.country, 'full_name': user.full_name, 'email': user.email, 'profile_img_url': user.profile_img_url}, status=status.HTTP_201_CREATED) return Response({"message": "User created"}, status=status.HTTP_201_CREATED) # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) MY serializer.py class UserSerializer_v2(serializers.HyperlinkedModelSerializer): first_img = serializers.FileField() class Meta: model = HNUsers fields = [ 'hnid', 'email', 'mobile_number', 'f_name', 'date_of_birth', 'gender', 'country', 'city', 'first_img_url', 'username', 'first_img', ] While I can create new user without uploading image but I want to upload the file with it . If I try to upload file POSTMAN response with the following error JSON parse error - 'utf-8' codec can't decode byte 0xff in position 1124: invalid start byte" -
Uploading audio files to S3 so they can be streamed instead of downloaded
I recently built an app in Django that allows users to upload audio files and then stream them. When I upload the mp3 files directly through the AWS console everything works fine and the files can be streamed in an html audio element. However, when I upload the files through my app it won't play them in the html element and it automatically downloads them when I click on the object url in S3. How do I fix my code so that the files are loaded into the browser instead of forced to download? for uploaded_audio_file in files: audio_file_instance = Song(song_title=track_list[j], concert=concert_instance) # s3 audio_file_for_S3 = uploaded_audio_file.name session = boto3.session.Session() s3_session = session.resource('s3') s3_session.Bucket('<my-bucket-name>').put_object(Key=uploaded_concert_year + '/' + uploaded_venue_name + '/' + uploaded_concert_month_and_day + '/' + audio_file_for_S3, Body=audio_file_for_S3, ContentType='audio/mp3', ACL='public-read') audio_name_without_spaces = audio_file_for_S3.replace(' ', '+') unformatted_location = 'https://<my-bucket-name>.s3.us-east-2.amazonaws.com/' + uploaded_concert_year + '/' + uploaded_venue_name + '/' + uploaded_concert_month_and_day + '/' + audio_name_without_spaces audio_file_instance.song_location = unformatted_location.replace(' ', '+') audio_file_instance.save() The line where I am uploading the files is here s3_session.Bucket('<my-bucket-name>').put_object(Key=uploaded_concert_year + '/' + uploaded_venue_name + '/' + uploaded_concert_month_and_day + '/' + audio_file_for_S3, Body=audio_file_for_S3, ContentType='audio/mp3', ACL='public-read') I thought read on here that adding 'ContentType='audio/mp3'' would fix this issue but it continues to download … -
Installation de mysqlclient
Voilà l'erreur que j'ai quand je fais le pip install mysqlclient.Aidez moi s'il vous plaît $ pip install mysqlclient Ensuite j'ai ça comme erreur lors e l'exécution : Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB)Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/feub1532/virtualenv/cobiRT/3.8/bin/python3.8_bin -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-5_8z4k8g/mysqlclient_5c00b1b207d5480a8e5ab8bdc487fc0a/setup.py'"'"'; __file__='"'"'/tmp/pip-install-5_8z4k8g/mysqlclient_5c00b1b207d5480a8e5ab8bdc487fc0a/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-s6ziewau cwd: /tmp/pip-install-5_8z4k8g/mysqlclient_5c00b1b207d5480a8e5ab8bdc487fc0a/ Complete output (43 lines): mysql_config --version ['10.3.28'] mysql_config --libs ['-L/usr/lib64', '-lmariadb', '-lpthread', '-ldl', '-lm', '-lssl', '-lcrypto', '-lz'] mysql_config --cflags ['-I/usr/include/mysql', '-I/usr/include/mysql/..'] ext_options: library_dirs: ['/usr/lib64'] libraries: ['mariadb', 'pthread', 'dl', 'm'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql', '/usr/include/mysql/..'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] /opt/alt/python38/lib64/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.8/MySQLdb creating build/lib.linux-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.8/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.8 … -
Syntax Error after installing python when attempting to use the pip command
I am attempting to install python and Django. I am getting this error every time I attempt to install anything with pip. All I have done right now is brew install python Then, I used: sudo easy_install pip After when doing the command below I get the sytanx error. Stefanoss-MBP:javaTutor fetz$ python -m pip install Django Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/Library/Python/2.7/site-packages/pip-21.0.1-py2.7.egg/pip/__main__.py", line 21, in <module> from pip._internal.cli.main import main as _main File "/Library/Python/2.7/site-packages/pip-21.0.1-py2.7.egg/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ -
UnicodeEncodeError when printing Japanese characters from Django on Apache Server
Inside any django view, I put a simple print() such that I can view the output on Apache's error log. def list_of_main_units(request): print("some english characters") print("テスト3") Here, The first print works perfectly fine outputing the exact characters -> some english characters But, The problem is when I try outputting Japanese characters , it turns into some unicode literals. Output for print("テスト3") -> \xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88\xef\xbc\x93 -
How to create and call UUID?
UUID I am making an app, how can I issue and call UUID when first running the app? I'm using Python, Django .And I have to make a call to the URL for the front. -
Serving Django + React on same nginx server
I have a React PWA frontend and a Django backend (plus admin) that I want to serve on the same Digital Ocean droplet using nginx. In the past, I simply served the built index.html through a Django view, but that can be somewhat slow and doesn't seem to enable the PWA features. Any ideas how to configure nginx for that? Thanks. -
ImportError: No module named 'project.wsgi_prod'
so im trying to deploy my dockerized django app to heroku, my deployment succeeds but the gunicorn worker crashes on launch with the error ImportError: No module named 'myproject' in my docker-entrypoint.sh My root/docker/web/docker-entrypoint.sh has the following #!/bin/bash . ./ready.sh python manage.py migrate exec gunicorn myproject.wsgi_prod -b 0.0.0.0:8000 -k gevent --workers 3 --timeout 90 my root/myproject/wsgi.py looks like this import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() I'm assuming this is a path issue, i tried adding cd ../.. before my exec line but that didn't fix it. Any ideas?