Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making PyCharm default to Django tests runner
I have a Django project that works perfectly with PyCharm's Django tests Run/Debug config. For a particular project. how can I get PyCharm to default to Django test runner when clicking on a test method? When I click on the folder, the right click menu defaults to Django tests (as desired). ' When I click on a test method, the right click menu defaults to Python tests (not desirable, as my tests use Django). How can I force this to be Django tests? -
How to return a json object from html template back to views.py in django
In Django, how do I return a json object from html template back to views.py. The JSON object is an array of multiple JSON objects. I would like to return it back to the views.py file so that external get requests can be made to retrieve that JSON object. test.html <html> <head> <title>Test</title> <script> // Array to store JSON objects var jsonObject = { "data": [ {% for person in persons %} { "name": "{{ person.name }}", "weight": {{ person.weight }}, "height": {{ person.height }}, "date of birth": "{{ person.dob }}", }, {% endfor %} ] }; </script> </head> <body> <h1>JSON Objects:</h1> <pre id="personsDisplay"></pre> <script> document.getElementById("personsDisplay").textContent = JSON.stringify(jsonObject); </script> </body> </html> views.py def test(request): n = 10 # Replace with your desired value of N youngest_people = Persons.objects.filter( country=OuterRef('country') ).order_by('age')[:n] queryset = Persons.objects.filter( id__in=Subquery(youngest_peoples.values('birth')) ).order_by('country', '-age') context = { 'person': queryset } return render(request, 'test.html', context) The views.py is getting the top 10 oldest people from every country, passing that to the test.html to create the custom json object which is an array of the top 10 oldest people from every country json objects which shows their name, weight, height and date of birth. I then return that jsonObject back … -
many postgres.exe processes show on RAMMap with 4k private bytes
Here's my software environment OS: Windows Server 2016 version 1607 Database: PostgreSQL 12.12 Backend application: Django 4.0.8 RamMap: v1.61 I have memory leakage issue on this server and tried using RamMap to find out what's possibly cause this problem. As you can see in the attached image below, I have a lot of postgres.exe listing on the Processes page with pid and 4K Private bytes, but none of these shows up in Task Manager screen. All clients access PostgreSQL use http POST via my Django backend application installed on other server. I've tried some ways but fail: taskkill /f /pid <PID> did not work since they're not show in Task Manager. restart PostgreSQL service but theses zombie processes were still there. slow down clients access speed but these processes were still increasing. I have no idea how can I do to kill these processes. Could anyone give me some instructions to solve this problem? or the zombie processes is not even an issue that they will just there and have nothing to do with memory leakage? -
Pip instalation for Python 3.11 in docker
I have Dockerfile to build image for Django project that uses Python 3.11 and runs in poetry environment (see content below). Problem is when I try to donwload get-pip.py file and run it using Python, it says no such file or directory but it should be in the same directory where Dockerfile is. I don't know, but why isn't it there? P.S. I use docker desktop with WSL 2 (Ubuntu 20.04) and Dockerfile is in project directory (where poetry.lock and pyproject.toml files are), /website is directory where django project is. # Download image of Ubuntu 20.04 FROM ubuntu:20.04 # To prevent interactive dialogs ENV TZ=Europe \ DEBIAN_FRONTEND=noninteractive # Update and install necessary packages RUN apt-get update \ # Install necessary packages to allow compilation of source code && apt-get install -y --no-install-recommends \ tzdata \ build-essential \ checkinstall \ libreadline-gplv2-dev \ libncursesw5-dev \ libssl-dev \ libsqlite3-dev \ tk-dev \ libgdbm-dev \ libc6-dev \ libbz2-dev \ software-properties-common \ # Install python 3.11 && apt-get update \ && add-apt-repository ppa:deadsnakes/ppa \ && apt-get install -y --no-install-recommends \ python3.11 # Install pip for Python 3.11 RUN curl -sS -O https://bootstrap.pypa.io/get-pip.py | python3.11 # THERE'S AN ERROR RUN python3.11 get-pip.py # Install poetry ENV … -
Names of DJango admin form components
I am trying to re-arrange an admin form and add a button to do die rolling in the center of it. I'd like to keep the original functionality of controls. Most likely in another setting this would be done with some sort of java jiggery pokery but I'd rather just do it with django. I figure the simplest (if not easiest) way to get what I want would be to just do a custom admin form. But I am not sure what some of the controls are called so I've been having a time trying to find out how to set them up. Essentially this is a financial investment for a LARP I am involved in. Each Investment was done by a character (foreign key) against an institution (also foreign key). The player invests an amount of money. The staffer takes the money and rolls a die adding a modifier for the institution that is hidden from the player in a table and changes according to what is going on for that institution. If the die roll is X, they get Y result which determines if they lose their investment, get it back or make a profit. I want to … -
Django queryset for current week sales (not 7 days of sale - only sales for the actual week) getting naive datetime warning
I am trying to get current week sales for a particular vendor. It did works but a warning "created_at received a naive datetime (2023-05-28 00:00:00) while time zone support is active" keeps on bugging me. I know it is a warning but I really like to fix it. I tryed to format week_start and week_end to timestamp but it did not work. I also saw some answers on this issue using timezone, but I dont know if it is the best way do get rid of this warning. current_week_revenue = 0 # current week revenue week_start = date.today() week_start -= timedelta(days=week_start.weekday()) week_end = week_start + timedelta(days=6) current_week_orders = orders.filter(vendors__in=[vendor.id], created_at__gte=week_start, created_at__lt=week_end) Does anybody knows how to change this to get this warning away. The warning says it is a format matter but I am not being able to solve it. Thank you very much. -
Django template loop through dict and render it value below key
I'm using Django template to generate an HTML page in which I'm going through a dict, the key is an URL to a picture, the value is the caption to that image, what I'd like to render is in each row, the caption being right below the image, and render all entries (always four) in a dict in the same row, here's my code so far: <div class="grid grid-cols-2 gap-2 p-2"> {% for one_metric in url_list %} <ul> <tr> {% for url, caption in one_metric.items %} <td><img width="350" height="300" src="{{ url }}"></td> <td>{{ caption }}</td> {% endfor %} </tr> </ul> {% endfor %} </div> What ended up rendering is the caption listed on the right of the picture instead of being below it, I've searched through the Internet but didn't figure it out, any advice would be greatly appreciated! -
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") …