Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Avoiding DateTime "auto_now" field to be changed when nothing actually has changed
What is the most efficient way to make sure my updated_at field- which has the auto_now param not to be changed when the object remains the same on PATCH request for example? -
How to use vuei18n-po?
i can't find a tutorial how to use package vuei18n-po in vue main.ts. Yts documentation is small, and not well descriped. https://www.npmjs.com/package/vuei18n-po. I have never use something like this inside app initiation in vue, so it is realy hard. it is my code: import { createApp } from "vue"; import App from "./App.vue"; import router from "./router"; import "jquery"; import "bootstrap"; import "bootstrap/dist/css/bootstrap.min.css"; import vuei18nPo from "vuei18n-po"; const app = createApp(App); await vuei18nPo({ po: ["django.po", "../../backend/locale/pl/LC_MESSAGES/django.po"], messagesFile: "generated/allInOne.json", messagesDir: "generated", }); app.use(router); app.mount("#app"); In my code i did not use plug it in option, because i wanted to generate it first. -
django.core.exceptions.ImproperlyConfigured: The module in NAME could not be imported: validators.NumberValidators
is there anyone who knows how to solve this error. I was trying add custom password validators in AUTH_PASSWORD_VALIDATORS. i got this following error. django.core.exceptions.ImproperlyConfigured: The module in NAME could not be imported: accounts.validators.NumberValidators. Check your AUTH_PASSWORD_VALIDATORS setting. here's what i did to add the custom NumberValidators AUTH_PASSWORD_VALIDATORS = [{ 'NAME': 'accounts.validators.NumberValidators', }, ] -
Adding CDN link to static folder of django
How can I add the cdn link for chart.js in html page to static folder so that I wont be dependent on cloudflare and I can cache it in my CloudFront distribution as well. can anyone help me on that. -
model object not saved in celery task
im trying to create Alarm object in celery task. but after calling task method, objects created in celery task is not saved. from celery import shared_task from alarms.models import Alarm from games.models import Participation @shared_task def create_alarms(game_id): participations = Participation.objects.filter(game=game_id) for participation in participations: alarm, created = Alarm.objects.get_or_create( game=participation.game, user=participation.user, valid_until=participation.game.start_datetime ) if not created: alarm.set_unsent() project/games/tasks.py from django.dispatch import receiver from django.db.models.signals import post_save, post_delete from .models import Participation, Game from .tasks import create_alarms, delete_alarm @receiver(post_save, sender=Participation) def _post_save_receiver(sender, instance, created, **kwargs): if created: game = instance.game game.increase_player() if game.is_fulfilled(): create_alarms.delay(game.id) project/games/signals.py - receiver method calling task method from __future__ import absolute_import unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.dev') app = Celery('project', broker='amqp://miti:miti@localhost/', include=['games.tasks']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() project/project/celery.py [2022-10-27 16:12:11,543: INFO/MainProcess] Task games.tasks.create_alarms[b8782685-3fd3-4a39-8d58-8fdb9df1871e] received celery log telling task is received by celery worker please help me i want to save created object in celery task is applied into django db(currently using mysql) -
How to add proxy api request in react using nodejs? (using one general function only instead of a seperate func for each api)
I am hitting all of my django apis directly from react, what i want to do is to add a proxy nodejs layer so to hide the actual api. Our react application is haivng ssr so we are already running a nodejs server. As we are already having a lot of apis, is there a way by which i can create a single function to hide all the api instead of create proxy apis for all django apis one-by-one? -
form.label is not showing in django
this is my code and I try to show the label but it is not displaying this is my form file forms.py class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = {'value': 'Place your vote', 'body': 'Add a comment with your vote'} def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) this is my views file and the function for this form views.py def project(request, pk): projectObj = Project.objects.get(id=pk) form = ReviewForm() context = { 'project': projectObj, 'form': form } return render(request, 'projects/single-project.html', context) this is the model for the review section models.py class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote') ) owner = models.ForeignKey(Profile, on_delete = models.CASCADE, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default = uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: # every user can only have single comment on each project unique_together = [['owner', 'project']] def __str__(self): return self.value and the html file to display the form html file <form class="form" action="{% url 'project' project.owner.id %}" method="POST"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#textarea">{{field.label}}</label> {{field}} </div> {% endfor … -
Python - Django Rest Framework - Count total row from tables in the database with a single call
I just switched to python and Django-rest-framework from java spring-boot, and I have a question below Let's say I have some tables: class table1(CommonModel): class table2(CommonModel): class table3(CommonModel): class table4(CommonModel): .... And I have an API to return total rows in these tables: { "table1": 10, "table2": 10, "table3": 10, "table4": 10, .... } My code so far is to count the total on each table with Model.objects.all().count() or Model.objects.filter(some_filter).count() And the problem here is obvious, if I have 10 tables, I will have to call 10 count query, which I think is not a good way to go because it spams too many queries to the database. I want to limit the number of the query to the database. The best would be to return all rows count for each table in a single query. I have looking for a solution like creating a custom query or so but nothing seems to solve my issue. Edit: I'm using Postgresql database -
django set initial value in form
class UserEditFormView(FormView): template_name = "edit.html" form_class = UserEditForm def get_initial(self): return {'nickname': self.request.user.nickname} class UserEditForm(forms.Form): nickname = forms.CharField(required=False, max_length=120) I tried to set initial value(placeholder) of the form but it's not working. The input field on the page is empty. -
i have created models and my views function to add the attendance of employee. But data data is not saving in database. and no error comes up
class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = '__all__' These are he models and please let me know if nay changes are required : Models: class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) eid = models.IntegerField(primary_key=True) salary = models.IntegerField() gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1) contactno = models.CharField(max_length=10) email = models.CharField(max_length=30) country = models.CharField(max_length=30) city = models.CharField(max_length=20) pincode = models.IntegerField() address = models.CharField(max_length=60) def __str__(self): return self.user.first_name + ' ' + self.user.last_name class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1) attendancedate = models.DateField() in_time = models.TimeField() out_time = models.TimeField() description = models.TextField() def __str__(self): return str(self.employee) These is the Views . Please let me know if any changes is required @csrf_exempt def addattendance(request): form = AttendanceForm() emp_list = Employee.objects.all() if request.method == 'POST': form = AttendanceForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('employee/detail_attendance') return render(request, 'employee/addattendance.html', {'form': form, 'emp_list': emp_list}) I tried everything but i dont know why data is not saving into database . also models are created fine and main thing is there is not error coming up. -
DFR Serializers vs. Forms, and handling of ImageField() as optional field, problem not working
My target is how to make ImageField() as optional in case user does not want to submit an image. When I use django Forms, then the ImageField() will work fine where the field will be treated as optional. Whereas, when I use Django "class FleetSerializer(serializers.ModelSerializer):" then the ImageField() will not be treated as optional. Any solution for this huge problem of mine? Thanks a million. Here is the complete code: MODELS, SERIALIZERS, VIEWS where my objective is to have REST API with field 'licRegImage' as optional. This code is aimed towards Flutter/Dart frontend why I prefer to use SERIALIZERS. For over two weeks now I have not been able to find a solution. I suspect it may be related to compatibility issues, or worst bugs. From Requirements.txt: Django==3.2.16 djangorestframework==3.13.1 djongo==1.3.6 pymongo==3.12.1 djangorestframework==3.13.1 Pillow==9.2.0 etc., etc. MODELS: from djongo import models class Fleet(models.Model): usrRegId = models.CharField(max_length=28) fleetId = models.CharField(max_length=13) vinNr = models.CharField(max_length=35) licRegNr = models.CharField(max_length=35) licRegExpire = models.CharField(max_length=10) licRegImage = models.ImageField(null=True, blank=True, upload_to='astfleet/imglicReg/', default = 'sys_global/images/no_image.png') objects = models.DjongoManager() class Meta: db_table = "ast_fleet" def __str__(self): return self.usrRegId SERIALIZERS: class FleetRegistrationSerializer(serializers.ModelSerializer): class Meta: model = Fleet fields =( 'usrRegId', 'fleetId', 'vinNr', 'licRegNr', 'licRegExpire', 'licRegImage', ) extra_kwargs = { 'usrRegId':{'write_only':True}, 'fleetId':{'write_only':True}, 'licRegImage':{'required':False}, … -
Python asyncio link body and response from it in aiohttp asyncio
I have async requests, i send 100 requests and get response from them I send body to get resonse, the problem is i caanot join request body with response, sometime there is no response i collect requests into a list def __gaterTasks(self, session, total_schets): _tasks = [] _updates = [] for schet in total_schets: _payload_objct = PayloadParams.objects.using('analytic_db').get(payload=schet['payload']) _payload_objct.status = True _updates.append(_payload_objct) _tasks.append( session.get(url=self.url, body=schet['payload']) ) PayloadParams.objects.using('analytic_db').bulk_update(_updates, ['status']) return _tasks i need to link body=schet['payload'] with the response with i get from it the function with runs async def get_data(self, total_schets): async with aiohttp.ClientSession(trust_env=True, auth=aiohttp.BasicAuth()) as session: tasks = self.__gaterTasks(session=session, total_schets=total_schets) responses = await asyncio.gather(*tasks) for each in responses: _each = await each.json() -
Django - if condition always return True
I have a condition which call an update function if is_approved= True @api_view(['POST']) @permission_classes([IsStaff]) def update_company_info(request): request_qs = CompanyUpdateRequests.objects.filter(id=request.data["request_id"],is_approved=None) serializer = CompanyUpdateRequestSerializer(request_qs[0], data=request.data, partial=True) approved = request.data['is_approved'] if serializer.is_valid(): if approved: print(request.data['is_approved']) update_info(request_qs[0].company, request_qs[0]) serializer.save() No matter the boolean value the if approved: gets executed. Any suggestions? -
How do I activate a django view as a scheduled task on pythonanywhere?
I am about to deploy my Django app to PythonAnywhere. I have a view (below) that cleans up all guest accounts older than a time period. I can activate this by manually going to the url (/cleanup/), however it would be nice to schedule this automatically. I see PythonAnywhere handles scheduled tasks that ask for a path to a .py file. Is it possible to separate this view into it's own .py file? MAX_GUEST_ACCOUNT_DAYS = 30 def cleanup(request): """ Deletes all guest user accounts and their media if older than MAX_GUEST_ACCOUNT_DAYS """ # Get all guest accounts created before the limit expired_guests = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)) for guest in expired_guests: guest.delete() print(f"Deleted guest account(s) older than {MAX_GUEST_ACCOUNT_DAYS} days.") return HttpResponse(f"Deleted guest account(s) older than {MAX_GUEST_ACCOUNT_DAYS} days.") -
how to click button second time after 1st time click using JS
here my code: function report(){ setTimeout(function () { var mehran = new URL('http://example.com'); window.open(mehran); /* alert("h") */ }, 5000); } <span><button type="submit" id="reportclick" style="color:white; background-color:coral; border: 1 px sloid black; width:100px; margin: auto;" onclick="report()">Get Report</button></span> I want to open open this link automatically after 5 seconds when i click on button first time. -
python/django database connection issue
Database settings DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE', "mysql"), 'NAME': os.environ.get('DB_NAME', "django_db"), 'USER': os.environ.get('DB_USER', "root"), 'PASSWORD': os.environ.get('DB_PASS', "123456798"), 'HOST': os.environ.get('DB_HOST', "localhost"), 'PORT': os.environ.get('DB_PORT'), } } error django.core.exceptions.ImproperlyConfigured: 'mysql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Connecting with mysql to generate migration but facing issue Its my first time and facing following above issue please guide. -
How to implement NGINX file storage and STORJ cloud?
Django media app + Nginx. And Storj cloud as content file cold storage. nginx.conf location /media { root /var/www/html/media;} I need to avoid to download file from storj, if this file already in /media. User requests mysite/file.mp4. Django download it from storj to /media and show to user. User requests mysite/file.mp4 second time. Nginx shows it from /media I have script for storj. session = boto3.session.Session() s3 = session.client(service_name="s3", aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, endpoint_url=URL) response = s3.download_file(BUCKET_NAME, OBJECT_NAME, FILE_NAME) Do I need to work with Django with this function or make it like system service and check events if Nginx has file in /media? -
VS Code does not see virtual environment variables in .env file when running django
I am trying to set up a postgres connection and use virtual environment variables for the first time. I created a .env file and placed it in my settings folder but my database variable is missing each time I try to use manage.py runserver. Is there a way to get this to run on windows? Moving the .env file next to my virtual environment did not work either. I also tried typing set DATABASE_URL='postgres://username:password@localhost:5432/authors-live' did not work either. Folder Structure: MASTERDJANGOWITHDOCKER -env (virtual environment folder) -authors-src --manage.py --.env --authors_api ---settings ----base.py ----.env (both .env files are exactly the same) settings/base.py import environ env = environ.Env() ROOT_DIR = Path(__file__).resolve().parent.parent.parent # need three to get to manage.py level # points django to where the apps are stored APPS_DIR = ROOT_DIR / 'core_apps' BASE_DIR = Path(__file__).resolve().parent.parent DATABASES = { 'default': env.db('DATABASE_URL') } .env file DATABASE_URL='postgres://username:password@localhost:5432/authors-live' DJANGO_SECRET_KEY="django-insecure" error message ... File "C:\Python39\lib\os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DATABASE_URL' ... File "C:\Users\...\authors-haven-api\authors-src\env\lib\site-packages\environ\environ.py", line 371, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable -
Non persisting data in postgres on docker restart
docker-compose.yml ` version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres volumes: - db_data:/var/lib/postgresql/data/ env_file: - ./.env.dev volumes: db_data: inspecting the volume dockerized-newsapp_db_data { "CreatedAt": "2022-10-27T10:13:21+05:30", "Driver": "local", "Labels": { "com.docker.compose.project": "dockerized-newsapp", "com.docker.compose.version": "2.12.0", "com.docker.compose.volume": "db_data" }, "Mountpoint": "/var/lib/docker/volumes/dockerized-newsapp_db_data/_data", "Name": "dockerized-newsapp_db_data", "Options": null, "Scope": "local", "CreatedTime": 1666845801000, "Containers": { "ca1449a281d4be86ef9044a4613d27fa4c4debf5806bf0c61d76287ef7b7ae5b": { "Name": "dockerized-newsapp-db-1", "Destination": "/var/lib/postgresql/data" } } } ` Every time I'm restarting the container the database is removed. Commands used: docker compose start docker compose stop Any idea, what might be causing this problem? -
Django Browser back button issue after logout not able to login again. It stay on Logout page only
I am trying to integrate Azure AD with Django. When I login with Azure ad at first time it working fine, than I logout and click Browser Back button from Logout page it is stay on logout page but After that when I try to login from logout page I'm not able to login again. Index content doesn’t load, content remains same as logout page. Also I'm using PWA for this. Index content will load. -
Double linked list in Django models
I am trying to create a music player using Django. on the site I should have playlists with music tracks. I need to create two models: composition and playlist. I have already created the Composition class: class Composition(models.Model): title = models.CharField(max_length=500) artist = models.CharField(max_length=500) playlist = models.ForeignKey('PlayList', on_delete=models.SET_NULL, null=True, blank=False) time_length = models.DecimalField(blank=True, max_digits=20, decimal_places=2) audio_file = models.FileField(validators=[validate_is_audio]) cover_image = models.ImageField() Now I need to create a playlist model class PlayList(models.Model, LinkedList):, which should, by assignment, be inherited from my base class linked_list, realizing a doubly linked list. This class has methods like init(self, first_item=None), append_left(self, item), append_right(self, item), remove(self, item), insert(self, previous, item), etc. On the site, I will have to have several playlists with a choice. This is my first time using django, so I don't know how to implement it. I haven't tried creating this model yet because I don't know where to start. -
How to use schemas in Django using MSSQL?
I don't have 50 reputations to comment on this answer. I want to ask question how can I find the path for mssql\introspection.py as I can't the path in my Django environment. By referring to this question, I have the exact issue which is I need to inspectdb all the tables including tables with custom schemas. I assume this answer will fix my issues OR if anyone have any other solution, I appreciate if you can share with me. -
I have some errors in python django
this is my errors I try but isn`t work :) -
Table inside Django model for Order in E-Commerce site
I am developing a Grocery Store Website using Django for the backend. I have a model named "Order" which contains fields Customer name, date, address, mobile no, payment method, status, etc, and most important Order List (This should be in table format and contains multiple fields product name, price, quantity). I have a products table and this product name, price will be from that products table. I want structure as Customer Name: Mobile No. Date: Address: Order list : | Product Name| Price | Quantity | |:----------- |:-----:| --------:| | Product 1 | 10.20 | 2 | | Product 2 | 15.20 | 5 | | Product 3 | 17.20 | 7 | Payment Method: Payment Status: Order Status: Please help me to get the possible solution to this problem. -
For loop in django template returning same id for specific column
I am trying to write an admin panel where videos can be edited, deleted and reviewed using Django. While the loop I have set up runs smoothly, it only accepts the first value as the id value in the video deletion function. I'm pretty sure I closed the for loop in the right place, I guess there's nothing wrong with it. **This is my template page.** {% extends 'dashboard/main.html' %} {% load static %} {% block content %} <div class="col-sm-12"> <div class="card"> <div class="card-header"> <h5>Edit / Show Videos</h5> </div> <div class="card-block"> <form method="get" action="{% url 'videos' %}"> <div id="zero-configuration_filter" class="dataTables_filter"> <label>Search:<input type="search" class="form-control form-control-sm" placeholder="Type video ID or Title" name="q" aria-controls="zero-configuration"></label> </div> <div class="table-responsive"> <table id="responsive-table-model" class="display table dt-responsive nowrap" style="width:100%"> <thead> <tr> <th>Video ID</th> <th>Video Title</th> <th>Video Create Date</th> <th>Video Status</th> <th>Video From</th> <th>Video IMG</th> <th>Video Duration</th> <th>Video Slug</th> <th> Action </th> </tr> </thead> <tbody> {% autoescape off %} {% for video in videos reversed %} <tr> <td class="tabledit-view-mode" style="cursor: pointer;"><span class="tabledit-span"> {{ video.id }}</span></td> <td>{{ video.video_title|truncatechars:25 }}</td> <td>{{ video.video_create_date }}</td> <td>{{ video.video_status }}</td> <td>{{ video.video_from }}</td> <td> <div class="col-lg-8 col-md-6 col-sm-6"> <img src="{{ video.video_img}}" alt="img" class="img-fluid animation-toggle animated" data-animate="jackInTheBox"> </div></td> <td>{{ video.video_duration }}</td> <td>{{ video.video_slug|truncatechars:25 }}</td> <td> <ul …