Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django LOGGING in docker problem with log file
Hi i have a problem with my default project configure: now i dont know why log file add something like SELECT .... and when i refresh website nothing happend in log file my settings.py logging # Default logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './logs/debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } my debug.log files problem (0.079) SELECT c.relname, CASE WHEN c.relispartition THEN 'p' WHEN c.relkind IN ('m', 'v') THEN 'v' ELSE 't' END FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid) ; args=None (0.070) SELECT "my_default_docker_project_django_migrations"."id", "my_default_docker_project_django_migrations"."app", "my_default_docker_project_django_migrations"."name", "my_default_docker_project_django_migrations"."applied" FROM "my_default_docker_project_django_migrations"; args=() (0.068) SELECT c.relname, CASE WHEN c.relispartition THEN 'p' WHEN c.relkind IN ('m', 'v') THEN 'v' ELSE 't' END FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid) ; args=None (0.070) SELECT "my_default_docker_project_django_migrations"."id", "my_default_docker_project_django_migrations"."app", "my_default_docker_project_django_migrations"."name", "my_default_docker_project_django_migrations"."applied" FROM "my_default_docker_project_django_migrations"; args=() (0.072) SELECT c.relname, CASE WHEN c.relispartition THEN 'p' WHEN c.relkind IN ('m', 'v') THEN … -
How to trigger notification sound when onmessage event occur using django channels?
I have created a chat website using django channels and want to play some audio as notification alert when any message was send / received between users. can anyone could help me in resolving it ? -
python manage.py dumpdata Unable to serialize database
I am trying to run the command python manage.py dumpdata > data.json However, I receive such a traceback: CommandError: Unable to serialize database: 'charmap' codec can't encode characters in position 1-4: character maps to <undefined> Exception ignored in: <generator object cursor_iter at 0x0000020E11353820> Traceback (most recent call last): File "C:\Users\Illia\Desktop\MyDjangoStuff\greatkart\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1625, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. How to solve this issue? -
built real time chat app with graphene(django)
I am working on social media like project. Frontend in react native and backend in django with graphql, database is postgresql. I want to build real time chat app, is it possible to do it with graphene, i searched a lot but grapahene doesnt support subscriptions. i don,t want to use django channels because it needs redis and it will cost more to host it along with psql. Any ideas how to implement it? Thanks -
Different behavior of the wagtail on the server and on the local machine
I have a strange wagtail behaviour. When I start Django on the local machine via run server all works fine, but when it runs on a server I have a follow error: PageClassNotFoundError at /admin/pages/196/edit/ The page 'Цены' cannot be edited because the model class used to create it (core.tablist) can no longer be found in the codebase. This usually happens as a result of switching between git branches without running migrations to trigger the removal of unused ContentTypes. To edit the page, you will need to switch back to a branch where the model class is still present. The same database, the same code base, I was checking the git branch is the same as the local machine. Guys, please help, I'm in my second week of beating this problem. -
Python, Django: get data from select-fields inside a table
inside my app I have a table that contains a select-field in each row. After pressing the submit-button I would like to receive all the selected values inside a list (or something else that's usable): template: <form method="POST"> {% csrf_token %} <table name="table-example"> <thead> ... </thead> <tbody> {% for item in list_example %} <tr> <td>...</td> <td>...</td> <td> <select name="select-example"> {% for item in list_selections %} <option name="option-example" value="{{ item }}">{{ item }}</option> {% endfor %} </select> </td> </tr> {% endfor %} </tbody> </table> <button type="submit">Update</button> </form> When trying to receive data from I only get one field! if request.method == "POST": data = request.POST.get('option-example', None) What am I doing wrong or what am I missing here? Or is this even possible? Thanks for all your help and have a great day! -
Django DateTimeField selected appointment
Lets say that someone booked an appointment. How can I let the date of the appointment un-choosable (not valid) so when he chooses the same date it appears error that the thing is not valid ? -
Cookie's domain set fail Django
I'm using Django for my two project. And I set SESSION_COOKIE_DOMAIN for all of them: SESSION_COOKIE_DOMAIN= ".bvroms.cn" Say one project's domain url is back.bvroms.cn and the other one is akm-back.bvroms.cn But when I go to visit back.bvroms.cn after I 've visited akm-back.bvroms.cn the cookie of akm-back.bvroms.cn is blocked. It showed: This cookie was blocked because neither did the request URL's domain exactly match the cookie's domain, nor was the request URL's domain a subdomain of the cookie's Domain attribute value. My question is why theese two domain were not the subdomain of the SESSION_COOKIE_DOMAIN? Is there something wrong with my settings? Thanks -
Django Queryset from two many-to-many classes
I have been trying to write a Django app that manage school student registration, for that I have two models; Student model & ClassRoom model, these two models are many-to-many related models through a custom model (Enrollment model) as follow: class Student(models.Model): fname = models.CharField(max_length=50) sname = models.CharField(max_length=50) gname = models.CharField(max_length=50) lname = models.CharField(max_length= 50) stdId = models.CharField(max_length= 10) # other student attributes class ClassRoom(models.Model): eduYear = models.ForeignKey(EduYear, on_delete=models.CASCADE) stage = models.ForeignKey(Stage, on_delete=models.CASCADE) stageClass = models.ForeignKey(StageClass, on_delete=models.CASCADE) oneClass = models.CharField(max_length=1) max_std = models.IntegerField(null=True, blank=True) student = models.ManyToManyField(Student, through='Enrollment') class Meta: unique_together = ("stage","stageClass","eduYear","oneClass") def __str__(self): pass return '{} {} {} {} '.format( self.eduYear,self.stage,self.stageClass, self.oneClass) # so, classroom will be as (2001 KG KG1 A) class Enrollment(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) oneClass = models.ForeignKey(OneClass, on_delete=models.CASCADE) EduYear = models.CharField(max_length=9) #Description of education year # other extra fields I provided a data entry screen for the user to save student information, where classRoom information is entered using Django administration (because it almost not changing). The user can link saved student with any classroom by using Enrollment class at any time. that's means some student can be saved without classroom (this is a business requirement), enrolled them to class room could be done later. … -
Python Django: Generate table from SQLite to code in models.py bug
I create table in SQLite and generate code to models.py by cmd: python manage.py inspect > home/models.py, but I can't runserver and have this bug. Please help me!!!!!!!!!!!!!!! PS E:\Code\Python\demoWeb> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 851, in exec_module File "<frozen importlib._bootstrap_external>", line 988, in get_code File "<frozen importlib._bootstrap_external>", line 918, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed ValueError: source code string cannot contain null bytes -
Django sending gmail failed
I've configured gmail in settings file as following: #gmail_send/settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'yoorusername@gmail.com' EMAIL_HOST_PASSWORD = 'key' #past the key or password app here EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'default from email' I've turned on less secure app access from google but it's still not working Here's the error : SMTPSenderRefused at /register (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError n6sm1130142pgm.79 - gsmtp', '"default from email"') Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 3.2.3 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError n6sm1130142pgm.79 - gsmtp', '"default from email"') -
Insert boolean field to database in django
I have this model class category(models.Model): name = models.BooleanField(default=True) def __str__(self): return self.name When I try to insert a new category in python manage.py shell with these commands: (InteractiveConsole) >>> from application.models import category >>> c = category(name='Integrity') >>> c.save() I get this following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 754, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 792, in save_base force_update, using, update_fields, File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 935, in _do_insert using=using, raw=raw, File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1254, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 1396, in execute_sql for sql, params in self.as_sql(): File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 1341, in as_sql for obj in self.query.objs File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 1341, in <listcomp> for obj in self.query.objs File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 1340, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 1281, in prepare_value value = field.get_db_prep_save(value, connection=self.connection) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\__init__.py", line 823, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\__init__.py", line 818, in get_db_prep_value value = self.get_prep_value(value) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\__init__.py", line 967, in get_prep_value return self.to_python(value) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\__init__.py", line 960, in to_python params={'value': … -
Django connecting to a Redis Server Hosted on Amazon EC2
I am new to Redis. I could setup the Redis server on Amazon Ec2 server and it works locally. Now, I am trying to connect to this server through my Django application but I am unable to do so. I have followed this query and updated my conf.d file to accept remote connections. I have also setup a password for redis server. My settings.py file for CHANNEL_LAYERS in Django looks like this: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { #"hosts": [("localhost", 6379)], "hosts": ["ec2-3-134-77-111.us-east-2.compute.amazonaws.com:6379"], }, }, } I think I am not setting up the CHANNEL_LAYERS correctly. Could someone please point me in the correct direction. Thanks for your time in advance. -
How can I use GET and POST on the same form in Django
I have a project wiki using Django and python from CS50W and stuck at a point where i have to check for the title is it exist or not and if it exists i will give message and option to change the title or edit it, now this part is using GET method and if the topic does not exist it will set focus to textarea and user can ad information about the title and save it to new file now this uses methot=POST. If I write the following code my check works createNewPage.html <div class="form-group" style="margin-right: 20%"> <form id="newTitle" action="{% url 'save' %}" method="GET"> {% csrf_token %} {% block newTitle %} <label>{{ newTitle_form.title.label }}</label> {{ newTitle_form.title }} {% endblock %} </form> {% if messages %} <div id="messageDiv" class="alert alert-info" role="alert"> {% for message in messages %} {{ message }} {% endfor %} </div> {% endif %} {% if messages %} <div class="h1 flex-container btn-save-placement" style="height: 0px; padding-top: 0px; margin-right: 0%"> <div> <a role="button" id="changeTopic" class="btn btn-outline-dark" href="{% url 'new_topic' %}">Change</a> <a role="button" class="btn btn-outline-dark" href="{% url 'edit' pagetitle %}">Edit</a> </div> </div> {% endif %} </div> <div class="form-group" style="margin-right: 20%; margin-top: 25px"> {% block textArea %} <label>{{ newText_form.text.label }}</label> {{ … -
How to run django function when a payment is made using client side integration
I want to set change a property of a object when a user pays via paypal (client-side integration). An example of changing proprerty can be: def paid(id): data = User.objects.get(id=id) data.paid=True data.save() I can create a view and do this by redirecting after the user pays. But i think it will be insecure cause the user can go to that url anytime he want and still the changes will be made. So I want to change these things only when the user pays without redirecting or letting the user know about it. How to do this? Thank you:) -
I have problem reset password in django . My error is 'availabe Apps' key error
Firstly I call 'from django.contrib.auth import views as auth_views'. After that I have set the 'path('reset_password/',auth_views.PasswordResetView.as_view(),name='reset_password'),' url. When i run the url the key error raised. Request Method: GET Request URL: http://127.0.0.1:8000/user/reset_password/ Django Version: 3.1 Exception Type: KeyError Exception Value: 'available_apps' Exception Location: C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\context.py, line 83, in getitem Python Executable: C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.3 Python Path: ['F:\12.05.2021\Project\Music_E-com', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\Syed Mithu\AppData\Local\Programs\Python\Python38', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\win32', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\win32\lib', 'C:\Users\Syed ' 'Mithu\AppData\Local\Programs\Python\Python38\lib\site-packages\Pythonwin'] Server time: Thu, 20 May 2021 06:51:41 +0000 -
How to check if an object corresponding to a foreign key exists or not?
I need help to evaluate weather i am doing it right or not, the scenario is an 3rd party application is sending an webhook request after a successful payment but the problem is that sometimes this application may send the same notification more than once.so it is recommended to ensure that implementation of the webhook is idempotent.so steps that i am implementing for this are if signature is correct (assume it is corect),Find orders record in the database using orderId in the request params. Please note: orderId in request params is payment_gateway_order_identifier in orders table. if txStatus = 'SUCCESS' AND haven't already processed COLLECTION payment for this same order, Create payments record. 201 response with nothing in the response body. else 201 response with nothing in the response body. else 422 response with {message: "Signature is incorrect"} in response body views.py @api_view(['POST']) def cashfree_request(request): if request.method == 'POST': data=request.POST.dict() payment_gateway_order_identifier= data['orderId'] amount = data['orderAmount'] transaction_status = data['txStatus'] signature = data['signature'] if(computedsignature==signature): #assume it to be true order=Orders.objects.get( payment_gateway_order_identifier=payment_gateway_order_identifier) if transaction_status=='SUCCESS': try: payment= Payments.objects.get(orders=order) return Response({"Payment":"Done"},status=status.HTTP_200_OK) except (Payments.DoesNotExist): payment = Payments(orders=order,amount=amount,datetime=datetime) payment.save() return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY) models.py class Orders(models.Model): id= models.AutoField(primary_key=True) amount = models.DecimalField(max_digits=19, decimal_places=4) payment_gateway_order_identifier = models.UUIDField( primary_key=False,default=uuid.uuid4,editable=False,unique=True) sussessfull … -
Why js can't be loaded but css can be normally loaded
I put jquery-ui.min.js and jquery-ui.min.css in same folder. in HTML: However, jquery-ui.min.js can't be loaded but css is OK even I change the name of jquery-ui.min.js or change folder but all fails Why css is OK but js fails??? How can I solve it? -
comment serialize in Django rest api
I want my comment serializer response to be like this - [ { "id": 50, "comment": "50Reply1", "timestamp": "2021-05-20 00:26:41", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": { "id": 51, "comment": "50Reply2", "timestamp": "2021-05-20 00:26:46", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": 50 }, { "id": 52, "comment": "50Reply3", "timestamp": "2021-05-20 00:26:51", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": 50 }, }] But instead I am getting something like this - [ { "id": 52, "comment": "50Reply2", "timestamp": "2021-05-20 00:26:46", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": 50 }, { "id": 51, "comment": "50Reply1", "timestamp": "2021-05-20 00:26:41", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": 50 }, { "id": 50, "comment": "Reply3", "timestamp": "2021-05-20 00:24:51", "user": { "hnid": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c", "username": "Sunasuns #GD6GXAJ4", "profile_img": "/media/Bay-Morning-Sea-Clouds-Beach-House-Wallpaper-1162x768.jpg", "full_name": "Suna suns" }, "reply_comment": null },] Here is my model.py class Comment(models.Model): post = models.ForeignKey(Posts, related_name='comments', on_delete=models.CASCADE) user = models.ForeignKey(HNUsers, related_name='comments', on_delete=models.CASCADE) comment = models.TextField("Comment", blank=True, null=True) timestamp = models.DateTimeField("Timestamp", blank=True, null=True, auto_now_add=True) reply_comment = models.ForeignKey('self', related_name='replies', on_delete=models.CASCADE, blank=True, null=True) class … -
How to dynamically add an If Else statement in Python?
Currently I had developed a script that will read incoming/latest email and filter the email based on certain criteria such as email subject and text. When user select subject or text, they are able to choose which condition they want to filter the email (Equals, Does not contain etc). My Problem I have a demo website that will let user to add different conditions to filter the email. But now my script can only handle one condition and execute at one time . How can I make my script to detect there are multiple condition and filter the email based on the multiple rules ? Im using Django to do my website My previous script: After user click on OK, the script in view.py will directly be executed and it will parse the email based on the current condition only What I trying to achieve: I had modify my html template and it will continuously letting user to add few conditions rather than just execute one condition only. Example: When user choose the parameter etc and click OK and new row will be store and the script will parse the email based on how many rules that user want to … -
django - Dynamic upload path including month and year not working
I want to upload file with dynamic path i.e. YEAR/MONTH//FILES To achieve this i am using below code def user_directory_path(instance, filename): return '%Y/%B/{0}/files/{1}'.format(instance.retailer.retailer_id, filename) class FileUpload(models.Model): file = models.FileField(upload_to=user_directory_path) car = models.ForeignKey(CarMaster, on_delete=models.CASCADE, default=None) class CarMaster(models.Model): user = models.ForeignKey(User,default=None,on_delete=models.CASCADE) car_id = models.PositiveIntegerField(unique=True) car_name = models.CharField(max_length=1000) Folder structure getting created is as below media\%Y\%B\100000\files Here %Y and %B should be replaced by Year and Month name which is not happening. Is there a way we can achieve this. -
IDW(Inverse Distance Weighted) Interpolation in openlayers 6.4.3
I have a django3.1 web application with map using ol6 in which I want to show IDW. I have generated an idw image using python & added to map as an image layer but it does not overlay in accurate point positions. So I am looking for a method or technique for overlaying idw as a vector/raster/anything which is correct using ol 6. -
Django urls Datatype
For passing datetime in django urls which datatype to use in place of datettime as datetime isn't working ('deletetask/datetime:id',deletetask,name="deletetask") -
AWS S3 static file access works on local but not production
I have setup a AWS S3 bucket for both my static and media files but it currently only works on local host but not when I try on gunicorn or when I deploy to Heroku. When I take a look at the network information on local host I can see the network is attempting to access the files from "https://mybucketname.s3.amazonaws.com/static/image.png". However, when I try this on gunicorn or heroku it is attempting to serve the files from "https://none.s3.amazonaws.com/static/image.png". I am unsure why it is using 'none' instead of 'mybucketname' and my settings are below. settings.py from pathlib import Path import os import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['xxxx.herokuapp.com', '127.0.0.1',] INSTALLED_APPS = [ xxx, 'storages', ] MIDDLEWARE = [ xxx, 'whitenoise.middleware.WhiteNoiseMiddleware', ] AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_S3_REGION_NAME = "us-east-1" AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'src.storage_backends.MediaStorage' # Configure Django App for Heroku. django_heroku.settings(locals(), staticfiles=False) If it's relevant my AWS s3 settings are set for '*' allowed hosts, public access is enabled for everything and my IAM account … -
Performance - SPRING VS DJANGO VS ASP.NET MVC
I want to build a personal Web Project which involves huge databases. Thus I want to have the best Performance from the framework. So which Framework is the best for the purpose. I have tried Django but I need an insight because Java and C# have Data Types which can help reduce the memory . NOTE : I know all 3 languages. OVERALL REVIEW of all the 3 will be appreciated. Also what is the difference between Spring and Spring - Boot and Spring - MVC