Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotate performance Django
I've got the following models: class Match(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True, null=False) competition:Competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name='matches') season:Season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='season_matches', null=True, default=None) home:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_matches') away:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='away_matches') minute = models.IntegerField(default=None, null=True) period = models.CharField(max_length=25, default=None, null=True) datetime = models.DateTimeField() status = models.IntegerField() opta_match = models.OneToOneField(OptaMatch, on_delete=models.CASCADE, related_name='match', default=None, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Season(models.Model): id = models.AutoField(primary_key=True) competition:Competition = models.ForeignKey(to=Competition, on_delete=models.CASCADE, null=False, blank=False, related_name='seasons') start_date = models.DateTimeField(blank=False, null=False) end_date = models.DateTimeField(blank=False, null=False) name = models.CharField(max_length=255, null=True, default=None) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Event(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True) name = models.CharField(max_length=255) minute = models.IntegerField() player_name = models.CharField(max_length=255, null=True, default=None) extra_player_name = models.CharField(max_length=255, null=True, default=None) period = models.CharField(max_length=255) team:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='events') match:Match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='events') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) And I wrote the following annotations to a Match object: all_matches_qs = (Match .objects .filter(status=1) .select_related('home', 'away', 'competition', 'competition__country', 'season', 'opta_match') .prefetch_related( Prefetch("season", queryset=Season.objects.prefetch_related( Prefetch("season_matches", queryset=Match.objects.prefetch_related( Prefetch('statistics'))) )), Prefetch('events', queryset=Event.objects.select_related("team", "match").filter(name__in=["Corner", "Goal", "Substitution", "Yellow Card", "Red Card"])), ) .annotate(season_statistics_count=Count('season__season_matches__statistics')) .annotate(goals=Count('events', distinct=True, filter=(Q(events__name='Goal') & Q(events__team=F('home'))))) ) Executing this on about 25 records takes me about 3.75 seconds … -
Override a template of a Django package
How can I override a change_list.html template of a Django package e.g Django import export, in an existing Django app. E.g I want to override this package template, this is what I did in my project. path to the file : app/templates/import_export/change_list.html {% extends 'import_export/change_list_export.html' %} {% block object-tools-items %} <div> Hello there </div> {% endblock %} I get this error : -
How to render differently a django model object field on a html page?
My model object have a IntegerField but I want to be able to render it differently on my html page, like lets say the object IntegerField is 500000 I want to render it as 500 000$ on my html page. So Add a space before the last 3 number and add a $ at the end. I have a models with a IntegerField that look like this class Listing(models.Model): listing_price = models.IntegerField(max_length=100) In my view I extract the models like this def home(request): listing_object = Listing.objects.all() context = { "listing_object": listing_object, } return render(request, "main/index.html", context) I render the data like this {% for listing in listing_new_object %} {{listing.listing_price}} {% endfor %} -
I get TypeError: Response.__init__() got an unexpected keyword argument 'errors' when trying to send POST request
I have this view that creates a post when sending a POST request to the endpoint. class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() permission_classes = [IsAuthorOrReadOnly] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) user = request.user if serializer.is_valid(): serializer.save(author=user) return Response(data=serializer.data, status=status.HTTP_201_CREATED) return Response(errors=serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
add regex in url in django
I have a url link in my template django like this http://localhost/ville/selectville/name/?&name=Paris+-+75002 I need to remove all characters that are before the character "+" to have a url like this http://localhost/ville/selectville/name/?&name=Paris this regex do the job myurl = "http://localhost/city/selectville/name/?&name=Paris+-+75002" re.sub(r'\+.*', '', myurl ) but how to integrate it in my urls.py file with this path path('selectville/<str:name>/', VilleSelect.as_view(), name='ville_select'), thank you -
'project.Account' has no ForeignKey to 'project.Object': How to link an account model to the objects of a project?
I am trying to create an announcement website (All) that can be visible to others (the Users, for which I added an Account). For this I wanted to modify a little the user profile to add fields like telephone, email address... So I modified admin.py: from django.contrib import admin from .models import Todo, Account from django.contrib.auth.models import User class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class TodoAdmin(admin.ModelAdmin): readonly_fields = ('created',) inlines = (AccountInline, ) admin.site.unregister(User) admin.site.register(Todo, TodoAdmin) But got back: <class 'todo.admin.AccountInline'>: (admin.E202) 'todo.Account' has no ForeignKey to 'todo.Todo'. So I added a ForeignKey to Todo with account = models.ForeignKey(Account, on_delete=models.CASCADE): from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.CharField(max_length=100) firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=50) company = models.CharField(max_length=5) def __str__(self): return self.user.username class Todo(models.Model): title = models.CharField(max_length=100) datetime = models.DateTimeField() memo = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) important = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) account = models.ForeignKey(Account, on_delete=models.CASCADE) def __str__(self): return self.title But I still have the error. -
Django AccountActivationTokenGenerator login link works multiple times
I have been using AccountActivationTokenGenerator with Django SingIn and SignUp mechanism. class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.email_verified) ) account_activation_token = AccountActivationTokenGenerator() class PasswordResetTokenGenerator: ... def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, _ = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): # RemovedInDjango40Warning: when the deprecation ends, replace # with: # return False if not constant_time_compare( self._make_token_with_timestamp(user, ts, legacy=True), token, ): return False # Check the timestamp is within limit. if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT: return False return True I can successfully generate the link and email to user, and the user can use the link to login to the system. However the link works everytime the user clicks it. I just what the link to be valid only once, and when it is used, it should be invalidated for the next attempts. @api_view(['GET']) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def activate(request, uidb64, token, project_uuid='None', backend='videoo.registration.views.EmailBackend'): try: uid = force_text(urlsafe_base64_decode(uidb64)) User = … -
Store very little Integer in DB( PostgreSQL )
How to store very little Integer (4 bite) integer in my database? Hi.🙌 In my model I want to store a very little integer in my DB and I don't want to use SmallIntegerField. Because Django will store 16 Byte data in DB and it is too much for my need. How can I store 4 bite integer or even less in PostgreSQL? Thanks for your help.🙏 -
Django not recognized in virtual environment altough already installed when inside virtual environment
I've created a virtual environment in my PC(Windows). I've pushed the project to my git repository and now cloned it into my Mac. I activated the virtual environment, and tried running : python3 manage.py runserver This error is raised : ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I understand that the message sent from above is defined inside the manage.py if an ImportError is raised. What I'm trying to understand is how to make the virtual environment to include the python packages inside my project. I will explain what I've tried doing below. AFTER cloning the project, I've changed line in my pyvenv.cfg ... include-system-site-packages = true //previously = false ... I'm not sure what I did wrong while setting up the virtual environment and installing the packages while being IN the virtual environment. -
Event tracking on Django
I want to implement the function of recording people for a certain event. By type: The registered user sees the desired publication -> the "mark" button on the publication -> the data is saved in the database. I can't imagine how to do it, I didn't really find a solution. I would be glad to explain how this can be done on Django I didn't find a solution :( -
Django Azure rest framework call 500 server error
I have an django app that is running fine locally, but deployed to azure app service I am getting a 500 error when when it requests data. The app is being deployed in a docker container on an azure app service: URLs.py path('primaryexams/', TemplateView.as_view(template_name='xxxDB/primaryexams.html'), name='primaryExams'), path('primaryexamsdata/', views.PrimaryExamsView.as_view(), name='primaryexam_data'), views.py class PrimaryExamsView(generics.ListAPIView): serializer_class = PrimaryExamSerializer template_name='xxxDB/primaryexams.html' def get_queryset(self): return xxxPrimaryExamData.objects.all() def filter_for_datatable(self, queryset): # filtering search_query = self.request.query_params.get('search[value]') if search_query: lookups = Q(xxxid__first_name__icontains=search_query)|Q(xxxid__last_name__icontains=search_query)|Q(xxxid__xx_id__icontains=search_query) queryset = xxxPrimaryExamData.objects.filter(lookups) return queryset def list(self, request, *args, **kwargs): draw = request.query_params.get('draw') queryset = self.filter_queryset(self.get_queryset()) recordsTotal = queryset.count() filtered_queryset = self.filter_for_datatable(queryset) try: start = int(request.query_params.get('start')) except (ValueError, TypeError): start = 0 try: length = int(request.query_params.get('length')) except (ValueError, TypeError): length = 25 end = length + start serializer = self.get_serializer(filtered_queryset[start:end], many=True) response = { 'draw': draw, 'recordsTotal': recordsTotal, 'recordsFiltered': filtered_queryset.count(), 'data': serializer.data, } return Response(response) serializers.py class PrimaryExamSerializer(serializers.ModelSerializer): xxx_id = serializers.ReadOnlyField(source='xxxid.xxx_id') last_name = serializers.ReadOnlyField(source='xxxid.last_name') first_name = serializers.ReadOnlyField(source='xxxid.first_name') program_institution = serializers.ReadOnlyField(source='program_institution.institution_id') program_institution_name = serializers.ReadOnlyField(source='program_institution.institution_name') test_center_institution = serializers.ReadOnlyField(source='test_center_institution.institution_id', default='none') class Meta: model = AbnsPrimaryExamData fields = ( 'id','xxx_id','last_name','first_name','medical_school','program_institution','program_institution_name','graduation_year','test_center_institution' ) When I try to load the data I get an ajax error, and when I look at the request its getting a 500 server error: https://xxxinternal.azurewebsites.net/xxxDB/primaryexamsdata/?draw=1&columns%5B0%5D%...blah...blahh I have other views set … -
add a menu at draw marker in Folium?
I just add a menu onche you clic on the draw maker in draw.py toolbar I modified the html of the map using this code {{ this._parent.get_name() }}.on('draw:drawstart', function(e){ var type = e.layerType, layer = e.layer; if (type === 'marker') { console.log('drawing starting... ' + e.layer) // Do marker specific actions var html = "<br><li class=''><a class='' title='Ubicacion de mujeres'>Ubicacion de mujeres</a></li><br>" + "<li class=''><a class='' title='Zona de Violencia'>Zona de Violencia</a></li><br>" + "<li class=''><a class='' title='Poblaciones diversas'>Poblaciones diversas</a></li><br>"; document.querySelector(".leaflet-draw-actions").innerHTML += html; } }); What i'm trying to do is to add a menu so the user can create a marker depending on what type of layer you choose previously my idea es in this image here When i do this, the "cancel operation" does not work anymore and also i dont know how to change the color of the marker draggable that it is displayed. Any idea will be so helpful Thank you and regards! -
Django yfinance historical data
I'm running a private Django project, that might be summarized as an html page with a form composed of an input search, and a submit button. I want to be able to write any stock ticker ('AAPL') in the input, and to generate a chart following the request. However, I made all my tests outside the django framework. Here comes the tricky part. My code related to the data scrapping designed previously, does not work when executed in the Django framework. from yahoo_finance import Share def checkview(request): yahoo = Share('YHOO') stock = yahoo.get_open() return HttpResponse(room) Here is the error code. enter image description here Also, I tried a different approach with this code: import yfinance as yf tsla = yf.Ticker("TSLA") hist = tsla.history(period='1y') import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=hist.index,y=hist.Close, mode='lines')) fig.show() Can someone explain me, how can I solve the error ? And, how to install properly packages in the Django Framework. As an example, I will want to use Plotly going further in this project. Thanks ! -
How to generate a block of HTML code when submitting a form via Django
I would be grateful if someone explained to me how I could create a block of HTML Code when submitting a form with Django. For instance, if I want to upload an image, how could I automatically generate a HTML code block that puts the image inside a div with background and etc. Thanks! I searched a bit through documentation, and on the internet and couldn't find much about it. -
Psycopg2 error when i run my django project inside a container on windows
I have my django project in my pc (WIndows 11) and i want to put my project in a container, but when i am trying to run 'docker-compose build' in the terminal, i have always the same error. This is my Dockerfile FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN apt-get update && apt-get install -y libpq-dev RUN pip install --upgrade pip && pip install -r requirements.txt COPY . /code/ i am on that problem since monday. I have a 'pg-config' in my path and my django project works fine in my computer. I tried to use only 'psycopg2-binary' but i get a error that the 'psycopg2' package is not installed. I am on windows ! -
Django models: you need to display the menu and submenus
Can you please help. That's the question. I have a menu, the name of the menu is 'catr' and there is a submenu 'subcat' , I want to make the entire menu list output, and if the menu id matches the menu, then a subcategory is output, but I don't understand how to implement it.Help please.Sorry if I didn't explain it clearly, I hope you will understand, thank you in advance Here's what I tried to do enter image description here enter image description here -
Integrate pystray library with django in macOS
from documentation: run_detached(setup=None) Prepares for running the loop handling events detached. This allows integrating pystray with other libraries requiring a mainloop. Call this method before entering the mainloop of the other library. Depending on the backend used, calling this method may require special preparations: macOS Pass an instance of NSApplication retrieved from the library with which you are integrating as the argument darwin_nsapplication. This will allow this library to integrate with the main loop. source I do not understand this statement. How can I pass NSApplication instance to Icon class as argument. Where do I get this instance?. I am using macOS m1 -
How to properly run tests based on the APITestCase in Django?
When I use the python manage.py test command, in the console I see such a result: Ran 0 tests in 0.000s. How to run these UNIT tests? Also how to know the correctness of URLs which I use in the reverse function? project/urls.py: urlpatterns = [ path('', include('client.urls')), ] client/urls.py: urlpatterns = [ path('clients', ClientView.as_view()), path('clients/<int:pk>', ClientView.as_view()), ] client/tests.py: from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from client.models import Client class ClientTestCase(APITestCase): def setUp(self): self.data = { "first_name": "Jimmy", "last_name": "Smith", "email": "jimmysmith@gmail.com" } self.response = self.client.post( reverse('client:client-list'), self.data, format="json" ) def create_client(self): self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertEqual(Client.objects.count(), 1) self.assertEqual(Client.objects.get().first_name, 'Jimmy') def get_clients(self): response = self.client.get(reverse('client:client-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Client.objects.count(), 1) def get_client(self): client = Client.objects.get() response = self.client.get( reverse('client:client-detail', kwargs={'pk': client.id}), format="json" ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, client) def update_client(self): client = Client.objects.get() new_data = { "first_name": "Bob", "last_name": "Marley", "email": "bobmarley@gmail.com" } response = self.client.put( reverse('client:client-detail', kwargs={'pk': client.id}), data=new_data, format="json" ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Client.objects.get().first_name, 'Bob') def delete_client(self): client = Client.objects.get() response = self.client.delete( reverse('client:client-detail', kwargs={'pk': client.id}), format="json" ) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(Client.objects.count(), 0) -
Cannot save a modelform using Django Crispy Forms
I cannot save my form because the payload is not formatted correctly.. I'm using HTMX for rendering the form in a modal here's the code: forms.py class RecipeForm(forms.ModelForm): title = forms.CharField( label="Titolo", ) method = forms.CharField( widget=forms.Textarea(), label="Procedimento", ) tags = CustomTagsMultipleChoice( queryset=Tag.objects.all(), widget=forms.CheckboxSelectMultiple, label="Tag", ) hero_image = forms.ImageField( label="Immagine", ) class Meta: model = Recipe fields = ["title", "method", "tags", "hero_image"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs = { "hx-post": reverse_lazy("recipes:recipe_create"), "hx-target": "#dialog", } self.fields["tags"].required = False self.fields["method"].required = False self.fields["hero_image"].required = False self.fields["tags"].label = False self.helper.layout = Layout( FloatingField("title"), FloatingField("method", css_class="fl-textarea"), "hero_image", InlineCheckboxes("tags"), Div( Submit("submit", "Salva"), Submit("button", "Cancella", css_class="btn btn-danger", data_bs_dismiss="modal"), css_class="text-end", ), ) views.py @login_required def recipe_create(request): if request.method == "POST": form = RecipeForm(request.POST,request.FILES) if form.is_valid(): form.save() return HttpResponse(status=204, headers={"HX-Trigger": "recipeSaved"}) form = RecipeForm(request.POST,request.FILES) context = {"recipe_form": form} return render(request, "recipes/partials/_recipe_create.html", context) form = RecipeForm() context = {"recipe_form": form} return render(request, "recipes/partials/_recipe_create.html", context) _recipe_create.html {% load crispy_forms_tags %} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Aggiungi una ricetta</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button> </div> <div class="modal-body"> {% crispy recipe_form %} </div> </div> if I print request.POST I get this badly formatted payload <QueryDict: {'------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name': ['"submit"\r\n\r\nSalva\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="csrfmiddlewaretoken"\r\n\r\n0DWNbShUV0r8mFSPUNQaSQapC38FQFrMeOtmqFY64H4x3ReOuG7suKqUip7sSpqv\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="title"\r\n\r\ntest\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g\r\nContent-Disposition: form-data; name="method"\r\n\r\n\r\n------WebKitFormBoundaryIbg12MlAkITtzU0g--\r\n']}> the form … -
Why Nginx is Serving my django app in port 8000 instead of 80?
i have created a app using django https://github.com/pyalz/video_app . I run this application now using django compose build django compose up . When i open http://0.0.0.0:8000 its coming with static files. when i open http://0.0.0.0:80 its not showing me static files **Docker compose ** version: '3.7' services: django_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - django_gunicorn volumes: static: Docker File FROM python:3.10.0-alpine RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./video_app /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] Entry.sh #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input DJANGO_SUPERUSER_PASSWORD=$SUPER_USER_PASSWORD python manage.py createsuperuser --username $SUPER_USER_NAME --email $SUPER_USER_EMAIL --noinput gunicorn video_app.wsgi:application --bind 0.0.0.0:8000 NGINX Docker file FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf Default.conf upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } } enter image description here enter image description here Could you please help me resolve this issue -
Django How add math result from form in Model.objects.create
I'm trying to divide one value by another from the form and write the result. But it doesn't work def add_project(request): form_address = AddressForm(request.POST or None) form_project = ProjectForm(request.POST or None) form_detail = ProjectDetailForm(request.POST or None) if request.method == 'POST': if form_address.is_valid() and form_project.is_valid() and form_detail.is_valid(): address_clean = form_address.cleaned_data project_clean = form_project.cleaned_data detail_clean = form_detail .cleaned_data a = Address.objects.update_or_create(**address_clean) p = Project.objects.create( address = a[0], manager = request.user, file = project_clean['file'], sq = project_clean['sq'], rent_tax = project_clean['rent_tax'] ) sq_price = project_clean['rent_tax'] / project_clean['sq'] ProjectDetail.objects.create( project = p, sq_price = sq_price, **detail_clean ) return redirect("crm:homepage") context = {'form_address':form_address, 'form_project':form_project, 'form_detail':form_detail,} return render(request, 'crm/add_project.html', context) I try sq_price = project_clean['rent_tax'] / project_clean['sq'] The print command outputs a number. But Django says it is an error: create_method..manager_method() got multiple values for keyword argument 'sq_price' Traceback project_clean { 'file': 'https://aaa.com/zzz.zip', 'rent_tax': 1548, 'sq': Decimal('325')} -
Django Social account is redirected to gitlab.com instead of gitlab.local
Hello I have installed gitlab locally on my own server. I am trying to make django settings with django social app with the steps specified in the readthedocs readthedocs link to enter through readthedocs gitlab accounts, but for some reason my server connects to gitlab.com when I say connect with gitlab via readthedocs instead of https://gitlab.local. I need to redirect it to my server. How do I do this, the django docs say the following steps but I have no idea how and where to change it. https://django-allauth.readthedocs.io/en/latest/providers.html#gitlab GitLab The GitLab provider works by default with https://gitlab.com. It allows you to connect to your private GitLab server and use GitLab as an OAuth2 authentication provider as described in GitLab docs at http://doc.gitlab.com/ce/integration/oauth_provider.html The following GitLab settings are available, if unset https://gitlab.com will be used, with a read_user scope. GITLAB_URL:Override endpoint to request an authorization and access token. For your private GitLab server you use: https://your.gitlab.server.tldSCOPE:The read_user scope is required for the login procedure, and is the default. If more access is required, the scope should be set here. which file do I need to modify to make the following setting or what is the way to do it? Example: SOCIALACCOUNT_PROVIDERS … -
Conditional Aggregation of Foreign Key fields
I would like to get the count of foreign key objects with django, the foreign key itself will change conditionally. So, something like the example below. Game.objects.annotate( filled=models.Case( models.When( GreaterThan( models.F("size_max"), ( models.Count( models.Case( models.When( participant_type=1, then="players" ), models.When( participant_type=2, then="teams", ), ), ), ), ), then=1, ), default=0, ) ) What I'd like to achieve is this: players and teams are reverse foreign keys to Game. I want to check whether the size_max field of Game exceeds the count of players or teams depending on the participant_type. How would I go about achieving this? Any help would be appreciated. The above query results in an error - it introduces a GROUP BY with the model name in it. So, something like GROUP BY ('Game'), "game"."id" which I have no clue why this happens. -
Django RestFramework - convert list to dict
I'm translating an API in Java to DRF and the consumption will be in a data.py Using DRF API ind = requests.get(base_url + "get_ind?ind_id={}".format(ind)) print(ind.json()) [{ "id": 1, "ind_id": 1, "co_ind": "Some String", "no_ind": "Some String", "ds_ind": "Some String", "ds_not_ind": "", "uni_id": 1, "per_id": [ { "id": 7, "no_per": "Some String", "tip_var": "", "co_per": "Some String", "no_cat": "", "per_id": 7, "uni_id": 1 }, { "id": 9, "no_per": "Some String", "tip_var": "", "co_per": "Some String", "no_cat": "", "per_id": 9, "uni_id": 1 }, ], "co_mod": "Some String" }] I want: Using Java API ind = requests.get(base_url + "get_ind?ind_id={}".format(ind)) print(ind.json()) { "id": 1, "ind_id": 1, "co_ind": "A", "no_ind": "DOMÍCILIOS QUE POSSUEM EQUIPAMENTO TIC", "ds_ind": "Total de domicílios", "ds_not_ind": "", "uni_id": 1, "per_id": [ { "id": 7, "no_per": "Proporção de domicílios que possuem equipamentos TIC", "tip_var": "", "co_per": "DIC_TV", "no_cat": "", "per_id": 7, "uni_id": 1 }, { "id": 9, "no_per": "Proporção de domicílios que possuem equipamentos TIC", "tip_var": "", "co_per": "DIC_RADIO", "no_cat": "", "per_id": 9, "uni_id": 1 }, ], "co_mod": "A" } This is the view.py: class GetIndFilter(SearchFilter): def filter_queryset(self, request, queryset, view): queryset = super().filter_queryset(request, queryset, view) ind_id = request.GET.get('ind_id') if(ind_id != ''): result = Inds.objects.filter(ind_id = ind_id) return result class GetIndViewSet(viewsets.ModelViewSet): queryset … -
Подключение приложения с github в django-проект [closed]
Всем привет, я нуб. Делаю свой проект на Django в свободное от работы время. Я хочу подключить в строку для ввода адреса на странице плагин, который по опенсорсу распространяется на гитхабе. Он использует jquery. Я не могу понять куда мне его втыкать в проекте и где что указывать, чтобы было весело. Просмотрев несколько видео и прочитав несколько статей, я клонировал гит репозиторий в папку со статикой в джанго, а в шаблоне указал к ней путь. И попробовал метод из этого стороннего приложения применить к инпуту. Начал с того, что получаю инпут, около которого текстом написан мой метод, начал шевелить подключение JS кода к шаблону, избавился от ошибок и пришёл к тому же результату. Пожалуйста, помогите, я за деньги готов по зуму созвониться чтобы получить ответ. {% load static %} <!DOCTYPE html> <html> <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script> <script src={% static 'gameslist/jquery/jquery.fias.min.js' %} ></script> <input type="text"> $('text').fias({ oneString: true }); </html> Получаю на странице это enter image description here