Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form class data in HTML Template
I am having a hard time getting my data from my form class into my html template. I have the following form class: class AnswerForm(forms.Form): def __init__(self, product, *args, **kwargs): super(AnswerForm, self).__init__(*args, **kwargs) self.fieldsets = {} for index, multiplier in enumerate(product.multiplier_list): rowLength = len(str(multiplier * product.multiplicand)) fieldsetFields = [] for i in range(5, 0, -1): field_name = f'field_{i}' self.fields[field_name] = forms.CharField( label=f'Answer {i}', widget=forms.TextInput(attrs={'class': 'answer-cell', 'tabindex': i, 'maxlength': 1}), required=i <= rowLength ) fieldsetFields.append(self.fields[field_name]) # Determine if row or result if index + 1 == len(product.multiplier_list): fieldsetId = f'fieldset-{product.type}result' else: fieldsetId = f'fieldset-{product.type}row' self.fieldsets[fieldsetId] = fieldsetFields And the form in my html template looks like this: <!DOCTYPE html> <html> <head> <title>Your Page Title</title> </head> <body> <form method="post"> {% csrf_token %} {% for fieldset_id, fields in form.fieldsets.items %} <fieldset id="{{ fieldset_id }}"> {% for field in fields %} <div class="form-group"> {{ field }} </div> {% endfor %} </fieldset> {% endfor %} <button type="submit">Submit</button> </form> </body> </html> I always receive the following output: django.forms.fields.CharField object at 0x0000013E23A3F730&g It worked before without the wrapped fieldset around it. -
DRF, Django Rest Framework. Render results as html
I need to have a page with simple html which shows not pure JSON but formatted data with meta information. I have this snipped of code. class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer router = SimpleRouter() router.register(r'product', ProductViewSet) urlpatterns = [ path('product/list/<int:pk>', ProductViewSet.as_view({'put': 'update'}), name='product-view'), path('product/', ProductViewSet.as_view({'get': 'list'}), name='product-view'), ] I have this as result. enter image description here -
pytelegrambotapi (telebot) how create pagination button i use django+telebot
enter image description here button.py from telebot import types def quarter_keyboard_uz(district_id): keyboard = types.InlineKeyboardMarkup() quarters = Quarter.objects.filter(district_id=district_id) for quarter in quarters: button = types.InlineKeyboardButton(quarter.name_uz, callback_data=f'quarter_{quarter.id}') keyboard.add(button) return keyboard bot.py import telebot elif current_state == "wait_district": user = BotUser.objects.get(chat_id=chat_id) district_id = call.data.split('_')[-1] district = District.objects.get(pk=district_id) user.district = district user.user_state = "wait_quarter" user.save() district.save() if current_language == 'UZ': bot.send_message(chat_id, "itimos o'z mfyigizni tanlang", reply_markup=quarter_keyboard_uz(district_id)) elif current_language == 'RU': bot.send_message(chat_id, "выберите общественное собрание вашего района", reply_markup=quarter_keyboard_ru(district_id)) elif current_state == "wait_quarter": user = BotUser.objects.get(chat_id=chat_id) quarter_id = call.data.split('_')[1] quarter = Quarter.objects.get(pk=quarter_id) user.quarter = quarter user.user_state = "wait_adress" user.save() quarter.save() if current_language == 'UZ': bot.send_message(chat_id, "itimos o'z adresingizni kiriting") elif current_language == 'RU': bot.send_message(chat_id, "Пожалуйста, введите ваш адрес") -
Django transaction and racing condition
I have the following Django code: with transaction.atomic(): items = Item.objects.all() for item in items: item.count += 1 Item.objects.bulk_update(items, ['count']) Does this code still contains the racing condition, despite the transaction? My understanding is that transaction doesn't lock the rows for read, so several threads running the same code might read the same count value so as a result it might not be incremented proper number of times? -
CSV File Downloaded as true.txt When Programmatically Triggered in JavaScript
I'm encountering a peculiar issue with downloading .csv files programmatically in a web application. When I click on a presigned URL (pointing to an AWS S3 object) directly from the console log or navigate to it manually, the .csv file downloads correctly with the proper filename and extension. However, when I try to trigger the download programmatically using JavaScript, the file gets downloaded as true.txt instead. Here's the frontend code snippet: const DownloadData = async () => { const token = localStorage.getItem("token"); const backendUrl_fetchdata = `http://127.0.0.1:8000/fetch-data/`; try { const response = await axios.post( backendUrl_fetchdata, { // request payload }, { headers: { Authorization: `Token ${token}`, }, withCredentials: true } ); if (response.status === 200 && response.data.urls) { response.data.urls.forEach(({ url, filename: expectedFilename }) => { console.log("Downloading file from URL:", url); if (expectedFilename.endsWith('.csv')) { // Attempt to download CSV const link = document.createElement("a"); link.href = url; link.setAttribute("download", expectedFilename); document.body.appendChild(link); link.click(); document.body.removeChild(link); } }); } } catch (error) { console.error("Error fetching URLs:", error); } }; Backend (Django): The backend generates presigned URLs for the files stored in AWS S3. These URLs are sent to the frontend as part of the response. Observations: The console.log accurately prints the URL, and clicking it initiates the … -
How to prevent OpenTelemtry traces from being printed to console?
I setup otel traces in my django app, by overriding Gunicorn's post_fork: import os from opentelemetry import trace from opentelemetry.exporter.otlp.proto.http.trace_exporter import \ OTLPSpanExporter from opentelemetry.instrumentation.django import DjangoInstrumentor from opentelemetry.instrumentation.logging import LoggingInstrumentor from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor def post_fork(server, worker): """Configue OpenTelemetry traces.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'solutions.settings') resource = Resource.create(attributes={ "service.name": "solutions" }) trace.set_tracer_provider(TracerProvider(resource=resource)) span_processor = BatchSpanProcessor( OTLPSpanExporter(endpoint="http://grafana-agent-traces.prometheus:4318/v1/traces") ) trace.get_tracer_provider().add_span_processor(span_processor) DjangoInstrumentor().instrument() LoggingInstrumentor().instrument(set_logging_format=True) Traces are successfully exported but are also printed to console. How to avoid that? I have tried to add this, but it has no effect: logging.getLogger("opentelemetry").setLevel(logging.WARNING) -
after changing a user password then the session got flushed
when i changed user password the user becomes anonymous means the session get flushed after.How to solve this issue. Why this happens when the password changed. the url has given below path('psswdReset/',psswdReset, name = 'psswd_reset') def psswdReset(request): if request.method == 'POST': new_psswd = request.POST.get('new_psswd') psswd = request.POST.get('psswd') password_is_correct = check_password(psswd, request.user.password) if password_is_correct: user = CustomUser.objects.get(id=request.user.id) user.password = make_password(new_psswd) user.save() messages.success(request, 'Password changed successfully!') return render(request,'User/userPsswdReset.html',{}) print('anonymouse', request.user.is_anonymous) return render(request,'User/userPsswdReset.html',{}) -
request.user always returns Anonymous user, even though request.META gives proper token when decoded in JWT it gives user_id
settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', "allauth.account.auth_backends.AuthenticationBackend", ] views.py def google_login_view(request): if not request.user.email: return HttpResponse("An email is required to login.", status=400) email_from_google = request.user.email try: user = User.objects.get(email=email_from_google, is_active=True) user_details = UserDetails.objects.get(email=email_from_google, is_active=True) except (User.DoesNotExist, UserDetails.DoesNotExist): return HttpResponse("User not found. Please register.", status=404) # generate_token_pair is defined in tokens.py access_token, refresh_token, access_token_exp, refresh_token_exp = generate_token_pair(user) current_time = datetime.now() access_token_expiration_timestamp = access_token_exp.timestamp() access_token_expiration_datetime = datetime.fromtimestamp(access_token_expiration_timestamp) # Check if the access token has expired if access_token_expiration_datetime < current_time: # Check if the refresh token is still valid if refresh_token_exp >= current_time: with transaction.atomic(): new_access_token, _, new_access_token_exp, _ = generate_token_pair(user) user.access_token = new_access_token user.save() # Log the user back in with the new access token login(request, user, backend='allauth.socialaccount.providers.google.backends.GoogleOAuth2') redirect_url = f"{settings.FRONTEND_REDIRECT_URL}?access_token={new_access_token}" return redirect(redirect_url) else: logout(request) # Ensure the user is logged out return redirect(settings.LOGIN_URL) else: login(request, user, backend='allauth.socialaccount.providers.google.backends.GoogleOAuth2') redirect_url = f"{settings.FRONTEND_REDIRECT_URL}?access_token={access_token}" return redirect(redirect_url) @authentication_classes([JSONWebTokenAuthentication]) @api_view(['POST']) def send_client_feedback_email(request, project_id): try: pass I have above setup Now when I Add PDB set trace in google login view I get a request.user of current logged in user. Now when I try to use my POST METHOD and when I add request.user It returns Anonymous … -
Plotting a bargraph in django using matplotlib
so here is my code. The bargraph is not showing in the dashboard page. This is my views.py code. expenses = Expense.objects.filter(user=user) incomes = Income.objects.filter(user=user) expense_date_list=[] amount_list=[] for expense in expenses: expense_date=expense.date.strftime("%Y-%m-%d") amount=expense.amount expense_date_list.append(expense_date) amount_list.append(amount) data=plt.bar(expense_date_list, amount_list) fig=plt.gcf() buf=io.BytesIO() fig.savefig(buf, format='png') buf.seek(0) data=urllib.parse.quote(base64.b64decode(buf.read())) context = { 'expenses': expenses, 'incomes': incomes, 'user':user, 'data':data`} return render(request, 'dashboard.html', context) -
Django:TemplateDoesNotExist at /accounts/login/
accounts/models.py from django.db import models from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms # Create your models here. class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True,label='email',error_messages={'exists':'This already exists'}) firstname = forms.CharField(required=True,label='firstname') lastname = forms.CharField(required=True,label='lastname') class Meta: model = User fields = ('firstname','lastname','username','email','password1','password2') def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) self.fields['firstname'].widget.attrs['placeholder'] = 'First Name' self.fields['lastname'].widget.attrs['placeholder'] = 'Last Name' self.fields['username'].widget.attrs['placeholder'] = 'Username' self.fields['email'].widget.attrs['placeholder'] = 'Email' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password' def save(self, commit=True): user = super(UserCreateForm,self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError(self.fields['email'].error_messages['exists']) return self.cleaned_data['email'] accounts/views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, auth from accounts.models import UserCreateForm from django.http import JsonResponse import random from django.core.mail import send_mail from django.conf import settings def registerpage(request): if request.method == 'POST': #login form = UserCreateForm(request.POST) if form.is_valid(): new_user = form.save() new_user = authenticate( username = form.cleaned_data['username'], password = form.cleaned_data['password1'], ) login(request, new_user) return redirect('home') else: #registration form = UserCreateForm() context = {'form':form} return render(request, 'store/auth/register.html', context) accounts/urls.py from django.urls import path,include from . import views urlpatterns = [ path('register', views.registerpage, name='register'), path('', … -
Need Help {{ Can't install mysql client }}
I'm just beginner for codeing and i try to connect Django with Mysql. But When i pip install myslqclient it error code below : ERROR: Command errored out with exit status 1: command: 'c:\users\admin\envs\envdjango\scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-ktopnk4j\\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-ktopnk4j\\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Admin\AppData\Local\Temp\pip-wheel-e994nvxe' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-ktopnk4j\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\ Complete output (23 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb creating build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\admin\envs\envdjango\scripts\python.exe' -u -c 'import io, … -
List Data from Multiple Models in Single HTML Table
I am trying to render data from 3 models in single html table. I have tried an error few times but failed. Below is my code. The workstation, printer and laptop have foreign of site ID. I want to list all the workstation, laptop and printer filter by a site. Below is my code: Models: class Site(models.Model): site_name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Site Name") site_address = models.CharField(max_length=30, blank=True, null=True, verbose_name="Site Address") def __str__(self): return self.site_name class Workstation(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Workstation Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") workstation_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Workstation Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name class Laptop(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Laptop Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") laptop_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Laptop Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name class Printer(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Printer Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") printer_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Printer Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name URL: urlpatterns = [ path('', views.SiteView.as_view(), name='site'), path('report/<sitename>', views.ReportView.as_view(), name='reportview'), ] Template 1: Site List <table> <tr> <th>Site</th> <th>Address</th> </tr> {% for site in site_list %} … -
Django join two or three models class into get request
models.py class CMDBInstanceProduct(models.Model): name = models.CharField(primary_key=True, max_length=50) def __str__(self): return self.name class CMDBStatus(models.Model): name = models.CharField(primary_key=True, max_length=50) def __str__(self): return self.name class Instance(models.Model): cmdbid = models.CharField(primary_key=True, max_length=15]) name = models.CharField(max_length=100) product = models.ForeignKey(CMDBInstanceProduct, on_delete=models.CASCADE) status = models.ForeignKey(CMDBStatus, on_delete=models.CASCADE) def __str__(self): return self.cmdbid class Instance_account(models.Model): fk_instance = models.ForeignKey(Instance, on_delete=models.CASCADE) name = models.CharField(max_length=200) views.py @api_view(('GET',)) def accountlist(request): accountlists = Instance_account.objects.all().prefetch_related('fk_instance') dict = {} records=[] for account_list in accountlists: list = {"name":account_list.name,"ci_name": account_list.fk_instance.ci_name ,"product": account_list.fk_instance.product} print (list) records.append(list) dict["pickup"]=records return JsonResponse(dict) my print(list) {'name': 'accountnameinstance', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} {'name': 'accountname', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} {'name': 'shareacc', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} i get an error TypeError: Object of type CMDBInstanceProduct is not JSON serializable Anyone could help on this to solve JSON serializable? -
Django - is there a way to shuffle and run only a subset of tests?
We are using Django with tests. We have in total about 6,000 tests which take about 40 minutes to run. Is there a way to shuffle the tests and run only 200 (randomly chosen) tests? This should be done with a command line parameter with the number 200 (which may change), since usually we run all the tests. -
Passing image to email in Django
I am attempting to send an email with a image embedded in the html code. I have verified that the image is being accessed but, I'm not able to see the image when I get the email. Trigger In Views: try: logo = base64.b64encode(open("dashboard/static/assets/abc.png", "rb").read()).decode() current_site = get_current_site(request) mail_subject = 'Welcome to AV Support' message = render_to_string('activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), 'logo':logo }) plain_message = strip_html(message) email = send_mail( mail_subject, message=plain_message,html_message=message, recipient_list=[ user.email], from_email=settings.EMAIL_HOST_USER ) email print('EMAIL SENT') except Exception as e: print('NO EMAIL SENT') print(e) Passing Logo To Email: <img src="data:dashboard/static/assets/abc.png;base64,{{logo}}" width="250" height="50" /> I have verified that the "logo" has data and the file is in the directory, the email comes up with a blank space. Could someone tell me what needs to be done? -
D5RF - Display something in HTML format before processing API requests
Django 5 - Rest Framework I am building a Django REST API project. I am currently dealing with a request that takes so long to process. I want to know if I could display something like an HTML Response before the request is processed, or just like a text saying: Loading... Please wait. Here is my code: from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView class SomeView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request): # I wanted to display it here. # ----------------- # Some process here # ----------------- # And then the actual response of the process. return Response(response, status=status.HTTP_200_OK) Any help would be appreciated, thank you. -
Usage of 'DIRS' attributes of TEMPLATES and static files in Django
I am new to Django and back-end development in a general. I am currently trying to build a very simple app. I saw some tutorials and am a little bit confused about 2 things: 1. What is the use of the attributes DIRS below in the picture. I knew that it was somehow used for "registering" templates but in my own apps, I didn't register it and somehow it still worked normally. Here is the picture of my settings.py and overall structure of my project: Project screenshot 2. What does it mean to "deploy" static files and why is it a better way than let Django automatically "deploy" the files by itself? (see picture below) Django docmumentation - https://docs.djangoproject.com/en/5.0/howto/static-files/ I really appreciate any thorough explanation on how things work since I am a beginner. I would be grateful if you guys provide any resources for Django practice as well! -
creating Event Loop scoped object (singleton) shared between coroutines Python
I want to create and store a singleton object such that, the variable necessarily has different object for different event loops (running concurrently) and for a single event loop, all coroutines executing inside the eventloop shares the same object. (what i want is contextVars which operate at the event loop scope. cannot use contextVars as coroutines have different contexts and hence different objects.) I do not control creation of event loops. I only have access to a coroutine (async def func()) executing inside an eventloop. Usecase: I am running a django server on gunicorn with uvicorn worker (afaik, different requests can run concurrently on the same worker at any time, but with differnet event loops). I want to share a connection pool, and the connection pool implementation binds itself to an eventloop (usage of asyncio lock, condition and queue) ), making global-variable like singleton erroneous. There are some other hacky solutions, like attaching the singleton to the request object, or attaching the singleton to the current event loop object, but the requirement seems like a fundamental usecase, and hopefully python has thought about it and solved the same. -
I can't get DRF-Spectactular to generate OpenApiParameter values for functions, only classes
Currently I'm working on a django project and I have an api_views.py file with the following view function: @api_view(["GET"]) @extend_schema( parameters=[ OpenApiParameter( name="jurisdiction", description="City for the query", required=True, type=str, default="Boston" ), ], description='More descriptive text', responses={200: OpenApiTypes.OBJECT}, # Define your response schema ) def distinct_address_autocomplete(request: Request): jurisdiction = request.GET.get("jurisdiction", "Boston") # Get distinct addresses for the city addresses = get_distinct_addresses(jurisdiction) # Filter addresses based on user's query filtered_addresses = addresses # Implement your filtering logic return Response(filtered_addresses) I've got it all set up correctly in all the settings.py and urls.py because it shows up in swagger, but incorrectly. The OpenApiParameter doesn't show up at all, it looks like this: But when I refactor this as a class like so: class DistinctAddressAutocompleteView(APIView): @extend_schema( parameters=[ OpenApiParameter( name="jurisdiction", description="City for the query", required=True, type=str, default="Boston" ), ], description='More descriptive text', responses={200: OpenApiTypes.OBJECT}, # Define your response schema ) def get(self, request: Request): jurisdiction = request.GET.get("jurisdiction", "Boston") # Get distinct addresses for the city addresses = get_distinct_addresses(jurisdiction) # Filter addresses based on user's query filtered_addresses = addresses # Implement your filtering logic return Response(filtered_addresses) The parameter shows up! What am I doing wrong on the function view? As best I can tell, I've set … -
Aggregate of OuterRef in Django Subquery
I have the following two models in Django 4.2: class Team(Model): members = ManyToManyField(...) ... class Size(Model): max_members = PositiveSmallIntegerField(blank=True, null=True) class Meta: ordering = [F('max_members').asc(nulls_last=True)] The idea is that each Team has a Size but I can't (as far as I know) model this as a SQL relation. But that's OK, we can get the size of a team as follows: Size.objects.filter(Q(max_members=None) | Q(max__gte=team.members.count())).first() However if I want to get the size associated with an entire queryset of teams at once, I am stuck. It seems like the following should work: teams.annotate( size=Subquery( Size.objects.filter( Q(max_members=None) | Q(max_members__gte=Count(OuterRef('members'))) ).values('pk')[:1] ) ) But this produces invalid SQL (we are using PostGres): SELECT "teams_team".* (SELECT U0."id" FROM "teams_size" U0 HAVING (U0."max_members" IS NULL OR U0."max_members" >= (COUNT("teams_teammembers"."user_id"))) ORDER BY U0."max" ASC NULLS LAST LIMIT 1) AS "size" FROM "teams_team" LEFT OUTER JOIN "teams_teammembers" ON ("teams_team"."id" = "teams_teammembers"."team_id") This is missing a GROUP BY teams_team.id and the HAVING clause should be WHERE. I can get some of the way there with some hacking: if I swap Count for Func(..., function='COUNT') then Django doesn't realise there is any aggregation and keeps the WHERE clause as it should do. But adding the grouping by hand, … -
pytest-django access to db when using pytest_generate_tests
Is there a way to be able to indirectly generate parameters via a database query when using pytest-django. For example if I have the following: Some code from here. pytestmark = pytest.mark.django_db def pytest_generate_tests(metafunc): if "foo" in metafunc.fixturenames: metafunc.parametrize("db", Foo.objects.filter(bar=1), indirect=True) def test_foo(load_all_foo, foo): # do things with all foo and test I am not sure what the deferred parametrization means here. Looking at code, pytest as well as pytest-django was not quite helpful. In the link above the example is still using an initial static list of params which then get converted to an actual db object. Where it would be useful to me is when I have a test that has a large setup and teardown time, plus the list of Foos can change and ocassionally fail. However rather than stopping and exiting when a test with one specific Foo fails I would like to continue and see the failed one in the report. I could sort of call metafunc.parametrize with an array of Nones and then yield a Foo in another fixture but that's not really a test. Any help would be greatly appreciated. -
Django BMI calculator not showing results
I'm trying to create a simple BMI calculator in django and for the life of me I cannot figure out why the app doesn't show the result after I press the "calculate" button. Does anyone have any insights on why this may be? views.py def calculate(response): if response.method == "POST": form = BMIform(response.POST) if form.is_valid(): weight = form.cleaned_data["weight"] height = form.cleaned_data["height"] bmi = weight / height ** 2 return render(request, "main/calculate.html", {"form": form, "bmi": bmi}) else: form = BMIform return render(response, "main/calculate.html", {"form": form}) models.py class BMImodel(models.Model): weight = models.FloatField() height = models.FloatField() def bmi(self): return weight / height ** 2 forms.py class BMIform(ModelForm): weight = forms.FloatField() height = forms.FloatField() class Meta: model = BMImodel fields = "__all__" html file for the calculations {% extends 'main/base.html' %} {% block content %} <h1><center>Calculate your BMI</center></h1> <style> .btn-primary { background-color: rgb(82, 200, 216); color: black; border: none; } .btn-primary:hover { background-color: rgb(0, 128, 145); color: white); } </style> {% csrf_token %} {{ form }} <div class="form-group col-md-4"> <button type="submit" name="calculate" class="btn btn-primary">Calculate</button> </div> {% if bmi %} <div class="form-group col-md-4"> <h5>BMI: {{bmi}}</h4> </div> {% endif %} </form> {% endblock %} I tried following several different tutorials but got lost somewhere along the … -
Filter blog posts using Category name with space in django
I have a website project in django with a blog app in it, I have category model for posts for filtering posts by category, the problem is when category name has space in it like "web development" my code works fine in development on my system, but after I deploy it on host nothing shows for category names which has white space in it. Here my urls.py for blog app: from django.urls import path from blog.views import * app_name ='blog' urlpatterns = [ path('', blog_view, name='index'), path('category/<str:cat_name>', blog_view, name='category'), path('author/<str:username>', blog_view, name='author'), path('search/', blog_search, name='search'), path('tag/<str:tag_name>', blog_view, name='tag'), path('<int:pid>', blog_single, name='single'), ] And here my view.py: def blog_view(request, **kwargs): posts = Post.objects.filter(status=1, published_date__lte=timezone.now()) if kwargs.get('cat_name'): posts = posts.filter(category__name= kwargs.get('cat_name')) if kwargs.get('username'): posts = posts.filter(author__username= kwargs.get('username')) if kwargs.get('tag_name'): posts = posts.filter(tags__name__in= [kwargs.get('tag_name')]) posts = Paginator(posts, 3) try: page_number = request.GET.get('page') posts = posts.page(page_number) except PageNotAnInteger: posts = posts.get_page(1) except EmptyPage: posts = posts.get_page(1) context = {'posts': posts} return render(request, 'blog/blog-home.html', context) I don't know what's happening on host but on localhost this request works fine and shows posts in that category: http://127.0.0.1:8000/blog/category/Web%20Development but on host the query doesn't work. Thanks -
Django on CPanel, can't install requirements.txt
I am trying to publish a Django web-application using CPanel. I created the python application but when I tried to install requirements.txt (using python version 3.8.18), I get tput: No value for $TERM and no -T specified error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata.╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. This is my requirements.txt asgiref==3.5.1 attrs==20.3.0 cachetools==5.3.0 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.12 cryptography==37.0.2 defusedxml==0.7.1 device-detector==5.0.1 distlib==0.3.4 Django==4.0.4 django-allauth==0.52.0 django-cors-headers==3.13.0 django-filter==22.1 django-user-agents==0.4.0 djangorestframework==3.13.1 filelock==3.7.1 geonamescache==1.5.0 google-auth==2.16.0 google-auth-httplib2==0.1.0 google-auth-oauthlib==0.8.0 httplib2==0.21.0 idna==3.3 jellyfish==0.9.0 joblib==1.2.0 lib50==3.0.4 Markdown==3.3.7 markdown2==2.4.3 networkx==3.0 numpy==1.24.2 oauthlib==3.2.2 pbr==5.9.0 pexpect==4.8.0 Pillow==9.1.0 pipenv==2022.7.4 platformdirs==2.5.2 pomegranate==0.14.8 ptyprocess==0.7.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.21 pygame==2.2.0 PyJWT==2.6.0 pyparsing==3.0.9 python3-openid==3.2.0 pytz==2022.1 PyYAML==5.4.1 regex==2022.10.31 requests==2.27.1 requests-oauthlib==1.3.1 rsa==4.9 scipy==1.10.1 six==1.16.0 sqlparse==0.4.2 stevedore==4.0.0 submit50==3.1.1 termcolor==1.1.0 ua-parser==0.16.1 urllib3==1.26.9 user-agents==2.2.0 virtualenv==20.15.1 virtualenv-clone==0.5.7 virtualenvwrapper==4.8.4 whitenoise==6.4.0 I have previously published web apps using Django and CPanel. For some reason, it will not install this time. How can I make the packages install properly? -
MSAL - Multi-Tenant Web APP - aad.config.json
We have successfully gotten our Django + Nginx + MySQL web app hosted and auth working through Azure with O365 for mailing using graph & O365 EWS. We have two different redirect URI's 1 for a dev environment and the other for prod. Both seem to work fine with both being up at the same time. The issue we are running into is the AAD.config.json, I authorized and got all the way through MFA with the external tenant account. On the APP Registration in hosted tenant Azure/Entra it shows supported account types: multiple organizations and verified the Publisher with the MPN ID. Whenever I try logging in with External Tenant (user's added to User & groups with default access role assigned) AuthCanceled at /social-auth/complete/azuread-oauth2/ Authentication process canceled During handling of the above exception (400 Client Error: Bad Request for url: https://login.microsoftonline.com/common/oauth2/token), another exception occurred: Below is the aad.config.json taken from https://github.com/Azure-Samples/ms-identity-python-samples-common/blob/main/aad.django.config.json { "type": { "client_type": "CONFIDENTIAL", "authority_type": "MULTI_TENANT", "framework": "DJANGO" }, "client": { "authority": "https://login.microsoftonline.com/common/oauth2/token" }, "auth_request": { "redirect_uri": null, "scopes": [], "response_type": "code" }, "flask": null, "django": { "id_web_configs": "MS_ID_WEB_CONFIGS", "auth_endpoints": { "prefix": "auth", "sign_in": "sign_in", "edit_profile": "edit_profile", "redirect": "redirect", "sign_out": "sign_out", "post_sign_out": "post_sign_out" } } }