Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to not let django create django_migrations table
After the first creation of my database I don't want to change it,I won't need to makemigrations or to migrate from my django project, and I don't want Django to create django_migrations table, How I could do that? -
I'd like to reduce SQL statements using consecutive/chained prefetch_related()
Please let me ask how I can reduce the number of SQL using chained prefetch_related(). I wrote item = Item.objects.prefetch_related('item_photo', 'item_stock', 'item_review',) # .prefetch_related('item_photo').prefetch_related('item_stock')... item (0.000) SELECT "item"."id", "item"."name", "item"."price", "item"."category_id", "item"."runs", "item"."wins", "item"."description", "item"."total_sales", "item"."created_at", "item"."updated_at", "item"."on_sale", "item"."note" FROM "item" LIMIT 21; args=(); alias=default (0.000) SELECT "item_photo"."id", "item_photo"."item_id", "item_photo"."photo", "item_photo"."priority", "item_photo"."note" FROM "item_photo" WHERE "item_photo"."item_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9) ORDER BY "item_photo"."priority" ASC; args=(1, 2, 3, 4, 5, 6, 7, 8, 9); alias=default (0.000) SELECT "item_stock"."id", "item_stock"."item_id", "item_stock"."stock", "item_stock"."note" FROM "item_stock" WHERE "item_stock"."item_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9); args=(1, 2, 3, 4, 5, 6, 7, 8, 9); alias=default (0.000) SELECT "item_review"."id", "item_review"."item_id", "item_review"."user_id", "item_review"."stars", "item_review"."comment", "item_review"."note" FROM "item_review" WHERE "item_review"."item_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9); args=(1, 2, 3, 4, 5, 6, 7, 8, 9); alias=default <QuerySet [<Item: Apple>, <Item: Banana>, <Item: Orange>, <Item: Lemon>, <Item: Tea>, <Item: Ginger>, <Item: Onion>, <Item: Banana>, <Item: Water>]> but, it displayed many SQL statements even if I bound tables with prefetch_related(). In addition, if I wrote following this in views.py, pk= 4 item = Item.objects.prefetch_related('item_photo', 'item_stock', 'item_review',).get(pk=pk) context = { 'form': form, 'item': item, 'photos': item.item_photo.values(), 'stock': … -
Django: Pass a variable back into views
I'm writing a sudoku webpage with Django and JS so I'm passing my unsolved sudoku list into the page via the context dictionary. In the page, I have 2 buttons in a simple HTML form. If 'NEW' is selected, it refreshes the page with a new sudoku. If 'SOLVE' is selected, I want it to send the current sudoku list back into views to go through the solver function and then sent back into the template. I currently have everything working except I have no idea how to send the unsolved sudoku list back into views. I've seen a lot of responses to questions like this saying to use request.POST.get() but how would I get the list into the queryDict? Also, I can't seem to find any posts on this topic within the last decade or so. Correct me if I'm wrong, but I think Python and Django may have changed slightly in the last 10 - 15 years. -
PostgreSQL doesn't work in ubuntu 20.04 Django Docker
My docker-compose works fine and runs on Windows 10 but when i tried to run it from ubuntu 20.04 i get the DB errors. My django settings.py file: DATABASES = { 'default': { 'ENGINE': env('SQL_ENGINE'), 'NAME': env('SQL_DATABASE'), 'USER': env('SQL_USER'), 'PASSWORD': env('SQL_PASSWORD'), 'HOST': env('SQL_HOST'), 'PORT': env('SQL_PORT'), } } my .env file: SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=my_db SQL_USER=my_admin SQL_PASSWORD=my_api SQL_HOST=db SQL_PORT=5432 My 'docker-compose.yml` file: version: '3.9' services: web: build: ./pets command: gunicorn pets.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - .env depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - "1337:80" depends_on: - web volumes: postgres_data: static_volume: media_volume: My Dockerfile: FROM python:3.10.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev COPY requirements.txt . RUN pip install -r requirements.txt COPY entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $HOME RUN mkdir $APP_HOME WORKDIR $APP_HOME COPY .. $APP_HOME RUN mkdir $APP_HOME/staticfiles RUN mkdir $APP_HOME/mediafiles RUN chmod +x /usr/src/app/entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] First error i got: FATAL: role "my_admin" does not exist When i change the SQL_USER to postgres i've got … -
DJango eror: TypeError, Exception Value:__call__(): incompatible function arguments
I was trying to develop facial based attendance system, where user enter name,email and image in the database . tO Recognize, user enter image which recognise face endpoints using Python's face recognition library (https://pypi.org/project/face-recognition/). I defined database in models.py as class User(models.Model): name = models.CharField(max_length=255) email = models.EmailField() face_encodings = models.TextField(null=True, default=None) Similary, I have defened register and recognize function in views.py as def register(request): if request.method == 'POST': #name = request.POST['name'] #email = request.POST['email'] #image_file = request.FILES['image'] name = request.POST.get('name', '') # Use get method to get the value of 'name' key email = request.POST.get('email', '') image_file= request.FILES.get('image', None) image = face_recognition.load_image_file(image_file) face_encodings = face_recognition.face_encodings(image)[0] user = User(name=name, email=email,face_encodings=face_encodings) user.save() messages.error(request, 'User registered') return render(request, 'register.html') return render(request, 'register.html') def recognize(request): if request.method == 'POST': image_file = request.FILES.get('image', None) image = face_recognition.load_image_file(image_file) face_encodings = face_recognition.face_encodings(image) recognized_users = [] for face_encoding in face_encodings: users = User.objects.all() for user in users: user_face_encoding = face_recognition.face_encodings(user.face_encodings)[0] distance = face_recognition.face_distance([user_face_encoding], face_encoding)[0] if distance < 0.6: recognized_users.append({'name': user.name, 'email': user.email}) return JsonResponse({'status': 'success', 'recognized_users': recognized_users}) return render(request, 'recognize.html') I could register the user .But when i enter to recognize by uploading image . I got error: TypeError at /recognize/ __call__(): incompatible function arguments. The following … -
Python has stopped working when I import folium in my django project, why?
I'm facing a problem with my django project I'm creating a geolocation app with django 4.1, Python:3.11 Everything was working fine but when I import folium in my views, the local server crash, windows says "python has stopped working", and whenever I use the command "python manage.py" ,windows says "python has stopped working", and when I remove the "import folium inmy views" the project is running perfectly again. I don't know what is happening could someone help me please, I really need to solve the "folium" problem for my project These are all the packages installed in my virtual environment C:\Users\Neko>pip freeze asgiref==3.6.0 branca==0.6.0 certifi==2022.12.7 charset-normalizer==3.0.1 Django==4.1.7 folium==0.14.0 idna==3.4 Jinja2==3.1.2 MarkupSafe==2.1.2 numpy==1.24.2 Pillow==9.4.0 requests==2.28.2 sqlparse==0.4.3 tzdata==2022.7 urllib3==1.26.14 I checked in github and they said restart the pc: I already did Check if the package is installed in the right folder: I did, I installed it in a venv with all the dependencies Check if the version of python, django and folium was compatible: I did they all have the last version So what seems to be the problem please help me -
The right time to learn Django REST API
I would like to know what the right time is for learning django rest api , should I go for it after learning the basics ? thank you. nothing to show here -
Django Test Error: "1824, Failed to open the referenced table"
This is the flow of how my database is created: I already have a legacy MySql database with some tables. I create the django project and connect it to the legacy database. I run migrate, in order to create the django tables for sessions and authentication on the legacy DB. Then, directly from the DB I create the GeSession Table and the reference to the DjangoSession Table. Then I import all the tables models using "inspectdb" command. To be able to test, inside models.py, I set managed = True to every table except for the django ones. Then I run makeMigrations and migrate --fake-initial. If I try to use the django ORM to make queries it works without any problem, but during testing it keeps failing the test database creation giving me this error: MySQLdb.OperationalError: (1824, "Failed to open the referenced table 'django_session'") and then right after: django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'django_session'") Everytime I tweak something on the models.py file I delete the first migration file, I run makemigrations and then run: migrate --fake-initial. I dont understand what I'm doing wrong. Is it bad to keep the django tables and the other ones on the same … -
Is it impossible to apply view in authentication method?
I am trying to refresh jwt token during authentication method. (Because I want to handle tokens in server-side) I'm using Django, DRF. This is my authentication.py, which is included in 'DEFAULT_AUTHENTICATION_CLASSES' class CustomAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: # I want to apply CookieTokenRefreshView here # But if I apply view, it raises errors validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token), validated_token When I try to apply CookieTokenRefreshView, (I overrided TokenRefreshView to set jwt as cookie) error raises. (Actually, error raises already when I just import view) Errors ImportError: Could not import 'account.authenticate.CustomAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'APIView' from partially initialized module 'rest_framework.views' (most likely due to a circular import) (\venv\lib\site-packages\rest_framework\views.py). Is it impossible to issue access token when access token expires in Django? Please let me know if there is another solution. -
Comments not registering into database when submitting form
When I try add a comment via my form, the page is redirected correctly but no comment is rendered/added. I am getting the following error in terminal when trying to add comment: Broken pipe from ('127.0.0.1', 55445) views def post_comment(request, slug): template_name = 'view-post.html' post = get_object_or_404(BlogPost, slug=slug) # Comment posted if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet user_comment = comment_form.save(commit=False) # Assign the current post to the comment user_comment.post = post # Assign comment to user user_comment.user = request.user # Save the comment to the database user_comment.save() else: # You may include extra info here from `comment_form.errors` messages.error("Failed to post comment") return redirect('viewpost', {'slug': slug,}) html <form method="POST" id="comment-form"> {% csrf_token %} {{comment_form|crispy}} <button class="btn btn-outline-secondary rounded-0 comment-button" id="form-submit" type="submit" onClick="window.location.reload();">Submit</button> </form> -
Like button not recording the data
I have implemented a like button onto my view_post page, but the like's aren't been registered. When the button is clicked the page is redirected correctly but no likes are added. views def get_post(request, slug): try: post = BlogPost.objects.get(slug=slug) except BlogPost.DoesNotExist: messages.error(request, 'This post does not exist.') post = None comment_form = CommentForm() return render(request, 'mhpapp/view-post.html', {'post': post, 'comment_form': comment_form,}) def like_post(request, slug): template_name = 'view-post.html' post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) messages.success(request, ("Thanks for the like...:-)")) liked = True return redirect('get_post', {'slug': slug,}) urls path('<slug:slug>/', views.get_post, name='viewpost'), path('<slug:slug>/',views.like_post, name='likepost'), html <strong>{{ post.total_likes }} Likes</strong> {% if user.is_authenticated %} <form action="{% url 'likepost' post.slug %}" method="POST"> {% csrf_token %} {% if request.user in post.likes.all %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="post-id" value="{{ post.slug }}"><i class="fa-solid fa-heart-crack"></i></button> {% else %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="post-id" value="{{ post.slug }}"><i class="fa-solid fa-heart"></i></button> {% endif %} </form> {% else %} {% endif %} -
No module named 'library'
I am trying to add a login system with Google-api-python-client that let's user login with their google account and my frontend is REACT JS. I was following a tutorial and was setting up my serializers.py accordingly but my serialzers.py can't find library and i can't use the googe, register_social_user from rest_framework import serializers from app.models import * from django.conf import settings from rest_framework import serializers from library.sociallib import google from library.register.register import register_social_user from rest_framework.exceptions import AuthenticationFailed class GoogleSocialAuthSerializer(serializers.Serializer): auth_token = serializers.CharField() def validate_auth_token(self, auth_token): user_data = google.Google.validate(auth_token) try: user_data['sub'] except: raise serializers.ValidationError( 'The token is invalid or expired. Please login again.' ) print(user_data['aud']) if user_data['aud'] != settings.GOOGLE_CLIENT_ID: raise AuthenticationFailed('oops, who are you?') user_id = user_data['sub'] email = user_data['email'] name = user_data['name'] provider = 'google' return register_social_user( provider=provider, user_id=user_id, email=email, name=name) I have installed library in my django project but ot still does't work. why is it cauing the problem and what to do? and can anyone suggest me the best way to create a login system with Google for my React-django project?? -
django-two-factor-auth[phonenumbers] got a redundant migration -> psycopg2.errors.DuplicateTable: relation "two_factor_phonedevice" already exists
I'm facing the following database creation table error when spinning up a django project from scratch when I have django-two-factor-auth[phonenumbers] in my requirements. When I run the migrate command, it raises a psycopg2.errors.DuplicateTable error: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, projectapplication, otp_static, otp_totp, sessions, two_factor Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying projectapplication.0001_initial... OK (... project application migrations) Applying projectapplication.0032_alter_foo_bar_baz_and_more... OK Applying otp_static.0001_initial... OK Applying otp_static.0002_throttling... OK Applying otp_totp.0001_initial... OK Applying otp_totp.0002_auto_20190420_0723... OK Applying sessions.0001_initial... OK Applying two_factor.0001_initial... OK Applying two_factor.0002_auto_20150110_0810... OK Applying two_factor.0003_auto_20150817_1733... OK Applying two_factor.0004_auto_20160205_1827... OK Applying two_factor.0005_auto_20160224_0450... OK Applying two_factor.0006_phonedevice_key_default... OK Applying two_factor.0007_auto_20201201_1019... OK Applying two_factor.0008_delete_phonedevice... OK Applying two_factor.0009_initial...Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "two_factor_phonedevice" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 21, in <module> main() File "/app/manage.py", line 17, … -
i cant use node modules package
i have a js file: <script type="module" src="{% static 'admin_panel/assets/js/sendAxios.js' %}" > I use it in this way: import axios from "axios"; But it gives the following error Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../". When I chnage to : import axios from '../../../node_modules/axios'; It gives me the following error http://127.0.0.1:8000/static/node_modules/axios net::ERR_ABORTED 404 (Not Found) I always had these problems for import and require commands.. How can I use node modules of a package? -
How to loop over the items in Django?
I was stuck to loop my table in template and put only 4 teams in each table. Here i want to create table groups stage of football. My Table_Team has 8 teams. So, i want my table in template looping where the table each has 4 teams. So,how to do it? Here is my Table class Table_Team(models.Model): code = models.CharField(max_length=10, default="") team = models.CharField(max_length=50) group = models.CharField(max_length=1) play = models.IntegerField(default=3) win = models.IntegerField() draw = models.IntegerField() loss = models.IntegerField() goalDiff = models.IntegerField() points = models.IntegerField() And here is my Template <div class="container"> <div class="row"> <div class="col-md-4 mb-3"> <div class="ptable"> <h1 class="headin">Standings</h1> <table> <tr class="col"> <th>#</th> <th></th> <th>Team</th> <th>P</th> <th>W</th> <th>D</th> <th>L</th> <th>GD</th> <th>PTS</th> </tr> <tr class="wpos"> <td>&nbsp;</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table> </div> </div> </div> </div> Sorry for my english. I hope you understand what i mean. Thank you. -
Swagger is using schema host instead of current server
I am working with swagger , Django. I have used drf-spectural library. I have created one schema.yaml using openApi docs. And i have one docs/api/ API Url for swagger documentation . When i am executing API from documentation it is taking Host url of static file instead of my current server. for example :- my schema file is place of s3 bucket, The Url is https://bucket.awss-s3.com/folder/schema.yaml and my server url is https://sub-domain.example.com/docs/api/ and my example api url is https://sub-domain.example.com/api/get-product/ but when executing from swagger it is taking https://bucket.awss-s3.com/api/get-product/ So my swagger config are SPECTACULAR_SETTINGS = { "SWAGGER_UI_SETTINGS": { "url": "/static/schema.yaml" } } -
Sites-Framework and static_root
In my project, 3 different sites are working in a virtual environment. I have a 4th dashboard design to organize these sites. site1_settings.py STATIC_URL = 'static/site1/' STATIC_ROOT = BASE_DIR / 'static/site1/' STATICFILES_DIRS = [ "C:/projs/ddd/static/site1/", ] MEDIA_ROOT = 'C:/projs/ddd/media/site1/' MEDIA_URL = '/media/site1/' For 3 sites Static/site[1-2-3]/ and Media/site[1-2-3]/ works fine. But Dashboard doesn't work because it looks in their directory. Copying the Dashboard's files into each solves the problem, but DRY does not. How can I point Dashboard's Static and Media to a single Static/Dashboard and Media/Dashboard from Settings.py. Thanks in advance. -
Docker-compose doesn't work on ubuntu 20.04 [permission denied entrypoint.sh]
My docker-compose works fine and runs on Windows 10 but when i tried to run it from ubuntu 20.04 i get this error: ERROR: for container_web_1 Cannot start service web: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "/usr/src/app/entrypoint.sh": permission denied: unknown ERROR: for web Cannot start service web: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "/usr/src/app/entrypoint.sh": permission denied: unknown ERROR: Encountered errors while bringing up the project. I can't understand why do i get Permission denied for entrypoint.sh? I use chmod +x to avoid this... My entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z "$SQL_HOST" "$SQL_PORT"; do sleep 0.1 done echo "PostgreSQL started" fi exec "$@" My Dockerfile FROM python:3.10.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev COPY requirements.txt . RUN pip install -r requirements.txt COPY entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh COPY .. . ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $HOME RUN mkdir $APP_HOME WORKDIR $APP_HOME COPY … -
Need to store Cart Item in Django
I have to store CartItem: {"title": "bread", "price": "100.0"} in Django REST framework. App name: BackendDjangoApp But I am getting error: "return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: BackendDjangoApp_cartitem [26/Feb/2023 11:53:06] "POST /api/cartItems/ HTTP/1.1" 500 192021" views.py: class CartItemView(generics.ListCreateAPIView): queryset = CartItem.objects.all() serializer_class = CartItemSerializer serializers.py: class CartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = '__all__' models.py: from django.db import models from django.contrib.auth.models import User class CartItem(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) I am making POST request: http://127.0.0.1:8000/api/cartItems/ POST body: {"title": "bread", "price": "100.0"} I am not maintaining any User session. -
iam unable to use my Multiple product slides on Homepage in Django
I am attempting to display two product slides on the homepage of my website built with the Django framework. Upon reloading the page, I am able to view both slides, however, I am encountering an issue where I am unable to see all the buttons to control both slides. Currently, I am only able to view the buttons for one slide. I am unsure of what mistake I may have made #This is my view.py from math import ceil from django.shortcuts import render from django.http import HttpResponse from .models import Product # Create your views here. def index(request): products = Product.objects.all() n = len(products) nslides = n//4 + ceil((n/4)-(n//4)) allprods=[[products,range(1,nslides),len(products)],[products,range(1,nslides),len(products)]] params={'allprods':allprods} return render(request, "shop/index.html", params) def about(request): return render(request, "shop/about.html") def contact(request): return render(request, "shop/about.html") def product(request): return HttpResponse("we are at product") def checkout(request): return HttpResponse("we are at checkout") def tracker(request): return HttpResponse("we are at tracker") def search(request): return HttpResponse("we are at search") and this is my index.py {% extends "shop/basic.html" %} {% block title %} Link. {% endblock %} {% block css %} .col-md-3 { display: inline-block; margin-left:-4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img{ width: 227px; max-height: 242px; } body .carousel-indicator li{ background-color: blue; } body … -
alter __bases__ inherit in class and save new changes with python
Is there a way to alter an apiview class where by means of a Command I add a mixin class from which it must inherit and see the change reflected in the code after having executed the command Example: mixin.py class Mixin(object): pass views.py class ApiExampleApiView(generics.ListAPIView): pass example_command.py class Command(BaseCommand): def handle(self, *args, **options): ApiExampleApiView.__bases__ += (Mixin, ) **here I do not know if something should go to save and after executing the command, the api will see the change reflected as follows views.py class ApiExampleApiView(Mixin, generics.ListAPIView): pass -
I am trying to create an application, with react front end and django backend that would call a third party API named betaface
I created the frontend form that would take namespace and the file as an input and send it to the backend. When i was trying to test it, i received the following errors. Error upload_image_to_betaface() missing 1 required positional argument: 'file_path' Here's my views.py file url = "https://www.betafaceapi.com/api/v2/media/file" payload = { 'api_key': 'd45fd466-51e2-4701-8da8-04351c872236', 'set_person_id': f'random@{namespace}' } files = [('file', ('image.jpg', open(file_path, 'rb'), 'image/jpeg'))] headers = {} response = requests.request("POST", url, headers=headers, data=payload, files=files) return response.text``` models.py ```class UploadedImage(models.Model): image = models.ImageField(upload_to='uploads/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.image.name``` urls.py ```urlpatterns = [ path('upload/', upload_image_to_betaface), ]``` -
How to display two complete images in the same div size, like behance?
First of all, sorry for my bad english It turns out that I am trying to make a section where several images are shown, the format is that the user previously loads the images and the number of columns per block/div from a form. Now my problem is when the images within the same block/div are of different sizes, I don't know if it is because of different height or width. What I managed to do is make them both have the same size, all inside the block/div, but they lose the content, that is, they don't look complete. Now I pass two screenshots, where the first is how it fits me, and the second is how I would like it, which would be a style to behance with the grids. Because of my bad English my case behance case Now I pass you part of the code that I am implementing! <section id="content-body" class=" " style=""> <input id="{{project.id}}" type="text" class="pid" style="display:none;"> <div class=" mt-20 mb-10 grid place-items-center" style=""> {% for data in projectImages %} <div x-data="{dropdownOpen: false}" @click.outside="dropdownOpen = false" class="relative group/cuadricula"> <div class="grid max-w-7xl mb-3 gap-3" style=" grid-template-columns: repeat({{data.columns}}, minmax(0, 1fr)); "> {% for img in data.images.all %} … -
why domain name points to root directory index.html[Congratulation page]in linux django, but not to AWS lightsail instance ip address
I have an AWS lightsail account [Linux, Django]. I managed to point my domain name to my lightsail Ip address. This page displays the Congratulation setup page, which is in the root directory and the file is the index.html [Default landing page]. I created a simple lightsail instance page with views.py and urls.py. In the browser, if I type the domain name, it resolve the index.html page, only. But when I type the Ip address, it resolve to my AWS instance page. Problem, how do I get Domain Name to resolve to my instance Ip address. I managed to properly point the domain name to my Ip address [the Congratulation page, default page] but not my AWS instance Ip address [for my website]. -
How to use railway PostgreSQL Database with Django
It is my first time working with the railway PostgreSQL database, I used postgres connection URL and my connection is working fine but I can't find the database table I created in models.py Models.py from django.db import models # Create your models here. class Todos(models.Model): # item = models.CharField(max_length=300) I have checked resources online but don't seem to find any solutions, I'm not sure if am doing something wrong. Can someone help me with this pls