Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the fastest way to query for items with an existing foreign key and many-to-many entry in Django?
I have a simple model with a foreign key and a many-to-many relationship: class Car(models.Model): uuid = models.UUIDField() is_red = models.BooleanField() class Owner(models.Model): car = models.ForeignKey(Car, to_field="uuid", on_delete=models.CASCADE) class Driver(models.Model): cars = models.ManyToManyField(ProtectedArea, related_name="cars") Now a lot of my application logic relies on cars on which at least one of the three conditions: it is red, it has at least one owner, it has at least one driver is true. It might be an important information, that in reality the Car-model contains some rather big polygonal data, maybe that is relevant for performance here? I have a custom manager for this but now matter how I built the query it seems extremely slow. Times are taken from my local dev machine with ~50k cars, 20k Owners, 1.2k Drivers. The view is a default FilterView from django-filter without any filters being actually active. My manager currently looks like this: class ActiveCarManager(models.Manager): def get_queryset(self): cars_with_owners = Owner.objects.values("car__uuid").distinct() cars_with_drivers = Drivers.objects.values("cars__uuid").distinct() return ( super() .get_queryset() .filter( Q(uuid__in=cars_with_owners) | Q(uuid__in=cars_with_drivers) | Q(is_red=True) ) ) The view generates 2 queries from this, one count query and one query to fetch the actual items. The query that is so slow is the count query. On our … -
get the lastest record of an object
I have two models: Cat (id, name) CatRecords (id, cat_id, status, created_time) Each day, a cat have one record about the status of the cat I want to get all the cats and the latest record of each, sorted by the created_time of the record I can get all records of each cat, but I cannot get the latest record of each The query class of Cat: class Query(graphene.ObjectType): all_cats = graphene.List(CatType) cat = graphene.Field(CatType, cat_id=graphene.UUID()) latest_record = graphene.Field(CatRecordType) def resolve_all_cats(self, info, **kwargs): cats = Cat.objects.all() return cats def resolve_cat(self, info, cat_id): return Cat.objects.get(cat_id=cat_id) def resolve_latest_record(self, info): subquery = CatRecord.objects.filter(cat_id=OuterRef("id")).order_by( "-created_time" ) return ( Cat.objects.all() .annotate(latest_record=Subquery(subquery.values("id")[:1])) .values("latest_record") ) My query query { latestRecord{ id name } } the error is { "errors": [ { "message": "Received incompatible instance \"<QuerySet [{'latest_record': UUID('3d2af716-94aa-4952-9050-4d7f69384e3d')}, {'latest_record': UUID('0705aeda-a2ec-47c3-8bd1-1aa445c40444')}]>\".", "locations": [ { "line": 2, "column": 3 } ], "path": [ "latestRecord" ] } ], "data": { "latestRecord": null } } -
Django Social Authentication Issue: Unable to Login Using Facebook or LinkedIn
I'm facing an issue with integrating social authentication (Google, Facebook, LinkedIn) into my Django web application using social-auth-app-django. While Google login works fine, I'm unable to get Facebook or LinkedIn login to function correctly. Login | Facebook Error | Linkedin Error | Linkedin Error2 I followed the setup instructions for social-auth-app-django and configured the keys and secrets for Google, Facebook, and LinkedIn in my settings.py. Google authentication works as expected, redirecting users to the correct page after login. However, when attempting to log in using Facebook or LinkedIn, the authentication process fails silently without any clear error message or redirection.Steps Taken: Verified client IDs and secrets for Facebook and LinkedIn are correctly set in settings.py. Ensured correct scopes and field selectors are configured for LinkedIn. Checked that all necessary middleware and context processors are included in settings.py. from pathlib import Path import os import logging BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-@*#c*5am%k5_-@#axxxxxxxxxxxah=(h9pbnf!z-x01h@n#66' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'demo', 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'signin.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
how change the MARKDOWNX_MEDIA_PATH in Django setting to include the image name in the path?
I am using the markdown library, i want to change the path to the images in a way that it contains the name of the file, according to the markdown [doc][1] the path can change by adding something like : from datetime import datetime MARKDOWNX_MEDIA_PATH = datetime.now().strftime("markdownx/%Y/%m/%d") i tried adding image.name but it didn't work in the setting now i was wondering if i can inject the file name here in the setting some how? -
django-admin startproject coredj File "<stdin>", line 1 django-admin startproject core SyntaxError: invalid syntax what's problem here?
whenever i am firing django-admin startproject core this command it throws me syntax error. iam using python version3.11 and django version in 5.0.6. iam trying to create this in my E:drive and i have succesfullly installed the django and import it look for the version created virtaul env but still,not working throwing syntax error at startproject django-admin startproject coredj File "", line 1 django-admin startproject coredj ^^^^^^^^^^^^ SyntaxError: invalid syntax i checked for compatible version of django with python.when i run the command i expect it to create the foldername core in my pythonproject directory which is residing in my** E :**but it's not happening -
In django by turn off the button edit the value in database to ‘NO’ on turn on the button change it to ‘YES’. Using Django
models.py class AssetOwnerPrivileges(models.Model): asset_add = models.CharField(max_length=20,default='YES') html button <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> When button switch "ON" ,value in database change to YES ,while button switch "OFF" value change to "NO". -
How to send user ID through forms
I want to display the information in the profile section after receiving the information from the user But I can't submit the user ID through the forms My Models: class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='information') full_name = models.CharField(max_length=40) email = models.EmailField(blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name My Forms: class PersonalInformationForm(forms.ModelForm): user = forms.IntegerField(required=False) class Meta: model = PersonalInformation fields = "__all__" MY Views: class PersonalInformationView(View): def post(self, request): form = PersonalInformationForm(request.POST) if form.is_valid(): personal = form.save(commit=False) personal.user = request.user personal.save() return redirect('profile:profile') return render(request, 'profil/profile-personal-info.html', {'information': form}) def get(self, request): form = PersonalInformationForm(request.POST) return render(request, 'profil/profile-personal-info.html', {'information': form}) -
Is serializer.save() atomic?
@api_view(["POST"]) def register_view(request: "Request"): serializer = RegisterSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: serializer.save() except IntegrityError: raise ConflictException return Response(serializer.data, status=status.HTTP_201_CREATED) class ConflictException(APIException): status_code = 409 default_detail = "username is already taken" default_code = "conflict" def test_username_taken(self): with transaction.atomic(): User.objects.create_user(username="customer4", password="Passw0rd!") response = self.client.post( "/register", { "username": "customer4", "password": "Passw0rd!", "confirm_password": "Passw0rd!", "phone_number": "13324252666" }, ) self.assertEqual(response.status_code, status.HTTP_409_CONFLICT) The test result shows : raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I'm a Django and DRF noob and don't know what to do... I tested on postman and there is no problem, with 409 status_code response -
Is it possible to use transfer my django app on fme
So I created a randomiser app with django, I used import random and just called the function in my views. I could also use an implementation of fisher-yates algo to implement the randomisation I want. The person I built the app for has no python knowledge. They can't code with python. So I am trying to maybe integrate the python code on FME because they are efficient in using that. I was just wondering if it will be possible for me to do that. Has anyone tried something like that before and successfully done it. I am taking a short course in FME right now just to learnt the basics of using it. I am just wondering if there are any courses you guys will recommend or any steps for be to integrate the app on FME so they don't have to use django to use the app. -
What is causing this BadDeviceToken response in APNS?
This is my code sending the apns: @classmethod def PingDevice(cls, devicetoken, pushmagic): # Create the payload for the push notification payload = Payload(custom={'mdm': pushmagic}) print("Payload:", payload) print(f"device token: {devicetoken}") # Path to your certificate cert_path = os.path.join(settings.BASE_DIR, 'sign', "PushCert.pem") print("Certificate Path:", cert_path) # Load your certificate and private key credentials = CertificateCredentials(cert_path) print("Credentials:", credentials) # Create an APNs client apns_client = APNsClient(credentials=credentials, use_sandbox=False) print("APNs Client:", apns_client) # Send the push notification try: response = apns_client.send_notification(token_hex=devicetoken, notification=payload, topic='apns-topic') if response == 'Success': print("Push notification sent successfully") else: print(f"Failed to send notification: {response.description}") except Exception as e: print('Bad device token:', e) But i face the problem this is response i get with print in code on AWS: Bad device token: I really appreciate any help. -
OIDC Linkedin authentication canceled in django applicaation
I have integrated OIDC Linkedin third party auth in my django application and it automatically cancled authenticaton. I'm attaching logs for refrence, if anyone faced this issue before or does anyone know the solution please feel free to give me soluction, logs Django version is 4.1.2 library i used social-auth-core: 4.5.4 -
Dynamically generate django .filter() query with various attrs and matching types
I use django 1.6 (yep, sorry) and python2.7 and I need to generate queryset filter dynamically. So, the basic thing I need is to use different fields (field1, field2, field3) in filter and use different type of matching (equals, startsfrom, endswith, contains). Here as an example of possible combinations: Mymodel.objects.filter(field1__strartswith=somevalue). # Or like this: Mymodel.objects.filter(field2__endswith=somevalue). # Or like this: Mymodel.objects.filter(field3=somevalue) # Or like this: Mymodel.objects.filter(atrr3__contains=somevalue) I've found this answer and it looks good but I believe there are some more "django-like" ways to do it. I've also found this one with Q object. But maybe I can somehow import and pass to the queryset some objects of this types of matching? -
How can I get an image displayed in HTML with the URL from a context-object?
I'm new to Django and I'm now stuck at a problem of getting an image from a database displayed in an HTMl via it's URL. I had a code that was already working and I now tried to add advanced features and that's were all started to fall apart. So first of all what's already working: I have a Database where I store the URLs of Images and other data. I then display the images and the other data in a "Report"-Template. This is my view.py for this: from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from .utils import get_report_image from .models import Report1 from django.views.generic import ListView, DetailView from django.conf import settings from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa import pandas as pd class ReportListView(ListView): model = Report1 template_name = 'reports/main.html' class ReportDetailView(DetailView): model = Report1 template_name = 'reports/detail.html' # Create your views here. def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def create_report_view(request): if is_ajax(request): report_id = request.POST.get('report_id') name = request.POST.get('name') remarks = request.POST.get('remarks') img_Energie = request.POST.get('img_Energie') img_Emissionen = request.POST.get('img_Emissionen') img_Energie = get_report_image(img_Energie) img_Emissionen = get_report_image(img_Emissionen) #print("report_id: ", report_id) Report1.objects.create(report_id = report_id, name=name, remarks=remarks, image_Energie=img_Energie, image_Emissionen=img_Emissionen) return JsonResponse({'msg': 'send'}) return JsonResponse({}) and this is … -
static url settings in jinja2
I'm using jinja2 template in Djagon and I want to assign a static url for all my project so that I won't use long relative path in my css and js file. Below is how I set jinja2 template in Django and configured jinja2 environment. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, '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', ], 'environment': 'project.utils.jinja2_env.jinja2_environment', }, }, ] def jinja2_environment(**options): """ This is the :param options: :return: """ env = Environment(**options) env.globals.update({ 'static': StaticFilesStorage.url, 'url': reverse, }) return env However, when I use the static url in my css or js like: <link rel="stylesheet" type="text/css" href="{{ static('css/reset.css') }}"> It raised an error like: File "***\login.html", line 6, in top-level template code <link rel="stylesheet" type="text/css" href="{{ static('css/reset.css') }}"> TypeError: FileSystemStorage.url() missing 1 required positional argument: 'name' I guess maybe there is some conflict between jinja2 and Django because I can't use Django template suggested like below neither {% load static %} {% static 'css/reset.css' %} I could not figure this out. Someone could help me here? Thanks. -
Django creating duplicate records
There are only 5 subjects in the Subject table with unique names, but when run the following query to fill the table, some students have 5 some 10 and some are populated with 15 or 20 records. It should create records for every student for every subject only once. Any clue? def create_student_marks()-> None: try: students_obj = Student.objects.all() for student in students_obj: subjects_obj = Subject.objects.all() for subject in subjects_obj: SubjectMarks.objects.create( student = student, subject = subject, marks = random.randint(30, 100) ) except Exception as ex: print(ex) -
gunicorn issues with ModuleNotFoundError when deploying DRF project to Render due to
DRF project is running in development environment, expects to deploy to Render through yaml. The error message is as follows: ==> Running 'gunicorn core.wsgi:application' Traceback (most recent call last): File "/opt/render/project/src/.venv/bin/gunicorn", line 8, in <module> sys.exit(run()) ^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 67, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]", prog=prog).run() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 236, in run super().run() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() ^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/arbiter.py", line 58, in __init__ self.setup(app) File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/arbiter.py", line 118, in setup self.app.wsgi() File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() ^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() ^^^^^^^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app mod = importlib.import_module(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' gunicorn is called in Procfile as follows: web: gunicorn core.wsgi:application have tried to change the module name to django_project.core.wsgi:application but the … -
Django __main__.Profile doesn't declare an explicit app label
So I am working on Django and have not much experience with it yet. So far I've set up alright but now I've run into this error: RuntimeError: Model class main.Profile doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The INSTALLED_APPS looks like INSTALLED_APPS = [ 'tweets.apps.tweetsConfig', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'de Sitter vacua', ] I'm completely flabbergasted at this because I have no idea what the issue here is. I tried going through stackexchange Q&As and am clueless as to what the issue here is. Tried some solutions but it doesn't seem to be working. -
Coolify Django Deployment
I'm using Coolify and I want to deploy a Django application. I created an entrypoint.sh #!/bin/sh set -e echo "Running migrations..." python manage.py migrate echo "Collecting static files..." python manage.py collectstatic --noinput echo "Starting Gunicorn HTTP server..." exec gunicorn coolify.wsgi:application --bind 0.0.0.0:8000 I have a Dockerfile and it's all connected in a docker-compose.yml file with the db. The containers are running but I keep getting a Bad Request 400 response for any endpoint. -
Using jquery-editable-select in a Django App
This is my very first Django app so please don't be too harsh :-) I'm trying to use jquery-editable-select in my Django web App but I'm lost. https://github.com/indrimuska/jquery-editable-select According to this link, it seems like I need to install NPM first or Bower. I don't know what these are, can someone give me the basics from scratch ? Is it something to install via PIP like a python package ? -
What percentage of production backends use Raw SQL directly? [closed]
I was looking at Tech Empower’s web frameworks benchmarks.. I noticed that the highest performing versions of the frameworks used raw sql and the setups of the same frameworks that used an ORM or Query builder were significantly less performant (up to 5 times!). Look at actix-web, axum for example. So i’d like to know in a real, large big tech, production environment is raw SQL used and never ORMs or Query builders? -
How do I use JWT token authentication for API requests with rest_framework_simplejwt without needing user identification?
I have an API endpoint for my django application where I am allowing anyone with the JWT access token (valid for 15 mins) to use the API. But it doesn't work when I do a GET request with the access token. Authentication responds with "Token contained no recognizable user identification". Since anyone should be allowed to access the API with the token, I don't need to check if it's valid for any particular user. JWT is a requirement in the project to have stateless user authentication for other APIs. What is the correct/standard way to avoid this? Do I need a custom class or is there any better method to implement token authentication for APIs? -
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 …