Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to access a model using a foreign key in another model in the same models.py file. But I am getting a name "model_name" not defined error
class chaiVariety(models.Model): CHAI_TYPE_CHOICE = [ ('ML', 'MASALA'), ('GR', 'GINGER'), ('KL', 'KIWI'), ('PL', 'PLAIN'), ('EL', 'ELAICHI'), ] name = models.CharField(max_length=100) image = models.ImageField(upload_to='chais/') date_added = models.DateTimeField(default=timezone.now) type = models.CharField(max_length=2, choices=CHAI_TYPE_CHOICE) description = models.TextField(default=' ') def __str__(self): return self.name #One to many class chaiReview(models.Model): chai = models.ForeignKey(chaiVariety, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField() comment = models.TextField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} review for {self.chai.name}' As I am trying to access the chaiVariety model inside the chaiReview using a foreign key, I am getting the following error : name 'chaiVariety' is not defined -
Trouble Filtering CartOrderItems by Vendor Using Django ORM
I'm facing an issue with filtering CartOrderItems by Vendor using Django's ORM. Here's the scenario and the problem I'm encountering: 1.Scenario: I have a Django application where vendors can upload products (Product model) and manage their orders (CartOrderItems and CartOrder models). 2.Objective: I want to fetch orders (CartOrder instances) associated with products uploaded by the current vendor (request.user). 3Current Approach: In my view function vendor_pannel1, I'm trying to achieve this as follows: @login_required def vendor_pannel1(request): # Get products uploaded by the current vendor (user) vendor_products = Product.objects.filter(user=request.user) # Get the vendor IDs associated with these products vendor_ids = vendor_products.values_list("vendor_id", flat=True) # Get CartOrderItems related to those vendors order_items = CartOrderItems.objects.filter(vendor_id__in=vendor_ids) # Get orders related to those CartOrderItems orders = CartOrder.objects.filter(cartorderitems__in=order_items).distinct() context = { "orders": orders, } return render(request, "vendorpannel/dashboard.html", context) Issue: It is filtering nothing. 5.Expected Outcome: I expect to retrieve orders (CartOrder instances) related to products uploaded by the current vendor (request.user). 6.My Models: class CartOrder(models.Model): user=models.ForeignKey(CustomUser,on_delete=models.CASCADE) item=models.CharField(max_length=100) price= models.DecimalField(max_digits=10, decimal_places=2,default="1.99") paid_status=models.BooleanField(default=False) order_date=models.DateTimeField(auto_now_add=True) product_status=models.CharField(choices=STATUS_CHOICE, max_length=30,default="processing") class Meta: verbose_name_plural="Cart Order" class CartOrderItems(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE,default=1)default order=models.ForeignKey(CartOrder,on_delete=models.CASCADE) # product = models.ForeignKey(Product, on_delete=models.CASCADE, default=1) #please dont't ignore it invoice_num = models.BigIntegerField(blank=True,null=True) product_status=models.CharField(max_length=200) item=models.CharField(max_length=100) image=models.CharField(max_length=100) qty=models.BigIntegerField(default=0) price= models.DecimalField(max_digits=12, decimal_places=2,default="15") … -
django orm - how to join multiple tables
I have a bunch of tables in postgresql: create TABLE run ( id integer NOT NULL, build_id integer NOT NULL, ); CREATE TABLE test_info ( suite_id integer NOT NULL, run_id integer NOT NULL, test_id integer NOT NULL, id integer NOT NULL, error_text text ); CREATE TABLE tool_info ( id integer NOT NULL, tool_id integer, revision_id integer, test_info_id integer, ); CREATE TABLE suite_info ( id integer, suite_id integer NOT NULL, run_id integer NOT NULL, ); CREATE TABLE test ( id integer NOT NULL, path text NOT NULL ); I'd like to write the following query using the django ORM. I'm using 2.2. select test.path, tool_info.id, run.id, test_info.id, suite_info.id from run join test_info on run.id = test_info.run_id join suite_info on run.id = suite_info.run_id join tool_info on tool_info.test_info_id=test_info.id join test on test_info.test_id=test.id where run.id=34; I've tried this: x= Run.objects.filter(suiteinfo__run_id=34) (Pdb) str(x.query) 'SELECT "run"."id", "run"."build_id", "run"."date", "run"."type_id", "run"."date_finished", "run"."ko_type", "run"."branch_id", "run"."arch_id" FROM "run" INNER JOIN "suite_info" ON ("run"."id" = "suite_info"."run_id") WHERE "suite_info"."run_id" = 34' I can see it is doing a join, but the data doesn't appear in the select. I've tried selected_related, and the like. the RUN table is the central table that ties the data together. How can I create that query … -
redirect in view not finding url path or html template
I am trying to redirect from one view to another view or url name but getting errors regardless of what type of redirect I use. My preference is to use the view name to avoid hard coding the url. Relevant views snippets involved: main view snippet if form.is_valid(): """ check if passwords match """ print('form is valid') password1 = form.cleaned_data.get('password1') password2 = form.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise messages.add_message(request, messages.error, "Passwords don't match") return redirect('/members:new_profile') """ create user, set hashed password, redirect to login page """ print('creating user') user = form.save(commit=False) user.set_password(password1) user.save() return redirect('members:user_login') user_login view def UserLogin(request): """ Member authenticate, set session variables and login """ if request.method == 'POST': username = request.POST.get('email') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: """ set session expiry and variables with login""" login(request, user) request.session.set_expiry(86400) watchlist_items = Watchlist.objects.filter(created_by_id=user.id, status=True).values_list('listing_id', flat=True) print(f"watchlist_items: {watchlist_items}") if watchlist_items: request.session['watchlist'] = list(watchlist_items) print(f"watchlist session variable: {request.session['watchlist']}") messages.add_message(request, messages.success, 'You have successfully logged in') else: request.session['watchlist'] = [] messages.add_message(request, messages.success, 'You have successfully logged in') return redirect('general/dashboard.html') else: """ user has old account, prompt to reactivate and pay new subscription """ messages.add_message(request, messages.error, 'This account is no … -
How I Can Fix Django Deployment Error With Media Files
Set up my django project with nginx, gunicorn and whitenoise; this using a ubuntu environment When I upload an image to my server, everything turns out excellent, but when making the request it gives this error: "GET /media/new/image/Imagen_de_WhatsApp_2024-07-05_a_las_14.24.21_e5e0f412.jpg HTTP/1.1" 404 179" This is the configuration of my different files: nginx: server { listen 80; server_name 127.0.0.1; location /static/ { alias /home/albert-ubuntu/django-club-page/staticfiles/; } location /media/ { alias /home/albert-ubuntu/django-club-page/media/; access_log off; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } gunicorn: #!/bin/bash NAME="django-club-page" # Nombre de la aplicación Gunicorn DJANGODIR=/home/albert-ubuntu/django-club-page # Directorio raíz de tu proyecto Django USER=albert-ubuntu # Usuario bajo el cual se ejecutará Gunicorn GROUP=albert-ubuntu # Grupo bajo el cual se ejecutará Gunicorn WORKERS=3 # Número de workers que Gunicorn utilizará BIND=127.0.0.1:8000 # Dirección y puerto donde Gunicorn escuchará DJANGO_SETTINGS_MODULE=api.settings # Módulo de configuración de Django que Gunicorn usará DJANGO_WSGI_MODULE=api.wsgi # Módulo WSGI de Django que Gunicorn cargará echo "Starting $NAME as `whoami`" cd $DJANGODIR # Cambiar al directorio de tu proyecto Django source venv/bin/activate # Activar el entorno virtual de Python (si lo usas) export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Añadir el directorio de tu proyecto al PYTHONPATH # … -
React + Django webapp doesnt show user messages, despite showing server messages which are managed by the same logic both frontend and backend
What the title says, I'm trying to make battleships with websockets, yesterday everything was going more or less smooth, aside from having multiple ws opening so after changing stuff around for a while and deleting <StrictMode> i solved that problem but realized that users couldnt send messages anymore. On Frontend those are the 2 tsx files, im new to both React and websockets so perhaps im misusing the component type or something idk. Lobby.tsx : import './Lobby.css'; import React, { useEffect, useState, useRef } from 'react'; import ChatLog from '../components/ChatLog'; import BattleShipGame from '../components/BattleShipGame'; const Lobby: React.FC = () => { const [messages, setMessages] = useState<{ message: string, username: string }[]>([]); const [message, setMessage] = useState(''); const [ws, setWs] = useState<WebSocket | null>(null); const isWsOpen = useRef(false); useEffect(() => { const roomName = new URLSearchParams(window.location.search).get('room'); const token = localStorage.getItem('accessToken'); if (roomName && token && !isWsOpen.current) { console.log('Attempting to open WebSocket connection'); const socket = new WebSocket(`ws://192.168.1.125:8000/ws/lobby/${roomName}/${token}/`); socket.onmessage = (event) => { const data = JSON.parse(event.data); console.log('Received WebSocket message:', data); if (data.type === 'chat_message') { console.log('Received chat message:', data); setMessages((prev) => { const newMessages = [...prev, { message: data.message, username: data.username }]; console.log('Updating messages state with:', newMessages); return newMessages; }); } … -
I'm trying to import csv data into a Django model. The import is failing due to data types
I'm using the Django import,export module in the admin panel. The import field in question is a CHAR field. The csv field in question can contain numbers or numbers and letters. If an entry contains just a number, it imports nothing for this field. If I load this csv file in a spreadsheet, it shows that the fields that contain only numbers are considered numbers, but the fields with a mix are obviously not numbers. I expected the fields with only numbers to be accepted as CHAR, since they are allowed normally. I don't understand why it is not accepting these values as characters, or what I can do about it. Is the problem with the import procedure, how the field is defined in Django, or is it some type of formatting that is needed in the csv? Thanks. -
Why Django API serializer.data return the data empty?
I have a strange issue with my Django API I created a Model called States My serializer has printed the data well but the serializer.data printing the data like the attached screen class States(models.Model): en_name = models.CharField(max_length=100) ar_name = models.CharField(max_length=100) class Meta: verbose_name_plural = "States" def __str__(self): return self.en_name and I created a Serializer file class StatesSerializer(serializers.Serializer): class Meta: model = States fields = ['en_name', 'ar_name'] then I made my views.py @api_view(['GET']) @permission_classes([IsAuthenticated]) def getStates(request): states = States.objects.all() # Fetch all states from the database serializer = StatesSerializer(states, many=True) # Serialize the data print(serializer) # Add this line to check the serialized data return Response(serializer.data, status=status.HTTP_200_OK) my printed serializer StatesSerializer(<QuerySet [<States: Alexandria>, <States: Aswan>, <States: Asyut>, <States: Beheira>, <States: Beni Suef>, <States: Cairo>, <States: Dakahlia>, <States: Damietta>, <States: Faiyum>, <States: Gharbia>, <States: Giza>, <States: Ismailia>, <States: Kafr El Sheikh>, <States: Luxor>, <States: Matruh>, <States: Minya>, <States: Monufia>, <States: New Valley>, <States: North Sinai>, <States: Port Said>, '...(remaining elements truncated)...']>, many=True): the attached screen shows how the data is returned -
How to add a subdomain to a django URL?
I just have a simple question: How can I add a subdomain to my django url, like: forums.websitename.com or account.websitename.com? Since my URLS were starting to get messy, I would like to add subdomains to my website that is still in development. Thank you for all possible help. -
Error when trying to use 'platform login' command in Platform.sh
I'm trying to use platform.sh in my python virtual environment, but when I try to run 'platform login' in a command prompt to login, it will not work. The login browser page does open and says I logged in successfully, but the command prompt says '[RequestException] cURL error 60: SSL certificate problem: unable to get local issuer certificate'. Here is the full output of the command prompt (ll_env) C:\Users\david\PycharmProjects\pythonProject2\learning_log>platform login Opened URL: http://127.0.0.1:5000 Please use the browser to log in. Help: Leave this command running during login. If you need to quit, use Ctrl+C. Login information received. Verifying... [RequestException] cURL error 60: SSL certificate problem: unable to get local issuer certificate I tried quite a few things. I downloaded cacert.pem and set it up, and I also asked ChatGPT, who had no clue on what was going on. It kept presenting 'solutions' that would do nothing to help. -
Why does request.COOKIES periodically return an empty dict?
I set a cookie in my view like so: response.set_cookie( 'cookie_name', 'true', max_age=100000 ) The cookie sets ok, and is viewable in dev tools. I have a tag which checks for a specific cookie on every page load: @register.simple_tag(takes_context=True) def get_cookie_status(context): request = context['request'] print(request.COOKIES) Around 40% of the time, this prints an empty dictionary and I have absolutely no idea why. As I said above, Django picks up no cookies at all, but the loaded page has all of the expected cookies present. Is there any common reason why this would occur? -
Error while migrating. I am deploying my django app+telegram bot to heroku
I am deploying my django app+telegram bot to heroku. While migrating data to heroku, i am getting an error: C:\Users\Acer\brand_online\brand_online>heroku run python manage.py migrate --app brand-telegram Running python manage.py migrate on ⬢ brand-telegram... up, run.7513 (Basic) python: can't open file '/app/manage.py': [Errno 2] No such file or directory everything seems simple, but i am not writing /app/ before manage.py. I dont know where did it come from. Procfile: web: gunicorn brand_online.wsgi worker: python main.py How to fix? heroku run python C:\Users\Acer\brand_online\brand_online\manage.py migrate i tried to use detailed link to manage.py -
Date pickers should start on Monday instead of Sunday
I have a custom widget for date input: class JQueryUIDatepickerWidget(DateInput): def __init__(self, **kwargs): super().__init__( attrs={ "size": 10, "class": "datepicker", "autocomplete": "off", "placeholder": "Select date", }, **kwargs, ) but when I open date picker, it starts from Sunday, like: Su, Mo, Tu, We, Th, Fr, Sa. Can I update it to start on Monday? Might it be solved adding some JS or JQuery code to my base.html -
Django: Vendor Profile Not Detected Despite Being Created
I am working on a Django project where each user can have an associated vendor profile. I've created a vendor profile for a user, but when I try to access the vendor's shop, it always renders the no_vendor.html page, indicating that the vendor profile does not exist. View Function: Here is the view function where I attempt to retrieve the vendor profile: @login_required def vendor_shop(request): try: vendor = Vendor.objects.get(user=request.user) except Vendor.DoesNotExist: # Handle the case where the vendor does not exist return render(request, 'vendorpannel/no_vendor.html') # Redirect to a page or show a message all_products = Product.objects.filter(vendor=vendor) all_categories = Category.objects.all() context = { "all_products": all_products, "all_categories": all_categories, } return render(request, 'vendorpannel/shop.html', context) Models: Here are the relevant models: class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") cover_image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=RichTextUploadingField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=RichTextUploadingField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=RichTextUploadingField(null=True, blank=True) tags=TaggableManager(blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def … -
ImproperlyConfigured` Error When Deploying Django to Vercel with Supabase PostgreSQL
I'm currently trying to deploy my Django project to Vercel, using Supabase as the PostgreSQL database provider. I have separated my settings into base.py, development.py, and production.py to manage environment-specific configurations. Problem: When attempting to migrate the database using python manage.py migrate, I encounter the following error: ```bash django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. ``` Setup Details: Database Configuration (production.py): from decouple import config import dj_database_url from urllib.parse import urlparse # Production-specific settings DEBUG = True # Parse the DATABASE_URL to extract components url = urlparse(config('DATABASE_URL')) # Configure your production database (example using PostgreSQL) DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } # configure the database ENGINE to use the Postgres database DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql' # Optional: Additional database settings DATABASES['default']['ATOMIC_REQUESTS'] = True # Cache configuration CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': config('UPSTASH_REDIS_REST_URL'), 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } # Static and media files settings for production STATIC_URL = '/static/' MEDIA_URL = '/media/' # Use proper email backend for production (e.g., SMTP) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = config('EMAIL_HOST') EMAIL_PORT = config('EMAIL_PORT', default=587) EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # Cloudinary storage for production DEFAULT_FILE_STORAGE … -
Iterate through all the days in a month in DJANGO template
enter image description here I have a model table like above which contains two columns on which dates on which an item is being sold in a month. I want to show the entire month table in Django template instead of showing only the dates of sale, and on each day showing "yes" if the sale is there and keeping blank if no sale is there on that day. I.e How to iterate in Template through all the days in a month. How the code should be in Django "views.py" and in Template models.py class SaleDates(models.Model): date_of_sale = models.DateTimeField(blank=True, null=True) sold_choices = ( ('yes', 'yes'), ('no', 'no'), ) sold_status = models.CharField(max_length=9, choices=sold_choices,) template.html {% for item in list %} {% if forloop.first %} <table class="table table-hover table-bordered"> <tr> <th>Sl.NO</th> <th>date</th> <th>details</th> </tr> {% endif %} <tr> <td> {{ forloop.counter }} <br/> </td> <td> {{ item.date_of_sale }}</td> <td> {{ item.sold_status }} </td> </tr> {% if forloop.last %} </table> {% endif %} {% empty %} {% endfor %} -
Where to write queries in rest api, and how to secure it
I will make an application with Flutter. With Django, I will make a rest api to send data from mysql. I have never made an api before. In the tutorials I found, when I go to the api url, the whole database appears directly. My goal is to display the data in that url only in requests made via flutter. How do I make it hidden? In my second question, should I make the queries on flutter, or should I create a new url for each filtered query I will make in django. For example, if I have 200 queries, should I have 200 different url structures. I have not written any code yet, I am researching. -
Hello everyone! Does anyone know how I can georeference a png image with Gdal using Django?
I am trying to georeference a .png image with some control points, which would be the corner coordinates. I have achieved this using Gdal only with: from osgeo import gdal ds = gdal.Open(f'{filename}.png') gdal.Translate(filename + '.tif', ds, outputBounds=bounds) but when I try to put this in my DJANGO API I can't because Django GDAL doesn't have the gdal.translate method. Does anyone know what the equivalent of this function is in Django gdal or how can I georeference a png image with boundaries using django? -
CSV file not found error in html file in pyscript tag . Running this html file in python Django web framework
I am learning python django web framework . Reading csv file content and showing in pandas dataframe but getting error file not found. Tried all possible options using latest , alpha pyscript release . Tried absolute path as well as relative path . When running index.html it gives csv file not found error . CSV file is alreday there in the directory where index.html is located . <py-env> -numpy - pandas - paths: - ./customer.csv </py-env> import pandas as pd import numpy as np df = pd.read_csv("./customer.csv") print(df.head()) -
Only first placeholder displayed in Django's UserCreationForm
I'm trying to make a sign-up page with a customized user creation form - add placeholders to the fields. I'm trying to do it this way: forms.py class SignUpForm(UserCreationForm): email = EmailField(max_length=200) class Meta: model = User fields = UserCreationForm.Meta.fields + ("password1", "password2", "email") widgets = { 'username': TextInput(attrs={'placeholder': 'Username'}), 'email': EmailInput(attrs={'placeholder': 'Email'}), 'password1': PasswordInput(attrs={'placeholder': 'Password'}), 'password2': PasswordInput(attrs={'placeholder': 'Repeat password'}), } However, it only affects the username's placeholders - the other ones are unaffected. What I've tried doing was to add the placeholder to the declaration of the email variable, which works. However, there has to be a simpler way to do it, and - even if I'd do that the passwords would still not have placeholders. I have also tried to make the fields variables, like email = CharField(TextInput(attrs{'placeholder': 'Email'}), but that didn't help too. Tried doing it as in the "Adding placeholder to UserCreationForm in Django" thread, but that didn't change anything. Other threads too, that's probably due to Django's version. Each time before trying it out I delete the site's browsing data to make sure it's not a client-side problem. -
When deploying Django to prod, Gunicorn lives in the virtual environment, but we deactivate the virtual environment when we go live with Nginx
I've been following a few tutorials online on how to setup Django, Postgres, Gunicorn and Nginx in production. I noticed that it is always recommended to install all Python dependencies inside the virtual environment. This includes Gunicorn. For example, we fire up our virtual environment initially, then execute the 'manage.py runserver 0.0.0.0:8000' command, we then test if Gunicorn binds to it. Once we see that Gunicorn works we then deactivate our virtual environment to start configuring Nginx. It is never mentioned to enable our virtual environment again. How is Gunicorn able to process requests when it lives inside the virtual environment, which had been deactivated? I assume there is a mechanism somewhere wherein the virtual environment is enabled again automatically. But where and when is the virtual environment enabled? I mean, how is it enabled? I've tried looking for answers online and in tutorials, but I still can't find anything that explains it fully. -
User is not created in django when making a request
I try to make some requests to django, all is working fine, but a user is not created. import json import requests url = 'http://127.0.0.1:8000/register/' for i in range(10): s = requests.Session() r1 = s.get(url) csrf = r1.cookies['csrftoken'] data = { 'csrfmiddlewaretoken': csrf, 'username-input': f'111111111{i}', 'email-input': f'111{i}1@gmail.com', 'password-input': '1111', 'password-input-verify': '1111' } r2 = s.post(url, data=data) print(r2.status_code) please help !!!!!!!!!!!! -
Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>: In my React Native, Django-restframework
I have setup my RTK Query in React Native (expo-router)/File based here files rtk/api.ts: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: "http://127.0.0.1:8000/" }), endpoints: (builder) => ({ signUp: builder.mutation({ query: (userData) => ({ url: "accounts/signup/", method: "POST", body: userData, }), }), login: builder.mutation({ query: (credentials) => ({ url: "accounts/login/", method: "POST", body: credentials, }), }), logout: builder.mutation({ query: () => ({ url: "accounts/logout/", method: "POST", }), }), passwordReset: builder.mutation({ query: (data) => ({ url: "accounts/password_reset/", method: "POST", body: data, }), }), passwordResetConfirm: builder.mutation({ query: (data) => ({ url: `accounts/password_reset_confirm/${data.uidb64}/${data.token}/`, method: "POST", body: data, }), }), changePassword: builder.mutation({ query: (data) => ({ url: "accounts/change_password/", method: "POST", body: data, }), }), userVerification: builder.mutation({ query: (data) => ({ url: "accounts/user_verification/", method: "POST", body: data, }), }), userVerificationConfirm: builder.mutation({ query: (data) => ({ url: `accounts/user_verification_confirm/${data.idb64}/${data.token}/`, method: "POST", body: data, }), }), addPhone: builder.mutation({ query: (data) => ({ url: "accounts/phone/add/", method: "POST", body: data, }), }), addEmail: builder.mutation({ query: (data) => ({ url: "accounts/email/add/", method: "POST", body: data, }), }), }), }); export const { useSignUpMutation, useLoginMutation, useLogoutMutation, usePasswordResetMutation, usePasswordResetConfirmMutation, useChangePasswordMutation, useUserVerificationMutation, useUserVerificationConfirmMutation, useAddPhoneMutation, useAddEmailMutation, } = api; rtk/store.ts import { configureStore } from "@reduxjs/toolkit"; import { … -
How to aggregate nested manytomany relationships in django orm
Given the pseudo definitions: class User: name: string class Account: owner: foreignkey(User, related_name="accounts") class Transactions: type: Enum(1,2,3) account: foreignkey(Account, related_name="transactions" value: Int How do I write this query using django ORM? SELECT user.id, type, AVG(value) as type_average FROM user JOIN account ON account.owner = user.id JOIN transactions ON transactions.account = account.id GROUP BY user.id, type -
How to use postgres' ARRAY in django orm
In postgresql, I am able to combine two columns into one into an array like so SELECT id, ARRAY[address,zip] as address_array FROM user Is there a way to do this using django's orm? Why? I want to be able to transform it into a dict mapping like users = dict(User.objects.values("id", "address").all()) Gives me a mapping of: { 1: "Address 1", 2: "Address 2", ... ... } And ultimately I want: { 1: ["Address 1", "Zip 1"], 2: ["Address 2", "Zip 2"], } I am looking for a solution using django's orm, not python. I know I can do this by using python code after looping through the queryset.