Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sending csrftoken using fetch api from react to django
I am trying to send the csrf token i genenrated here is the csrftoken generation const [cr , setCR] = useState('') const getcsrf = async () => { await fetch('http://localhost:8000/auth/gettoken') .then( async res => await res.json()).then(data =>{ setCR( data.crsftoken) console.log(cr) }) } useEffect( () => { getcsrf() },[] ) after i have obtained the token i try to send it using fetch const handlelogin = async () => { if(cr !== ''){ console.log(cr) await fetch('http://localhost:8000/auth/login', {method : "POST", credentials: "include" , headers: { "Content-Type": "application/json", "X-CSRFToken" : cr }, body : { "username" : username, "password" : password } } ).catch(err => console.log(err))}else{console.log('cr is null')} } the csrf token is generated i can see it when i console.logged it but the fetch brings back a 403 forbidden error Forbidden (CSRF token from the 'X-Csrftoken' HTTP header incorrect.): /auth/login [09/Nov/2023 05:49:59] "POST /auth/login HTTP/1.1" 403 2553 i am expecting it to post to the url i gave it. what is wrong with it? -
Add user to group to specific database does not work
I am struggling to make the following code works for me. user = User.objects.using(data[‘db_name’]).get(pk=1) group = Group.objects.using(data[‘db_name’]).get(pk=2) user.groups.add(group) I can see that Django creates one record to auth_user_groups in the default database but not in the data[‘db_name’]) database. Interestingly, user and group objects are coming from data[‘db_name’] database. Can anyone advise me how to add new record to data[‘db_name’] database successfully? -
Detach Python Selenium from Gunicorn
I'm fairly new to gunicorn, Is there any possible way that allow me to run selenium browser outside of gunicorn enviroment? For example, I would like to update my Django application without interfering with a running selenium driver in the background. from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options def selenium(request): options = Options() options.add_argument("--headless=new") options.add_experimental_option("detach", True) chrome_path = "chrome/driver/chromedriver" driver = webdriver.Chrome(service=Service(executable_path=chrome_path) ,options=options) driver.get('https://example.com/') return HttpResponse(status=200) Selenium driver will stay active until, I restart gunicorn to update my code. Is there any other way to do so without driver shutting down? I've tried to detach selenium. and I've though that will be enough to allow driver to be detached from gunicorn. But that didn't work out. I'm updating my code through git and using "systemctl restart gunicorn" to allow it to update. -
When deploying django app, manage.py cant find views.py
I am trying to deploy a simple Django app that makes a user login and then serves a "hello world" on success. I use white noise for static. The web service builds correctly, but when deploying, I am getting the error module views.py can not be found. I can not understand why though as all paths seem to be correct. I use two different settings files; one for local development utilizing pip, and one for production using Gunicorn and a build.sh script (as per Render.com documentation). These are my server logs for deployment: Nov 8 11:05:22 PM Traceback (most recent call last): Nov 8 11:05:22 PM File "manage.py", line 23, in <module> Nov 8 11:05:22 PM main() Nov 8 11:05:22 PM File "manage.py", line 19, in main Nov 8 11:05:22 PM execute_from_command_line(sys.argv) Nov 8 11:05:22 PM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line Nov 8 11:05:22 PM utility.execute() Nov 8 11:05:22 PM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute Nov 8 11:05:22 PM self.fetch_command(subcommand).run_from_argv(self.argv) Nov 8 11:05:22 PM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv Nov 8 11:05:22 PM self.execute(*args, **cmd_options) Nov 8 11:05:22 PM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute Nov 8 11:05:22 PM output = self.handle(*args, **options) Nov 8 11:05:22 PM … -
Many to Many relation between two databases Django
I am building a separate Django project to handle a chat system, I already have a different Django project for everything else (user login info and serves API that does not relate to chat). In this chat project, it has a model class ChatRoom(models.Model): rmid = models.BigAutoField(primary_key=True) name = models.CharField(max_length=256) people = models.ManyToManyField(to=User, blank=True) timestamp = models.DateTimeField(auto_now_add=True) And a database router: class UserAuthRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'auth': return 'database_with_django_auth_models' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'auth': return 'database_with_django_auth_models' return None This allows me to use the same user login info from the main project since I have connected the database in settings. When I try to access ChatRoom model, I believe because the many-to-many field is relating to User model in the Auth lib/module, it causes this error as it is routed to use the other database: Django.db.utils.ProgrammingError: (1146, "Table 'database_with_django_auth_models.apps_chat_chatroom_people' doesn't exist") But the apps_chat_chatroom_people datatable is in the database that contains the ChatRoom schema, (i.e. the second database that is going to be used for the chat system) What is the proper way to handle this? I want to be able to use the same login credentials. -
how to create a multiple ForeignKey fields in a view create and save to database
First of all, I appreciate your help and time I would like to save all the 'equipamento' fields in the database instead of just one! When I save the form, it doesn't give any errors, but looking in the django admin, it is only saving one equipment field and not 2 or 3, because when I click on the green button (success) in the create view it generates 2 new fields to choose from. Moldel admin from django.contrib import admin from .models import Saida # Register your models here. admin.site.register(Saida) Moldel SAIDA # flake8: noqa from django.db import models from funcionario.models import Funcionario from estoque.models import Estoque class Saida(models.Model): funcionario = models.ForeignKey(Funcionario, verbose_name='Funcionário', on_delete=models.SET_NULL,null=True) data = models.DateTimeField(auto_now_add=True) observacao = models.CharField(max_length=500, blank=True, null=True, verbose_name='Observações') equipamento = models.ForeignKey(Estoque, verbose_name='Equipamento', on_delete=models.SET_NULL,null=True) quantidade_saida = models.PositiveIntegerField() def __str__(self): return f'Retirada N. {self.pk}' class Meta: verbose_name = 'Saida estoque' verbose_name_plural = 'Saida estoque' SAIDA VIEW CREATE def create(request): form_action = reverse('saida:create') if request.method == 'POST': form = saidaForm(request.POST, request.FILES) context = { 'form': form, 'form_action': form_action, } if form.is_valid(): saida = form saida.save() return redirect('saida:lista') return render( request, 'saida/create.html', context ) context = { 'form': saidaForm(), 'form_action': form_action, } return render( request, 'saida/create.html', context ) class … -
Problem communicating from celery container to redis
I'm Dockerizing my old project, but I came across this error: Traceback (most recent call last):File "/venv/lib/python3.10/site-packages/redis/connection.py", line 624, in connectsock = self.retry.call_with_retry(File "/venv/lib/python3.10/site-packages/redis/retry.py", line 46, in call_with_retryreturn do()File "/venv/lib/python3.10/site-packages/redis/connection.py", line 625, in <lambda>lambda: self._connect(), lambda error: self.disconnect(error)File "/venv/lib/python3.10/site-packages/redis/connection.py", line 690, in _connectraise errFile "/venv/lib/python3.10/site-packages/redis/connection.py", line 678, in _connectsock.connect(socket_address) During handling of the above exception ([Errno 99] Address not available), another exception occurred:File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 119, in reconnect_on_erroryieldFile "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 169, in _consume_fromself._pubsub.subscribe(key)File "/venv/lib/python3.10/site-packages/redis/client.py", line 1623, in subscriberet_val = self.execute_command("SUBSCRIBE", *new_channels.keys())File "/venv/lib/python3.10/site-packages/redis/client.py", line 1458, in execute_commandself.connection = self.connection_pool.get_connection(File "/venv/lib/python3.10/site-packages/redis/connection.py", line 1427, in get_connectionconnection.connect()File "/venv/lib/python3.10/site-packages/redis/connection.py", line 630, in connectraise ConnectionError(self._error_message(e)) During handling of the above exception (Error 99 connecting to localhost:6379. Address not available.), another exception occurred:File "/venv/lib/python3.10/site-packages/redis/connection.py", line 624, in connectsock = self.retry.call_with_retry(File "/venv/lib/python3.10/site-packages/redis/retry.py", line 46, in call_with_retryreturn do()File "/venv/lib/python3.10/site-packages/redis/connection.py", line 625, in <lambda>lambda: self._connect(), lambda error: self.disconnect(error)File "/venv/lib/python3.10/site-packages/redis/connection.py", line 690, in _connectraise errFile "/venv/lib/python3.10/site-packages/redis/connection.py", line 678, in _connectsock.connect(socket_address) During handling of the above exception ([Errno 99] Address not available), another exception occurred:File "/venv/lib/python3.10/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errorsyieldFile "/venv/lib/python3.10/site-packages/celery/app/base.py", line 787, in send_taskself.backend.on_task_call(P, task_id)File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 365, in on_task_callself.result_consumer.consume_from(task_id)File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 161, in consume_fromreturn self.start(task_id)File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 139, in startself._consume_from(initial_task_id)File "/venv/lib/python3.10/site-packages/celery/backends/redis.py", line 168, in _consume_fromwith self.reconnect_on_error():File "/usr/local/lib/python3.10/contextlib.py", line 153, in … -
read two excel headers using django pandas
In an excel table I need to read a budget using pandas. In the first two lines are the columns with the header and content that will be used as objects to save in the Sorder class. in the third line I have a new header for the product items. I can't get pandas to recognize this new header with the items. EXCEL Sorder client payment_cond interest_discount_table price_list sorder_date requested_delivery_date 21101197111186 30/49 MT90 TEC9 01/11/2023 08/11/2023 product gross_price quantity LAAAAA1054 2 2 LAAAAA0962 3 3 `if excel_file.name.endswith('.xls') or excel_file.name.endswith('.xlsx'): try: df = pd.read_excel(excel_file) print("first two lines:") print(df.iloc[:1]) print("third line onwards:") df = pd.read_excel(excel_file, header=2) base_row = df.iloc[2] print(df.iloc[2:]) for index, row in df.iloc[2:].iterrows(): product = row['product'] gross_price = row['gross_price'] qtd = row['qtd'] product_base = base_row['product'] gross_price_base = base_row['gross_price'] qtd_base = base_row['qtd'] print( f"product: {product}, gross_price: {gross_price}, qtd: {qtd}") ` -
Netbox Plugin Integration Issue
I have a plugin that works when I install it manually in my VM, but when I try to run the program ./upgrade.sh, I get the error: django.core.exceptions.ImproperlyConfigured: Unable to import plugin ...: Module not found. Check that the plugin module has been installed within the correct Python environment. How do I get this to work as it will work manually, but not with the ./upgrade.sh. I have verified the filenames, the documentation, and other items, but not finding an answer that helps. -
django admin add extra content
I am not an expert in Django admin( I have models: class Device(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, max_length=128) name = models.CharField(max_length=256) class DeviceHistory(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name='device_history') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) I want to add a table to the Django admin panel to the device's detailed page. There are two datetime inputs (start and end datetime). I need devide this time on hours, and check if exists one or more device history. This is how I've got the array of data: def get_device_history(device): date_first = timezone.now() - datetime.timedelta(hours=8) date_last = timezone.now() result = [] while date_first < date_last: date_end = date_first + datetime.timedelta(hours=1) histories_exists = DeviceHistory.objects.filter( device=device, created_at__gte=date_first, created_at__lte=date_end ).exists() result.append([str(date_first), str(date_end), histories_exists]) date_first = date_end And I've got something like this [['2023-11-08 10:03:00.577493+00:00', '2023-11-08 11:03:00.577493+00:00', False], ['2023-11-08 11:03:00.577493+00:00', '2023-11-08 12:03:00.577493+00:00', False], ['2023-11-08 12:03:00.577493+00:00', '2023-11-08 13:03:00.577493+00:00', False], ['2023-11-08 13:03:00.577493+00:00', '2023-11-08 14:03:00.577493+00:00', True], ['2023-11-08 14:03:00.577493+00:00', '2023-11-08 15:03:00.577493+00:00', True], ['2023-11-08 15:03:00.577493+00:00', '2023-11-08 16:03:00.577493+00:00', False], ['2023-11-08 16:03:00.577493+00:00', '2023-11-08 17:03:00.577493+00:00', True], ['2023-11-08 17:03:00.577493+00:00', '2023-11-08 18:03:00.577493+00:00', False]] How can I add this data to admin page like TabularInline table? And how can I add two datetime input for search in different range? Here is a picture of the functionality I need -
Django How to deploy image from database?
My project is the website which is moderated by a editor with admin laws (by the admin panel). He can add images for articles. Images are stored in the database. My problem is that I cant access images from the database in my website. They aren't displaying at all. Here is my structure of folders: folders in my project there are two apps: accounts and blog. For purpose of order i want to store images inside "blog" app in the folders like in the image. Here is my code: Models.py: class Reviews(models.Model): title = models.CharField(max_length=100) game_title = models.CharField(max_length=100) description = models.CharField(max_length=300) content = models.CharField(max_length=10000) game_rating = models.DecimalField(max_digits=2, decimal_places=1) game_user_rating = models.DecimalField(max_digits=2, decimal_places=1) date_of_publishing = models.DateField() def __str__(self): return f"{self.game_title}" class ReviewsMiniaturesImages(models.Model): miniature_image = models.ImageField(upload_to="blog/static/reviews_miniatures_images/") description = models.CharField(max_length=50) review = models.ForeignKey(Reviews, on_delete=models.CASCADE) Template: {% extends 'base.html' %} {% load static %} {% block content %} {% for review in reviews %} <div class="h-100 d-flex align-items-center justify-content-center"> <div class="card" style="width: 60rem;"> <img src="{% static review.reviewsminiaturesimages_set.get.miniature_image %}" class="card-img-top" alt="{{ review.reviewsminiaturesimages_set.get.description }}}}"> <div class="card-body"> <div class="row"> <div class="col"> <h5 class="card-title">{{review.game_title}}</h5> </div> <div class="col-7 d-flex justify-content-center"> <h4 class="card-title">{{review.title}}</h4> </div> <div class="col d-flex justify-content-end"> <h5 class="card-title">{{review.date_of_publishing}}</h5> </div> </div> <p class="card-text">{{review.description}}</p> <div class="row"> <div class="col"> <a href="{% … -
Django Migrations fails with postgres
I am trying to run a Django project with PostgreSQL but python manage.py migrate is failing with error - django.db.utils.ProgrammingError: relation "api_meeting" does not exist but there is not table with api_meeting on the other hand python manage.py migrate is working fine with sqlite database I tried - python manage.py migrate --fake but ended up with another error- relation "django_session" does not exist LINE 1: SELECT (1) AS "a" FROM "django_session" WHERE "django_sessio... my django version is 3.25 any ideas? Thanks -
Django pass user and product to current form
So i'm making a website that have some products and i want login user can leave a comment on that product but when submit a form (include rating from 1 to 5 star, text field), i can't set user and product therefor the form got error: {'user': ['This field is required.'], 'product': ['This field is required.']}. Because this method only for login user, is there a way to pass current user and the product get from product_id to the form. I think with the current user i can follow this question but what about the product. Any help would be appreciated! I already try to set it like below: @login_required(login_url='/login') def add_review(request, product_id): product = Product.objects.get(pk=product_id) nameForm = ProductNameForm() reviewForm = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) # print(form) if form.is_valid(): review = form.save(commit=False) print(review) review.user = request.user # Set the user review.product = product # Set the product review.save() product.average_rating = Review.objects.filter(product=product).aggregate(Avg('rating'))['rating__avg'] product.save() form = ReviewForm() print("Form is valid") else: print(form.errors) return render(request, 'add_review.html', {'form': nameForm, 'product': product, 'reviewForm': reviewForm}) Here is my review model: class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) rating = models.IntegerField() # You can add a rating field if needed … -
How to use ipdb debugger on Kubernetes environment
Traditionally I use ipdb as a debugger when I work on django. Here I want to use ipdb to debug so I put "import ipdb; ipdb.set_trace()" in my code. But on kubernetes I don't really know how to do it. I do kubectl attach pod-name -c container-name -i -t to access my django container, I see that the execution of the code stops on my breakpoint ok, BUT it continues and I get the error: "self.quitting: raise BdbQuit\nbdb.BdbQuit", the classic error that occurs when the code continues despite the breakpoint. It doesn't stop there, it continues straight on. How to properly use ipdb in a kubernetes env, any ideas ? Thank you ! -
Adminlte.io how to make the datable buttons work?
I wonder how to make the button works (copy CSV Excel PDF Print ..). See Data Table with default features {% extends 'adminlte/base.html' %} {% block title %}My App{% endblock %} {% block content %} <div class="card"> <div class="card-header"> <h3 class="card-title">DataTable with default features</h3> </div> <div class="card-body"> <div id="example1_wrapper" class="dataTables_wrapper dt-bootstrap4"><div class="row"><div class="col-sm-12 col-md-6"><div class="dt-buttons btn-group flex-wrap"> <button class="btn btn-secondary buttons-copy buttons-html5" tabindex="0" aria-controls="example1" type="button"><span>Copy</span></button> <button class="btn btn-secondary buttons-csv buttons-html5" tabindex="0" aria-controls="example1" type="button"><span>CSV</span></button> <button class="btn btn-secondary buttons-excel buttons-html5" tabindex="0" aria-controls="example1" type="button"><span>Excel</span></button> <button class="btn btn-secondary buttons-pdf buttons-html5" tabindex="0" aria-controls="example1" type="button"><span>PDF</span></button> <button class="btn btn-secondary buttons-print" tabindex="0" aria-controls="example1" type="button"><span>Print</span></button> <div class="btn-group"><button class="btn btn-secondary buttons-collection dropdown-toggle buttons-colvis" tabindex="0" aria-controls="example1" type="button" aria-haspopup="true"><span>Column visibility</span><span class="dt-down-arrow"></span></button></div> </div></div><div class="col-sm-12 col-md-6"><div id="example1_filter" class="dataTables_filter"><label>Search:<input type="search" class="form-control form-control-sm" placeholder="" aria-controls="example1"></label></div></div></div><div class="row"><div class="col-sm-12"><table id="example1" class="table table-bordered table-striped dataTable dtr-inline" aria-describedby="example1_info"> <thead> <tr><th class="sorting sorting_asc" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Rendering engine: activate to sort column descending">Rendering engine</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending">Browser</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Platform(s): activate to sort column ascending">Platform(s)</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Engine version: activate to sort column ascending">Engine version</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="CSS grade: activate to sort column ascending">CSS grade</th></tr> </thead> <tbody> <tr class="odd"> <td class="dtr-control sorting_1" … -
How to add Django ASGi in CPanel shared hosting?
I am using a shared hosting that provide cPanel, i am running a Django App with WSGI, and i want to use ASGI instead, to add the capability of real time stuff (like chat, ... etc). And i am not sure if that is possible with the shared hosting with cPanle option or not. I didn't try anything that may break the app. Thank you in advance. -
Cannot resolve keyword into field - Django shopping cart
Newby to Django here. I am trying to add a shopping cart to a simple project where users can pay for a single service. When a user provides basic info and clicks on 'checkout', I want to create the cart and add the only product they can pay for. It will always be one instance of the same product. I'm getting the following error when loading the cart page: Cannot resolve keyword 'product' into field. Choices are: id, quantity, user, user_id MODELS: class Product(models.Model) : name = models.CharField(max_length=100, unique=True) price = models.DecimalField(max_digits=8, decimal_places=2) description = models.TextField(null=True, blank=True, default='N/A') in_stock = models.BooleanField(default=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] db_table_comment = 'Product catalog' def __str__(self) -> str: return self.name class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( max_length=150, validators=[UnicodeUsernameValidator, ], unique=True ) email = models.EmailField( max_length=150, unique=True ) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) objects = UserManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email", ] class Meta: ordering = ['-date_joined'] class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.BigIntegerField quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} x {self.product}" def get_absolute_url(self): return reverse("cart:cart_detail") VIEWS: @login_required(login_url="/login_home") def cart(request): cart_item = Cart.objects.filter(user=request.user, product=1).first() if cart_item: cart_item.product = 1 cart_item.quantity = … -
How to serilaizer Both Image File and Array Field
Suppose I have this serializer in Django rest class CreateProfileSerializer(serializers.ModelSerializer): availability = UserAvailabilitySerializer(many=True) work_permit_pr = serializers.FileField() class Meta: model = UserProfile fields = [ 'work_permit_pr', 'availability' ] this is my views for above class but when i parse i am not able to either upload image or send data of array i.e many=True as front end always faces issue what is correct parser for both type i.e file and Serializer having many=True? class CreateUserProfileView(generics.CreateAPIView): serializer_class = CreateProfileSerializer permission_classes = [IsNanny, ] parser_classes = [parsers.MultiPartParser] def perform_create(self, serializer): return usecases.CreateUserProfileUseCase( serializer=serializer, user=self.request.user, ).execute() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) data = { "message": "User profile created successfully", "status": status.HTTP_201_CREATED } return Response(data) -
Images not displaying on my Website and PostgreSQL database that is hosted on Railway in Django app
I have a Django app with a PostgreSQL database hosted on Railway. I am able to retrieve and display all data from the database on my website except for images. Here is my relevant code: # views.py @csrf_exempt def addpost(request): if request.method == "POST": title = request.POST['title'] content = request.POST['content'] author = request.POST['author'] date = request.POST['date'] categories = request.POST['categories'] upload = request.FILES.get('image') newpost = NewPost( title=title, content=content, author=author, publication_time=date, categories=categories, image=upload ) newpost.save() return render(request, "addpost.html") # models.py class NewPost(models.Model): title = models.CharField() content = models.TextField() author = models.ForeignKey(User) publication_time = models.DateTimeField() categories = models.TextField() image = models.ImageField(upload_to="images/") The image field is saving to the database correctly, but not displaying on the front end. All other data displays fine. I have confirmed that: The images are saving to the database All other data displays correctly It seems to be an issue displaying the images only. Any ideas what I'm missing in order to get the images to display from the PostgreSQL database? -
Use jquery to detect changes in django-bootstrap-datepicker-plus
I am using django_bootstrap5 and django-bootstrap-datepicker-plus in my project. I have two datetime fields, I want to populate second field when first field is populated and I'm trying to detect this change using jquery, I tried following this question which is almost identical as mine, but it still does not work for me text here is my form widgets = {'date': DateTimePickerInput(attrs={'id': 'start-date'}), "end_date": DateTimePickerInput(attrs={'id': 'end-date'},range_from="date")} template form <div class="col-md-3"> <form method="post"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-primary">Save</button> </form> </div> jquery $(document).ready(function () { $('#start-date').on('dp.change', function (ev) { // function logic }); }); -
Multiple values for one key in drf APIClient GET request
I want to pass multiple values for a single key inside a drf APIClient GET request but only the first value gets sent. I am writing a unit test for my django application using drf's APIClient. I need to pass multiple values for a single key inside the query parameters. An example url would look like this: /api/v1/example/1/?tag=1&tag=tag2 Now I am trying to recreate this behavior in a test using the APIClient but I only ever get the first value. I tried: response = APIClient.get( url, params={"tag": [1, 2]} ) or response = APIClient.get( url, params={"tag": 1, "tag": 2]} ) or response = APIClient.get( url, params=[('tag', 1), ('tag', 2)] ) or payload = {'tag[]': [1, 2]} response = APIClient.get( url, params=payload ) Always the same result. If I check response.request["params"] the result is always {'tag': 1} -
TypeError: fromisoformat: argument must be str in django
hi i want migrate my code and use 5 laste created product but i see TypeError: fromisoformat: argument must be str i want use 5 product in template from django.db import models from django.core.validators import MaxValueValidator # Create your models here. class Product(models.Model): title = models.CharField(max_length=255, verbose_name="نام محصول") description = models.TextField(verbose_name="توضیحات محصول") little_title = models.CharField(max_length=255, verbose_name="توضیحات کوتاه") price = models.IntegerField(verbose_name="قیمت محصول به تومان") discount = models.IntegerField(blank=True, null=True, verbose_name="تخفیف (به تومان)") discount2 = models.IntegerField(blank=True, null=True, verbose_name="تخفیف (به درصد)", validators=[MaxValueValidator(100)]) image = models.ImageField(upload_to="Product", verbose_name="عکس محصول", default="Product/def.png") image1 = models.ImageField(upload_to="Product", verbose_name="عکس محصول 1", default="Product/def.png") image2 = models.ImageField(upload_to="Product", verbose_name="عکس محصول 2", default="Product/def.png") image3 = models.ImageField(upload_to="Product", verbose_name="عکس محصول 3", default="Product/def.png") image4 = models.ImageField(upload_to="Product", verbose_name="عکس محصول 4", default="Product/def.png") size = models.DecimalField(max_digits=3, decimal_places=1, verbose_name="قد محصول (به متر)") water = models.BooleanField(verbose_name="نیاز به آب زیاد؟") earth = models.BooleanField(verbose_name="تیاز به خاک خاص؟") earth2 = models.CharField(max_length=55, null=True, blank=True, verbose_name="درصورتی که به خاک خاص نیاز دارد " "اینجا نام خاک را قرار دهید در غیر " "اینصورت خالی بگذارید") light = models.BooleanField(verbose_name="نیاز به نور زیاد؟") created = models.DateTimeField(auto_now_add=True, verbose_name="تاریخ و زمان ایجاد") class Meta: verbose_name = "محصول" verbose_name_plural = "محصولات" def __str__(self): return self.title class Pot(models.Model): title = models.CharField(max_length=255, verbose_name="نام محصول") description = models.TextField(verbose_name="توضیحات محصول") little_title = models.CharField(max_length=255, verbose_name="توضیحات کوتاه") price = … -
Docker overlay2 directory growing with each build (zero downtime docker compose deployment)
Problem: The host machine's /var/lib/docker/overlay2 directory keeps growing with each build until I'm forced to stop the containers and run docker system prune -af to free up space. Here's the ncdu of the overlay2 directory after just 2 or 3 deployments/builds (there are many additional directories, but they're cut off): My deployment script for zero downtime keeps a set of containers always running. Here's the script: # sources: # https://www.atlantic.net/vps-hosting/how-to-update-docker-container-with-zero-downtime/ old_container=$(docker container ls --filter name=shipaware-django-* --filter status=running --latest | grep -o shipaware-django-[0-9].*) old_listener=$(docker container ls --filter name=shipaware-listener-* --filter status=running --latest | grep -o shipaware-listener-[0-9].*) # need to restart celery in case of new tasks old_celeryworker=$(docker container ls --filter name=shipaware-celeryworker-* --filter status=running --latest | grep -o shipaware-celeryworker-[0-9].*) old_celerybeat=$(docker container ls --filter name=shipaware-celerybeat-* --filter status=running --latest | grep -o shipaware-celerybeat-[0-9].*) echo "old_container: $old_container" docker compose -f production.yml up -d --scale django=2 --scale listener=2 --scale celeryworker=2 --scale celerybeat=2 --no-recreate --build #docker compose -f production.yml up -d --scale django=2 --scale listener=2 --no-recreate --build echo "scaled up django and listener to 2 containers" echo "sleeping 60s" sleep 60 docker container stop $old_container docker container stop $old_listener docker container stop $old_celeryworker docker container stop $old_celerybeat echo "stopped $old_container" docker container rm $old_container docker container rm $old_listener … -
Django annotate() optimization
Supposing a ManyToMany relationship between A and B. The following request is taking too much time to execute when some A instances have > 500 b. def get_queryset(self): qs = A.objects.all() qs = qs.annotate( not_confirmed=Count('b', filter=Q(b__removed__isnull=True, b__confirmed__isnull=True)), confirmed=Count('b', filter=Q(b__removed__isnull=True, b__confirmed__isnull=False)), ) return qs Do you have an idea how to optimize this ? I tried prefetch_related, or using b = B.objects.filter(removed__isnull=True) to do the request only once but not relevent... I would like my request time < 30 sec -
1024 worker_connections are not enough, reusing connections
2023/11/08 12:59:30 [warn] 1125#1125: 1024 worker_connections are not enough, reusing connections 2023/11/08 12:59:30 [alert] 1125#1125: *2978743 1024 worker_connections are not enough while connecting to upstream, client: 197.210.55.148, server: signals.sentinel.vip, request: "GET /api/token/968/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/token/968/", host: "here is my domin (im hiding it)" server { listen 80; server_name IP; client_max_body_size 2G; error_log /var/log/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/signals; } location / { if ($http_user_agent ~* (Googlebot|bingbot|Applebot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Sogou|facebot|ia_archiver) ) { return 403; } include proxy_params; proxy_pass http://127.0.0.1:8000; proxy_connect_timeout 300s; proxy_read_timeout 300s; proxy_send_timeout 300s; proxy_buffering on; proxy_buffer_size 16k; # proxy_buffers 6 16k; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_next_upstream error timeout http_502 http_503 http_504; } } This is my nginx.conf Any suggestion how i can fix this issue? Im using django pytho, have 21 workers.