Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I show the parameters in the URL when using Datatables' Server-side processing and SearchBuilder with Django?
I created a Django web app that queries a very large database. To address that, I use Datatables with Server-side processing and SearchBuilder and Django Pagination which all works great. I have an "index" view for a landing page which includes a Datatables component. A serperate "dt-json" view is used to respond to the Datatables' ajax request with json data. I need the index page to have the ajax request parameters as endpoints in the URL. Currently, the index page URL looks like this: http://127.0.0.1:8000/ and I want it to look like this: http://127.0.0.1:8000/?draw=1&columns%5B0%5D%5Bdata%5D=id&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&col... by default, with the entire SearchBuilder parameter string as the endpoint for bookmarking purposes. I know that the index page is not receiving the ajax request but is there a simple way of passing up this data to be displayed in the index URL? This is my first question post on Stack Overflow so my apoligies for any discrepancies. Thanks SO! Snippets of my code. models.py: class Flight(models.Model): id = models.BigAutoField(primary_key=True) user = models.CharField(max_length=32, blank=True, null=True) class Meta: managed = False db_table = 'flight' def get_data(self): return { 'id': self.id, 'user': self.user, } urls.py: urlpatterns = [ # homepage path('', views.index, name='landing-page'), # JSON object URL … -
How to rename Model without altering Table in Django?
We simply want to rename a Django model while preserving the existing DB table name. It would seem that the Meta field db_table would do this, except apparently this acts as an instruction to migrate, which then generates a migration AlterModelTable to change the actual table. Additionally, the ideal solution would be understood by makemigrations so that it does not repeatedly try to generate some ALTER statement. I am shocked, because this suggests to me that the database table name is not configurable. This seems so basic. Surely there is a way? Similar question here, but that one is about renaming a field: Django renaming model field without ALTER TABLE on the database. -
How to disable all dates in Django's DateInput widget except for those stored in a list?
first poster here in need of some help please. I'm building a web app with Django as a personal training project for bookings and I use a DateInput widget to display the dates for the user to select from. I somehow need to grey out(disable) everything, except for dates I have stored as objects in a list called available_dates. The list is asc ordered by date. I only managed to restrict the view to the first and last date available, but cannot figure out how to also disable the dates in between that are not available to book. Many thanks for any advice. print(available_dates) [<AvailableDate: 2023-05-25>, <AvailableDate: 2023-05-27>, <AvailableDate: 2023-05-28>] And here is my DateInput class: class DateInputSpecific(forms.DateInput): input_type = 'date' def __init__(self, *args, **kwargs): self.available_dates = kwargs.pop('available_dates', []) super().__init__(*args, **kwargs) def get_context(self, name, value, attrs): attrs.setdefault('min', self.available_dates[0].date) attrs.setdefault('max', self.available_dates[len(self.available_dates)-1].date) context = super().get_context(name, value, attrs) return context -
How can I generate a sub_transaction_number based on a selected main_transaction_number in Django using HTML Form fields?
I want to generate sub_transaction_number base on a selected main_transaction_number from html Forms fields. The format should OD2305230101 Where OD is the abbreviation for shipment period store in database. (Retrieved main_transaction_number from sales table, base on the shipment period for the selected main_transaction_number look for it corresponding abbreviation from the shipment period table) Where 23 is the last two digits of production year also stored in the sales table per main_transaction_number. Where 052301 is the main_transaction_number select from the form drop down field stored in the sales table Where 01 is count or number sequence for the selected main_transaction_number Note: Multiple of sub_transaction_number can generated for one main_transaction_number which have to follow number sequence with reference to the last sub_transaction_number saved in the sub_transaction_number table. The main_transaction_number is used as foreign key in a model called MainTransactionNumber Eg main_transaction_numb 052301 can have sub_transaction_number OD2305230101 OD2305230102 OD2305230103 The generated sub_transaction_number should be displayed live as value and read only in html form once main_transaction_number is selected from a drop list in the same form Be able to generate a sub transaction number live once a main transaction number is selected from a drop down list before the form is submitted -
Effective Approaches for Optimizing Performance with Large Datasets in Python?
I am currently working on a project that involves processing large datasets in Python. While I have managed to make it work, I am facing performance and efficiency challenges, especially when dealing with massive amounts of data. To provide more context, let's assume I have a dataset with millions of records, and I need to perform complex computations or data transformations on it. Currently, my code takes a significant amount of time to process the data, and it seems to consume a considerable amount of memory, leading to potential memory errors or slowdowns. Here's a simplified example of my code structure: import pandas as pd def process_large_dataset(): # Load the large dataset into a DataFrame df = pd.read_csv('large_dataset.csv') # Perform computationally intensive operations # ... (complex computations or data transformations) # Store the processed data to a new file or database df.to_csv('processed_data.csv', index=False) I would like to optimize my code and improve its efficiency when handling large datasets. Specifically, I am seeking advice on the following areas: Memory Management: What are the best practices for reducing memory usage when working with large datasets? Are there any techniques to minimize the memory footprint during data loading, processing, or storage? Speeding up … -
Send multiple HTMX HX-Trigger events in header from Django and trigger multiple events in html
I have two elements that I want to re-render after updating data in the db. The two html dom elements are: <div hx-trigger="revealed, update_location_graph_{{location.id}} from:body" hx-target="#plot_div_{{location.id}}" hx-get="{% url 'location-progress' location.id %}"> <div id="plot_div_{{location.id}}"> </div> </div> and <div hx-trigger="revealed, update_group_graph_{{ location.id }}_{{ group.id }} from:body" hx-target="#plot_div_{{location.id}}_{{group.id}}" hx-get="{% url 'group-progress' location.id group.id %}"> <div id="plot_div_{{location.id}}_{{group.id}}"> </div> </div> The one is a graph for all the groups of a location and the other is a graph for only one group in one location. In Django I want to send up two events to trigger the two updates in one response. Django code as follows: trigger1 = f'update_group_graph_{ location.id }_{ group.id }' trigger2 = f'update_location_graph_{ location.id }' return HttpResponse(status=204, headers={'HX-Trigger': {trigger1:"a", trigger2:"b"}}) I got the dictionary idea from this link on htmx's site, but this seems to only work for js listeners. Any ideas on how to send or receive these events correctly? -
While trying to save anything via Django Admin Getting Forbidden (403) CSRF verification Failed .Request Aborted Django Admin
While trying to save anything via Django Admin Getting Forbidden (403) CSRF verification Failed .Request Aborted. earlier It was working fine ,when we deployed the code It started throwing this error . I tried by disabling CSRF for temporary fix.What can be possible solutions to fix this issue and why this occurs generally. Having the same settings file ,django admin is working on dev but on production. enter image description here My setting.py file :- # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'guardian', 'corsheaders', 'djangodeletes', 'BruteBuster', 'admin_honeypot', 'django_bleach', #apps for health check - system monitoring 'health_check', # required 'health_check.db', # stock Django health checkers 'health_check.cache', 'health_check.storage', 'health_check.contrib.psutil' # disk and memory utilization; requires psutil # 'qr_code' # 'elasticapm.contrib.django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', #'csp.middleware.CSPMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'BruteBuster.middleware.RequestMiddleware' # 'elasticapm.contrib.django.middleware.TracingMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000" ] ROOT_URLCONF = 'design_studio_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # 'elasticapm.contrib.django.context_processors.rum_tracing', ], }, }, ] # Django soft deletable TEMPLATE_LOADERS = ( 'django.template.loaders.eggs.Loader', ) … -
Docker won't allow change template files in django web app
I have a Django app running in Docker, and while I can change .py files, for some reason (I am assuming Docker is blocking write access) I can't save changes to templates files. Is there a way around it without spinning down the container? docker-compose.yml version: '3.8' services: web: build: ./app command: gunicorn -w 3 myapp.wsgi:application --bind 0.0.0.0:8000 --reload volumes: - ./app/:/usr/src/app - ./static/:/home/app/web/static - ./media/:/home/app/web/media expose: - 8000 env_file: - ./.env restart: unless-stopped nginx: build: ./nginx volumes: - ./static/:/home/app/web/static - ./media/:/home/app/web/media ports: - 7000:80 depends_on: - web Dockerfile ########### # BUILDER # ########### # pull official base image FROM python:3.9.6-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY . . COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.9.6-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate directories … -
Accessing docker real client IP in docker container when haproxy itself is running as docker container
My app runs on cluster of 6 docker containers. Three of them are haproxy, nodejs (runs react app) and wsgi (runs django app). Following is my docker compose file (relevant sections are haproxy, wsgi and nodejs): version: "3.8" services: postgres: image: postgres:11 volumes: - myapp_postgres_volume:/var/lib/postgresql/data - type: tmpfs target: /dev/shm tmpfs: size: 536870912 # 512MB environment: POSTGRES_DB: mymodule POSTGRES_USER: myapp POSTGRES_PASSWORD: myapp123 networks: - myapp_network pgadmin: image: dpage/pgadmin4:5.4 volumes: - myapp_pgadmin_volume:/var/lib/pgadmin environment: PGADMIN_DEFAULT_EMAIL: myapp@cse.myinsti.ac.in PGADMIN_DEFAULT_PASSWORD: myapp123 ports: - 8080:80 networks: - myapp_network redis: image: redis:6.2.4 volumes: - myapp_redis_volume:/data networks: - myapp_network wsgi: image: wsgi:myapp3 volumes: - /myapp/frontend/static/ - ./wsgi/myapp:/myapp - /myapp/frontend/clientApp/node_modules - /etc/timezone:/etc/timezone:ro - /etc/localtime:/etc/localtime:ro - /var/run/docker.sock:/var/run/docker.sock:ro depends_on: - postgres - redis ports: - 9090 - 3000:3000 - 8000:8000 environment: C_FORCE_ROOT: 'true' SERVICE_PORTS: 9090 networks: - myapp_network deploy: replicas: 1 update_config: parallelism: 1 delay: 10s restart_policy: condition: on-failure max_attempts: 3 window: 120s nodejs: image: nodejs:myapp3 volumes: - ./nodejs/frontend:/frontend - /frontend/node_modules depends_on: - wsgi ports: - 9000:9000 # development - 9999:9999 # production environment: BACKEND_API_URL: http://0.0.0.0:3000 networks: - myapp_network nginx: image: nginx-brotli:1.21.0 volumes: - ./nginx:/etc/nginx/conf.d:ro - ./wsgi/myapp:/myapp:ro - myapp_nginx_volume:/var/log/nginx/ - /etc/timezone:/etc/timezone:ro - /etc/localtime:/etc/localtime:ro networks: - myapp_network haproxy: image: haproxy:2.3.9 volumes: - ./haproxy:/usr/local/etc/haproxy/:ro - /var/run/docker.sock:/var/run/docker.sock - /etc/timezone:/etc/timezone:ro - /etc/localtime:/etc/localtime:ro depends_on: - wsgi … -
How to create a system with a dynamic modules?
I need to create a django system, but the client just have access in modules that it buyed. The system will be a 5 differents modules and i have to create to dynamic way. How can i do that? I have no ideia how can start a project like this. -
How to change Django model field from Integer to Decimal field for Postgres DB?
I'm trying to change the data type of a Django model field from PositiveBigIntegerField() into DecimalField(). From: quantity=models.PositiveBigIntegerField() To: quantity=models.DecimalField(max_digits=8, decimal_places=2) But when I migrate the change, it shows the following Postgres DB error: Numeric field overflow Detail: A field with precision 8, scale 2 must round to an absolute value less than 10^6. is there any idea how can I fix this issue? -
Django ValueError when posting data to DB from HTML form - how to assign Foreign Key from option list?
When posting data to database from HTML page I am getting ValueError at /add_emp/ Cannot assign "'Female'": "PersonInfo.gender" must be a "Gender" instance I was trying to get the gender list under the html option list so that users can select one during post. My code looks as follows. I am new to django and self teaching from the internet. **Models.py** class Gender(models.Model): gender = models.CharField(max_length=10) def __str__(self): return self.gender class PersonInfo(models.Model): pid = models.CharField(max_length=10, blank=False) first_name = models.CharField(max_length=15, blank=False) middle_name = models.CharField(max_length=15, blank=False) last_name = models.CharField(max_length=15, blank=False) birth_date = models.DateField(blank=False) gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True) def __str__(self): return(f"{self.first_name} {self.last_name}") **Views.py** def add_emp(request): if request.user.is_authenticated: all_record = PersonInfo.objects.all() # Show Form if request.method == "POST": pid = request.POST['pid'] first_name = request.POST['first_name'] middle_name = request.POST['middle_name'] last_name = request.POST['last_name'] birth_date = request.POST['birth_date'] gender = request.POST['gender'] new_employee = PersonInfo(pid=pid, first_name=first_name, middle_name=middle_name, last_name=last_name, birth_date=birth_date, gender=gender) new_employee.save() messages.success(request, "Employee Added") return render(request, 'add_emp.html', {'all_record': all_record}) else: return render(request, 'add_emp.html', {'all_record': all_record}) else: messages.success(request, "Access denied") return redirect('lobby') **add_emp.html** <select name="gender" class="form-select"> <option selected>Select Gender</option> {% for gender in all_record %} <option> {{ gender.gender }} </option> {% endfor %} </select> -
It shows IntegrityError at /signup/ when hosting through pythonanywhere
I am trying to build a project and I have been able to successfully host the website locally and it is working perfectly fine. This time I tried hosting on pythonanywhere and it shows IntegrityError at /signup/ I don't really understand what it means. I am attaching the whole error file Error Github Link I tried re-migrating the project. I tried python manage.py mirgate --fake and some of the things given online but to no avail. -
'property' object has no attribute '_meta' while using django-activity-stream package
I am using the django-activity-stream package to show activity stream. Everything worked fine, but I couldn't assign user as an actor. This is my signals.py file. from actstream import action from django.db.models.signals import post_save from django.dispatch import receiver from apps.teams.models import Team from apps.users.models import User @receiver(post_save, sender=Team) def track_team_created(sender, instance, **kwargs): action.send(User, verb="create a team", target=instance) print("create a team") In this case, I can create a team. However, when I see the actions I get the below error. Field 'id' expected a number but got '<property object at 0x7f3804cf8540>'. Ok. I get that. I need user's id. So, I tried to add User.pk instead just User. Now, I cannot even create a team with below error. 'property' object has no attribute '_meta' I tried bunch of different ways. Like using User._meta.pk, settings.AUTH_USER_MODEL etc. but I couldn't solve this. For the reference, User class is using AbstractUser I am trying to solve this without touching the User Model because I have same issue in the other app, but this was in Model directly, so I could solve it easier. def save(self, *args, **kwargs): super().save(*args, **kwargs) action.send(User(self.author).pk, verb="created a note title") It was in models.py and it has class meta: and … -
Why are my Django project's blog images not showing when DEBUG is False on AWS Elastic Beanstalk?
I am using aws elasticbeanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.5.2) for my Django project. So I deployed project to elasticbeanstalk by following https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html 1 and with no issue I can see my static and images applied correctly. But when I add a blog image is not shown if DEBUG = False in my settings.py when I deployed. But if it is DEBUG = True, I see blog and images with no issue. I added screenshot below settings.py STATIC_URL = ‘/static/’ if DEBUG: STATICFILES_DIRS = [ os.path.join(BASE_DIR, ‘static’) ] else: STATIC_ROOT = os.path.join(BASE_DIR, ‘static’) MEDIA_ROOT = os.path.join(BASE_DIR, ‘media’) MEDIA_URL = ‘/media/’ urls.py urlpatterns = [ path(‘’, views.HomeView.as_view(), name=‘home’), path(‘blog/’, views.blog, name=‘blog’), path(‘blog/int:blog_id/’, views.blog_details, name=‘blog_details’), path(“ckeditor/”, include(‘ckeditor_uploader.urls’)), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
review ratings not displaying on the stars in Django
I have number of ratings in the database that needs to be displayed on the stars. This is what I tried, models.py:- class Doctors(models.Model): name = models.CharField(max_length=100, blank=True, null=True, default="") ratings = models.CharField(max_length=100, blank=True, null=True, default="") views.py:- def result(request): if request.method == 'POST': search = request.POST.get("search") result = Doctors.objects.filter(speciality__icontains=search) return render(request, "result.html", {"result": result}) return render(request, "result.html") result.html:- {% for res in result %} <div class="desc"> <h6 class="primary-text">{{res.name}}</h6> </div> <div class="ratings" id="ratings"> <i class="fa fa-star {% if res.ratings >= 1 %} rating-color {% endif %}"></i> <i class="fa fa-star {% if res.ratings >= 2 %} rating-color {% endif %}"></i> <i class="fa fa-star {% if res.ratings >= 3 %} rating-color {% endif %}"></i> <i class="fa fa-star {% if res.ratings >= 4 %} rating-color {% endif %}"></i> <i class="fa fa-star {% if res.ratings >= 5 %} rating-color {% endif %}"></i> </div> {% endfor %} This is what I am getting This is what I am expecting -
How to pass metadata to "Metadata" section in "Payments" on Stripe Dashboard after a payment on Stripe Checkout?
With the Django code below, I'm trying to pass metadata to Metadata section in Payments on Stripe Dashboard: # "views.py" from django.shortcuts import redirect import stripe def test(request): checkout_session = stripe.checkout.Session.create( line_items=[ { "price_data": { "currency": "USD", "unit_amount_decimal": 1000, "product_data": { "name": "T-shirt", }, }, "quantity": 2, } ], mode='payment', success_url='http://localhost:8000', cancel_url='http://localhost:8000', metadata = { # Here "name": "Joho Smith", "age": "36", "gender": "Male", } ) return redirect(checkout_session.url, code=303) So, I make a payment on Stripe Checkout as shown below: Then, I click on the payment on Payments on Stripe Dashboard as shown below: But, Metadata section doesn't have anything as shown below: But actually, Events and logs section has the metadata as shown below: So, how can I pass metadata to Metadata section in Payments on Stripe Dashboard after a payment on Stripe Checkout? -
Django MVT - altering form before going into form validation
My app is a Django MVT app (not REST Framework) and I am trying to create a template which requests photos from the user's camera. In my model, I have two ImageFields (which would represent those two photos): photo1 = models.ImageField(upload_to='profile/user', null=True) photo2 = models.ImageField(upload_to='profile/user', null=True) In my form, I declared them as TextInputs as follows: 'photo1': forms.TextInput(attrs={'class': INPUT_DEFAULT_CLASS, 'disabled': True}), 'photo2': forms.TextInput(attrs={'class': INPUT_DEFAULT_CLASS, 'disabled': True}), The reason I wanted them to be Text is because if it was a FileField and a user took a photo, I couldn't add the photo programatically into the FileField (because FileField is translated into a input type="file", which cannot be mutated through JS). So I add the file as a encoded base 64 png file into this Text Input and I want to process in order to make it ready for the ImageField from the model. In my form, I tried to do it like this, in the clean() method: def clean(self): cleaned_data = super().clean() photo1_data = self.data['photo1'] photo2_data = self.data['photo2'] if photo1_data and photo2_data: date_str = datetime.now().strftime('%Y_%m_%d') username = cleaned_data['username'] photo1_image = base64.b64decode(photo1_data.split(';base64,')[1]) photo1_file = ContentFile(photo1_image, name=f"{date_str}_{username}_photo1.png") photo1_uploaded = InMemoryUploadedFile(photo1_file, None, f"{photo1_file.name}", 'image/png', photo1_file.tell, None) photo2_image = base64.b64decode(photo2_data.split(';base64,')[1]) photo2_file = ContentFile(photo2_image, name=f"{date_str}_{username}_photo2.png") … -
solution for django.db.utils.OperationalError: (2002, "Can't connect to server on '127.0.0.1' (10061)")
I am a student who has recently started with studying database and django. I have been trying to open django web, but when I type python manage.py runserver it shows me a message at the end saying django.db.utils.OperationalError: (2002, "Can't connect to server on '127.0.0.1' (10061)") Is there any good solution for this problem? I have been searching for similar problems, but still haven't found a good solution yet. Please let me know if there is any other additional information needed. Thank you. -
Why is my React table not updating after adding or deleting objects in a Django database using axios and React Table?
Putting data from a django database into a react table I tried generating a JsonResponse with the data and display it at api/data. The data gets displayed on the url correctly. Then I tried loading the data inside the TableComponent using axios such as: const [data, setData] = useState([]); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('/api/data'); setData(response.data); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); The data gets loaded into a tableInstance like this: const tableInstance = useTable({ columns, data, }) It worked the first time but when I add or delete objects using the admin panel it gets displayed correctly at the api/data address but it won't show inside my table. -
Django in dock-compose can't see the database : Could not translate host name "db" to address: Name or service not known
I am currently on a project based around react in the frontend, django in the backend, postgresql for the database and nginx for the reverse proxy. Everything is linked up with a Docker-compose file. Right now, I try to link my postgresql database to django. However every time I try to launch my network with the docker-compose CLI, it fails with the migration of data in the django backend container with the following error: #0 0.697 django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known I do not understand why I have this error. When I try to check if the database is up, it works without any problem: docker-compose up -d db Creating network "docker_nginx_django_react_template_appNetwork" with driver "bridge" Creating db ... done docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES _ postgres:latest "docker-entrypoint.s…" 5 seconds ago Up 4 seconds 0.0.0.0:5432->5432/tcp, :::5432->5432/tcp db Here is my docker-compose file : version: '3.8' services: nginx: container_name: app_server_conf build: context: ./ dockerfile: ./Dockerfile ports: - "80:80" environment: - PUBLIC_URL=127.0.0.1 volumes: - staticfiles:/staticfiles networks: - appNetwork depends_on: - backend db: image: postgres:latest container_name: db restart: always ports: - "5432:5432" networks: - appNetwork environment: POSTGRES_HOST_AUTH_METHOD: trust POSTGRES_USER: test … -
how to do review and ratings in django? [closed]
I have ratings in the database that needs to be displayed on the stars. class Doctors(models.Model): name = models.CharField(max_length=100, blank=True, null=True, default="") ratings = models.CharField(max_length=100, blank=True, null=True, default="") {% for res in result %} <div class="desc"> <h6 class="primary-text">{{res.name}}</h6> </div> <div class="ratings" id="ratings"> <i class="fa fa-star {% if res.ratings == 1 %} rating-color {% endif %}"></i> <i class="fa fa-star {% if res.ratings == 2 %} rating-color {% endif %}"></i> <i class="fa fa-star {% if res.ratings == 3 %} rating-color {% endif %}"></i> <i class="fa fa-star {% if res.ratings == 4 %} rating-color {% endif %}"></i> <i class="fa fa-star {% if res.ratings == 5 %} rating-color {% endif %}"></i> </div> {% endfor %} This is what I tried -
Ajax Request to Django backend, print response Data to Modal
Im trying to POST Data from a Model to a Template Modal after an AJAX request. So I´ve got a clickable <td> which triggers an JS funtion <table class="table"> <thead> <tr> <th scope="col">Client</th> </tr> </thead> <tbody> <tr> <td class="Client"><a href="javascript:void(0)" class="link-offset-2 link-offset-3- hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover" onclick="clientInfo(event);">Client001</a></td> <td class="Client"><a href="javascript:void(0)" class="link-offset-2 link-offset-3- hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover" onclick="clientInfo(event);">Client002</a></td> </tr> </tbody> </table> The <td> triggers on click the clientInfo(event) function: function clientInfo(e) { var $row = $(e.target).closest("tr"); var $hostname = $row.find(".Client").text(); $.ajax({ type: "POST", url: '/api/clientinfo', data: { 'hostname': $hostname, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function(response) { $('#clientmodal').modal("show"); } }) } The clientInfo(event) funtion posts Data to my Django view def clientInfo(request): qs = client.objects.prefetch_related('vuls') return HttpResponse( {'clientdata':qs.filter(client=request.POST['hostname'])}, status=200 ) Finally I want to show the clientadata in the clientmodal. <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" id="clientmodal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <h1>Hostname: {{clientdata.client}}</h1> </div> </div> </div> It only displays Hostname: I Think im not accessing the post Data right. Additionally I think that my filter on the prefetch related Query isn´t working correct. Models.py from django.db import models from django.contrib import admin class client(models.Model): client= models.CharField(max_length=50,primary_key=True) user= models.CharField(max_length=100) vuls = models.ManyToManyField( 'vul', through='clientvul', related_name='client' ) class vul(models.Model): vid=models.IntegerField(primary_key=True) … -
Trouble sorting and displaying the latest 5 messages in Django conversation interface
I am working on a Django project where I'm building an interface to display conversations in a table format. However, I'm facing difficulties in sorting the messages so that only the latest 5 received or sent messages are visible. To limit the messages displayed to 5, I have successfully used the |slice:"5" filter in my HTML template. However, I'm struggling to implement the sorting of messages. Here's the relevant code snippet from my Django template: {% for conversation in conversations %} <tr> <td class="conv-name"> <a href="{% url 'detail' conversation.id %}">{{ conversation.name }}</a> <br> <input type="checkbox" class="conv-check-input" data-conversation-id="{{ conversation.name }}"> </td> {% for message in conversation.conversation.all|slice:"5" %} <td> <div> <div class="message"> <label title="{{ message.date }}" id="{{ message.id }}-{{ message.origin }}" origin="{{ message.origin }}"> {# onclick="checked(this)"#} {{ message.texte }} {% if message.origin == "Humain" %} <input type="checkbox" class="form-check-input" data-message-id="{{ message.id }}" data-conversation-name="{{ conversation.name }}" > {% endif %} </label> </div> <div class="label"> {% for label in message.labels.all %} <p class="{{ label.color }}">{{ label.name }}</p> {% endfor %} </div> </div> </td> {% endfor %} </tr> {% endfor %} I would like to achieve the following: Sort the messages based on their timestamp or any other relevant criterion. Display only the latest 5 messages … -
Method takes 2 positional arguments but 3 were given
My method actually gets 2 arguments other than self: class MyService(object): def my_method(self, instance, **kwargs): In the test code: my_service.my_method(old_instance, new_data) and Python says that: takes 2 positional arguments but 3 were given Actually method has self among arguments so I was expecting to have no problem. What am I missing?