Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authentication with Microsoft Azure AD in a multi-tenant app
Following the documentation, registered an application with Accounts in any organizational directory. The Tenant where the application resides is in "Default Directory" and has only one user, tiagomartinsperes@gmail.com. Also, the app has user assignment (as pointed out here) set to No After, created another Tenant (different directory) and invited the external user me@tiagoperes.eu. That's the user I'm getting troubles logging into the previously created app. Then, enable the OAuth2 support using social_core.backends.azuread.AzureADOAuth2 (from here). As I try to authenticate now, it works well with tiagomartinsperes@gmail.com but with me@tiagoperes.eu gives the following error Selected user account does not exist in tenant 'Default Directory' and cannot access the application 'a9a22676-8a1c-4297-95d3-8cd89553220e' in that tenant. The account needs to be added as an external user in the tenant first. Please use a different account. -
How do I affect a single looped element in Django html?
I'm building an app in Django, using Bulma for styling. I have a Polishes model that has a favorites field, which references the User (users can save polishes to their list of favorites): models.py: class Polish(models.Model): name = models.CharField(max_length=100) image = models.CharField(max_length=400, default="https://www.dictionary.com/e/wp-content/uploads/2018/02/nail-polish-light-skin-tone.png") brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='polishes') favorites = models.ManyToManyField(User, related_name='favorite', default=None, blank=True) def __str__(self): return self.name The add_favorites function checks to see if the polish has been added to the user's favorites already, and if it has, it removes the polish from the list. If it hasn't, it adds it: views.py: @ login_required def add_favorite(request, id): polish = get_object_or_404(Polish, id=id) if polish.favorites.filter(id=request.user.id).exists(): polish.favorites.remove(request.user.pk) else: polish.favorites.add(request.user.pk) return redirect('favorites_list') When I render the list of polishes, I'm using Bulma cards, displaying one polish per card. In the footer of the card, I want it to say 'Save to Favorites' if the polish is not in the user's list of favoties and 'Remove from Favorites' if it is. I'm struggling to get this piece to work. It will currently show either Save to Favorites or Remove from Favorites on all of the cards. Does anyone have any insight on how to render a different message only on those that are already … -
Django: TemplateSyntaxError - Could not parse the remainder
Exception Value: Could not parse the remainder: '['image/jpeg',' from '['image/jpeg',' Why am I getting this TemplateSyntaxError for the code below? {% for file in resource.files.all %} {% if file.file.content_type|lower in ['image/jpeg', 'image/png', 'image/gif'] %} <a class="resource-image" title="{{ file.id }}" href="{{ file.file.url }}"> <img width="100%" src="{{ file.file.url }}" alt="{{ file.id }} Image"/> </a> {% elif file.file.content_type|lower in ['video/mp4', 'video/wmv', 'video/mkv', 'video/x-flv', 'video/webm', 'video/mpeg'] %} <video width="100%" controls> <source src="{{ file.file.url }}"> </video> {% elif file.file.content_type|lower in ['audio/mp4', 'audio/m4a', 'audio/wav', 'audio/x-wav', 'audio/ogg'] %} <audio width="100%" controls> <source src="{{ file.file.url }}"> </audio> {% elif file.file.content_type|lower in ['application/pdf'] %} <!-- <embed src="{{ file.file.url }}" width="800px" height="2100px" /> --> {% endif %} <p class="small text-muted">{{ file.id }}</p> {% endfor %} I've checked the entire template file, and all the brackets are balanced. I can't find any syntax errors. -
Button function works randomly
so basically I am working on a flask app and everything is going well except one thing. I don't know why but my delete button works very randomly, sometimes on the second click, sometimes on the third click. Also I am very new to this website so I don't really know how to put a snippet but here's my code My html <section id="reponses" class="saisirReponse"> {% for i in range(2) %} <div class="elementReponse" id="{{'elementReponse'+((i+1)|string)}}"> <input type ="checkbox" name="{{'checkbox'+((i+1)|string)}}"/><span class="checkmark"></span> <textarea area-required="true" name = "{{'rep'+((i+1)|string)}}"></textarea> <button class = "bouttonSUPP" name="{{'btn'+((i+1)|string)}}" type="button" id="{{'btn'+((i+1)|string)}}" onclick="supp();">SUPP</button> </div> {% endfor%} </section> <input id="nb_quest" type="text" name="nb_quest" value="2"> <button class="bouttonLong" id="addDiv" type="button">Nouvelle réponse</button> Here's my function to add a response input (with seems to work well) (function (d) { "use strict"; d.querySelector("#addDiv").addEventListener("click", addDiv); function addDiv() { var p = d.createElement("div"); var x = d.createElement("INPUT"); var z = d.createElement("TEXTAREA"); var btn = document.createElement("BUTTON"); var t = document.createTextNode("SUPP"); var y =parseInt(document.getElementById("nb_quest").value)+1; x.setAttribute("type", "checkbox"); z.setAttribute("type", "text"); btn.appendChild(t); btn.name = "btn"+ y; btn.id = "btn"+ y; btn.setAttribute("class", "bouttonSUPP") p.setAttribute("class", "elementReponse"); btn.type = "button"; btn.setAttribute("onclick","supp();"); x.name = "checkbox" + y; x.id = "checkbox" + y; p.id = "elementReponse" + y; z.name = "rep" + y; z.id = "rep" + y; z.required = … -
Change color of a field in a table depending on how much time is left for the user to pay with Django
I am trying to change the color of a field in a table depending on how much time is left for the user to pay, if there are 7 days to pay it should change to yellow and if it is already the date of payment or already had to have paid it should change to red, the one that changes to red I got it, but I can't get it to change to yellow when there are 7 days to pay. This is my model and the def class payments (models.Model): client = models.OneToOneField(HealthQuests, on_delete=models.CASCADE, null=True, blank=True, verbose_name= 'Cliente') date = models.DateField(default=datetime.date.today, verbose_name= 'Fecha de facturación') payment_date = models.DateField(default=datetime.date.today, verbose_name= 'Fecha de pago') amount = models.FloatField(verbose_name='Monto de pago', default=0) def payment_yellow (self): return date.today() - payments.payment_date def payment_red (self): return date.today() And my html and the if <tbody> {% for obj in object_list %} <tr> <td><a href="update_payments/{{ obj.id }}" class="btn">{{ obj.client }}</a></td> <td>{{ obj.date }}</td> <td> {% if obj.payment_date <= obj.payment_red %} <div class="p-3 mb-2 bg-danger text-white">{{ obj.payment_date }}</div> {% elif obj.payment_yellow >= 7 %} <div class="p-3 mb-2 bg-warning text-white">{{ obj.payment_date }}</div> {% else %} {{ obj.payment_date }} {% endif %} </td> <td>{{ obj.amount }}</td> </tr> {% endfor %} … -
Django model foreign key cascade will not trigger delete
there two basic ways to do something when an instance gets deleted: Overwrite Model.delete Signal I used to reckon both of them serve the same purpose, just provides different ways of writing, but works exactly. However, in this occasion, I realise I was wrong: class Human(models.Model): name = models.CharField(max_length=20) class Pet(models.Model): name = models.CharField(max_length=20) owner = models.ForeignKey(Human, related_name="pet", on_delete=models.CASCADE) def delete(self, *args, **kwargs): print('------- Pet.delete is called') return super().delete(*args, **kwargs) h = Human(name='jason') h.save() p = Pet(name="dog", owner=h) p.save() h.delete() # nothing is shown Why Pet.delete Is not firing at Human.delete By the foreign cascade? Does I have to apply a signal on this? If so, would it cost more performance? I am building something very heavy, comment system, filter decent records and delete when the commented target get deleted, the comment model has many null-able foreign key fields, with models.CASCADE Set, only one of them is assigned with value. But in product delete view, I call product.delete Then triggers cascade, but comment.delete Is not firing. -
django template -TemplateSyntaxError
I am a beginner in Django world. When I try render my login.html template I'm facing this problem even there is a closing block. TemplateSyntaxError at /login/ Invalid block tag on line 12: 'else', expected 'endblock'. Did you forget to register or load this tag?` Here is my template {% extends 'base.html' %} {% block content %} {% if not request.user.is_authenticated %} <div style="margin-top: 30px"> <form method="POST"> {% csrf_token %} {% if error %} <p style="color: red">{{error}}</p> {% endif %} <div> <input type="text" name="username" placeholder="username" /> </div> <div> <input type="password" name="password" placeholder="password" /> </div> <button type="submit">Login</button> </form> </div> {% else %} <p> You're already logged in. Would you like to <a href="/logout/"> logout?</a> </p> {% endif %} {% endblock content%} -
Error instaling mysql : "metadata-generation-failed"
I am trying to install mysql on my virtual enviroment for DJango. I already have installled the conector: pip install mysql_connector Requirement already satisfied: mysql_connector in /home/djangoProject/my_env/lib/python3.8/site-packages (2.2.9) But, when I try to install mysql, I get an error: pip install mysql Collecting mysql Using cached mysql-0.0.3-py3-none-any.whl (1.2 kB) Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-1calve35/mysqlclient_8e8e5f7eb5c3471ab86bc7c3c2a339d7/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-1calve35/mysqlclient_8e8e5f7eb5c3471ab86bc7c3c2a339d7/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-1calve35/mysqlclient_8e8e5f7eb5c3471ab86bc7c3c2a339d7/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of 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. … -
Django-select2 not loading css maybe or just form looks bad
I downloaded and configured django-select2 and for some reason it looks disgusting not like it should be I check all settings and everything should be all right I guess its just some css files are not loading but in terminal everything`s good forms.py class WorkLogForm(forms.ModelForm): worklog_date = forms.DateField(label='Дата', widget=forms.DateInput( attrs={'type': 'date', 'class': 'form-control', 'placeholder': 'Введите дату'})) description = forms.CharField(label='Описание', widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Описание'})) contractor_counter = forms.ModelChoiceField( queryset=CounterParty.objects.all(), empty_label='', widget=ModelSelect2Widget( model=CounterParty, search_fields=['name__icontains'], ) ) contractor_object = forms.ModelChoiceField( queryset=ObjectList.objects.all(), widget=ModelSelect2Widget( model=ObjectList, search_fields=['name__icontains'], ) ) contractor_section = forms.ModelMultipleChoiceField( queryset=SectionList.objects.all(), widget=ModelSelect2Widget( model=SectionList, search_fields=['name__icontains'], ) ) class Meta: model = WorkLog fields = ( 'worklog_date', ) template.html {{ form.media.css }} <style> input, select { width: 100% } </style> <div class="container"> <form action="{% url 'home' %}" method="post"> {% csrf_token %} <div class="container mt-5"> {{ form.as_p }} </div> <button type="submit">Создать</button> </form> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> {{ form.media.js }} -
ViewSet class variable
Now I have the following logic implemented for a GET request in Django Rest Framework: class SomeViewSet(mixins.ListModelMixin, GenericViewSet): count = None def get_queryset(self): query_set = ... # some_logic self.count = query_set.count() return query_set def list(self, request, *args, **kwargs): response = super().list(request, *args, **kwargs) response.data = {'count': self.count, 'data': response.data} return response That is, the queryset is calculated according to complex logic, and it may contain a different number of objects that need to be returned in a GET request, since I don’t have access to the query_set variable inside the list function and I don’t want to copy the query_set calculation logic, I decided do it with a class variable. But still, the feeling that this is not very correct does not leave. What other options are there? -
How to install the node in Dockerfile?
I want to install the node v18 in on AWS Linux Prerequisite I have Django and frontend React system. So, I want to use node when installing frontend. If I use make Dockerfile such as From node:18 it works, but I want to use FROM python:3.9 to django work. Is it not a good idea to put Djang and React in the same container? Now my docker file is like this. FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN apt-get update WORKDIR /usr/src/app RUN apt-get install -y npm RUN pip install pipenv WORKDIR /usr/src/app/frontend_react RUN npm install --force RUN node -v //version 12 is installed RUN dnf module install nodejs:18/common RUN node -v RUN npm run build Howeber there is no dnf. How can I do this? -
How to serialize Django model with 2 or more foreign keys?
I have two models in models.py: from django.db import models from django.contrib.auth.models import User class Course(models.Model): name = models.CharField(max_length=100) description = models.TextField() cost = models.IntegerField() course_image = models.ImageField() def __str__(self): return self.name class PurchasedCourse(models.Model): purchased_by = models.ForeignKey(User, on_delete=models.CASCADE) purchased_course = models.ForeignKey(Course, on_delete=models.CASCADE) purchased_time = models.DateField(auto_now_add=True, blank=True) def __str__(self): return str(self.purchased_by) + ' => ' + str(self.purchased_course) My serializers.py so far: from rest_framework import serializers from .models import * class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = '__all__' class PurchasedCourseSerializer(serializers.ModelSerializer): class Meta: model = PurchasedCourse fields = '__all__' (it is just simple serializing) My views.py: from django.http import HttpResponse from requests import Response from .models import * from .serializers import CourseSerializer, PurchasedCourseSerializer from rest_framework import generics, viewsets from rest_framework.authentication import BasicAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated class CourseViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = (IsAuthenticated,) queryset = Course.objects.all() serializer_class = CourseSerializer class UserRelatedCourseViewSet(viewsets.ModelViewSet): queryset = PurchasedCourse.objects.all() serializer_class = PurchasedCourseSerializer def get_queryset(self): return PurchasedCourse.objects.filter(purchased_by__username=self.request.query_params['username']) So, question is how to get all Course objects(with all fields) that depends only on logged in user using PurchasedCourseSerializer? -
Django choosing which model to use in Django admin
I have three models models.py class Cluster(models.Model): blockOption= (('IMG', 'IMG'),('DESC', 'DESC'),) block = models.CharField(max_length= 100, choices=blockOption) order= models.IntegerField(null=True) post = models.ForeignKey(Post, verbose_name=('Link to Post'), on_delete=models.CASCADE) class Image(models.Model): src = models.ImageField(verbose_name=('Imagefile')) captions= models.CharField(max_length= 100, null=True) cluster = models.ForeignKey(Cluster, verbose_name=('Link to Post'), on_delete=models.CASCADE) class Description(models.Model): text=models.TextField(max_length=400) cluster = models.ForeignKey(Cluster, verbose_name=('Link to Post'), on_delete=models.CASCADE) and in admin.py class ImageAdminInline(TabularInline): extra = 1 model = Image class DescriptionAdminInline(TabularInline): model= Description @admin.register(Cluster) class ClusterAdmin(admin.ModelAdmin): inlines= (ImageAdminInline, DescriptionAdminInline) I have put ImageAdminInline and DescriptionAdminInline as inlines to ClusterAdmin. I' m planning to use ClusterAdmin to choose which admin I would be using. I hope it will be something similar to wagtail's streamfield(image above). Is there any solution that I could use without overriding admin template? I have tried using Ajax to just hide or show inlines but it was my first time to override django's template so it failed. -
login issue in https in django 1.6
In django 1.6 , when we tried to login using django login then after successful login , user is redirected to same login page. only change is , we change the http protocol to https. -
How do i get default date to my payload in django views
I am trying to create a payment API and part of my request body on postman is date but I want my programme to pick a default date now as my date so user do not need to enter date when using it. This is my serializer: PaymentSerializer(serializers.Serializer): code = serializers.RegexField(required=False, regex=r"[0-9A-Za-z]+") number = serializers.RegexField(required=False, regex=r"[0-9A-Za-z]+") hi_number = serializers.RegexField(required=False, regex=r"[0-9A-Za-z]+") ref = serializers.RegexField(required=False, regex=r"[0-9A-Za-z]+") date = serializers.DateTimeField(default=datetime.now) amount = serializers.DecimalField(max_digits=11, decimal_places=2) description = serializers.CharField() payload = { "integration_code" : integration_code, "payer_number" : request.data.get("payer_number"), "payment_number" : request.data.get("payment_number"), "payment_ext_reference" : request.data.get("tranref"), "payment_date" : self.get_serializer("payment_date"), "payment_amount" : request.data.get("payment_amount"), "payment_description" : request.data.get("payment_description"), } I need to be able to get the default in the payload but I cant seem to find my way around. -
Getting Logical Erro on Django ORM Query, the total is not matching with counts of all age group
` class OPDStatReportView(ListAPIView): filter_backends = [DjangoFilterBackend] serializer_class = OPDStatReportSerializer filterset_class = OPDStatReportViewFilterSet def get_queryset(self): query_dict = {} for k, vals in self.request.GET.lists(): if k != "offset" and k != "limit": if vals[0] != "": k = str(k) if k == "date_after": k = "created_date_ad__date__gte" elif k == "date_before": k = "created_date_ad__date__lte" query_dict[k] = vals[0] range_ages = ( {"lookup": "lt", "label": "0-9", "age": (10,)}, {"lookup": "range", "label": "10-14", "age": (10, 15)}, {"lookup": "range", "label": "15-19", "age": (15, 20)}, {"lookup": "range", "label": "20-59", "age": (20, 60)}, {"lookup": "range", "label": "60-69", "age": (60, 70)}, {"lookup": "gt", "label": ">70", "age": (70,)}, {"lookup": "gt", "label": "total", "age": (0,)}, ) aggr_query = {} for item in range_ages: age = item.get("age") lookup = item.get("lookup") label = item.get("label") if lookup == "lt": aggr_query[label] = Count(Case(When(age__lt=age[0], then=1))) elif lookup == "gt": aggr_query[label] = Count(Case(When(age__gte=age[0], then=1))) elif lookup == "range": aggr_query[label] = Count(Case(When(age__range=age, then=1))) queryset_old = ( CustomerVisit.objects.filter(follow_up_visit=True).annotate( age=(ExtractYear("created_date_ad") - ExtractYear("customer__user__dob_date_ad")) + (ExtractMonth("created_date_ad") - ExtractMonth("customer__user__dob_date_ad")) / 12 + (ExtractDay("created_date_ad") - ExtractDay("customer__user__dob_date_ad")) / 365, gender=F("customer__user__gender"), full_name=F("customer__user__full_name"), ) .values("gender") .annotate(**aggr_query) ).filter(**query_dict) queryset_new = ( CustomerVisit.objects.filter(follow_up_visit=False).annotate( age = (ExtractYear("created_date_ad") - ExtractYear("customer__user__dob_date_ad")) + (ExtractMonth("created_date_ad") - ExtractMonth("customer__user__dob_date_ad")) / 12 + (ExtractDay("created_date_ad") - ExtractDay("customer__user__dob_date_ad")) / 365, gender=F("customer__user__gender"), full_name=F("customer__user__full_name"), ) .values("gender") .annotate(**aggr_query) ).filter(**query_dict) queryset = { "old": … -
django channels with redis in WSL2
I have a redis installation running inside the windows subsystem for linux. It is working finde, but I cannot connect to it from django-channels. In my WSL I started redis and when using a normal terminal and python in Windows I can do for example: import redis c = redis.Redis("localhost", 6379, 0) c.keys("hello world") which leads inside of WSL2 to: 1675861647.991521 [0 [::1]:32934] "KEYS" "hello world" But when I am trying to do the same thing with the functions from the channels 4 tutorial I get stuck: $ python3 manage.py shell Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec 6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) import channels.layers channel_layer = channels.layers.get_channel_layer() from asgiref.sync import async_to_sync async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) async_to_sync(channel_layer.receive)('test_channel') the last call results in the following error: Task exception was never retrieved future: <Task finished name='Task-5' coro=<Connection.disconnect() done, defined at ...\venv\lib\site-packages\redis\asyncio\connection.py:723> exception=RuntimeError('Event loop is closed')> Traceback (most recent call last): File ...\venv\lib\site-packages\redis\asyncio\connection.py", line 732, in disconnect self._writer.close() # type: ignore[union-attr] File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\streams.py", line 337, in close return self._transport.close() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\selector_events.py", line 706, in close self._loop.call_soon(self._call_connection_lost, None) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 753, in call_soon self._check_closed() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 515, … -
Django: password reset not sending any email
I am trying to implement the 'password-reset' functionality using django. I set up my urls: path('account/reset_password/', auth_views.PasswordResetView.as_view(), name='reset_password'), path('account/reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('account/reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('account/reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), and the Settings.py: EMAIL_FILE_PATH = f"{BASE_DIR}/sent_emails" EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'someaccount@outlook.com' DEAFULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'somepassword' No emails are sent from the host email. I tried using console.EmailBackend and an email is indeed written, a working reset link is provided in the email. Everything works besides sending the email to the receiver address. Is there something wrong with the settings? -
in django-formset pypi package Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
when i try implement django-formset package selectize and preselect option show the error Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data plz help to solve this issue -
Restart Django server automatically at specific time
is there anyway to restart a local django server automatically everyday at a specific time? Thanks -
How to skip exception and continue to send the exception to sentry (Django)?
I want to be able to send errors to sentry while skipping the errors. The following can skip the error, but how can I make Sentry catch ValueError while achieving this? data = [1,2,3,4,5] new_data = [] def test(data): if d == 3: raise ValueError('error message') new_data.append(d) for d in data: try: test(data) except ValueError: continue -
Django - Let the user select multiple database entries and use that data in the next page
I would like to create a ListView, where the user can select certain database entries (see image below). The data connected to these entries would then be used to make plots. How do I create a form in which items of the ListView can be selected? So far I am able to create extra database entries in the CsvCreateView, but I don't know how to make a form in the ListView, where you can select the entries. Can anyone help me? The code: models.py: class CsvCreate(models.Model): file_name = models.FileField(upload_to='csvs') uploaded = models.DateTimeField(auto_now_add=True) selected = models.BooleanField(default=False) def __str__(self): return f"File id: {self.id}, uploaded at {self.uploaded}, activated: {self.activated}" def save_csvs(self): obj = self with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) values = [obj] dict_list = [] for i, row in enumerate(reader): if i < 3: pass else: for i in range(0,len(row)): values.append(row[i]) data_dict = dict(zip(parameters.parameters, values)) dict_list.append(data_dict) values = [obj] django_list = [Data(**vals) for vals in dict_list] Data.objects.bulk_create( django_list ) obj.activated = True obj.save() views.py: class CsvCreateView(View): model = CsvCreate form_class = CsvModelForm success_url = reverse_lazy('csvs:list_csvs') template_name = 'csvs/upload.html' def get(self, request): form = self.form_class() context = {'form': form} return render(request, self.template_name, context) def post(self, request): form = self.form_class(request.POST or None, … -
Does R support complex sampling designs?
Does R take into account the sampling technique used while making data analysis I got the analysis results but I didn't specify the sampling technique used which I think gives biased results -
How to get the top frequency
I have model class RawFrequencyDicts(Base): __tablename__ = "raw_frequency_dicts" id = Column(types.UInt64, primary_key=True) item = Column(types.String) lemmatized_text = Column(types.String) lemmatized_text_no_ordered = Column(types.String) frequency = Column(types.Int64) count_words = Column(types.Int64) mark_up = Column(types.Int64) domain_id = Column(types.Int64) language = Column(types.String) run = Column(types.Int64) run_desc = Column(types.String) created_at = Column(types.DateTime) updated_at = Column(types.DateTime) __table_args__ = (engines.MergeTree(),) And I have a choice of size. For example, when choosing 1000, I should get the top 1000 in frequency. Now I have a choice on the frequency itself. query_db = query_db.filter(model.frequency == int(params.frequency)) -
HTMX method not activated on select from list action in template (view does not see HTMX)
Good afternoon I have a micro Django app. In which I want to configure the ability to update the element using the [HTMX] method. I have a small form in a template - which is based on selecting an item from a list. The list is displayed well and the items appear in it. I connected this element in the template (selection list) with another element in the template - a graph. I'm trying to activate the [HTMX] method in Django code, but nothing happens. The code action does not go further. It feels like the view is not finding and activating the [HTMX] action. print("HTMX") - not action - print What could be the reason? You may be able to find some error in the code. I would be very grateful for any information. <hr/> <div class="row"> <div class="col-4"> <form> <select id="select-name" class="custom-select" name="select" autocomplete="off" hx-get="{% url 'tabl_2_htmx' %}" hx-target="#figure"> {% for select in selector %} <option value="{{select}}">{{select}}</option> {% endfor %} </select> </form> </div> <div id="figure" class="col-8"> {% include 'tabl_2_htmx_figure.html' %} </div> </div> def tabl_2_htmx(request): context = {} queryset_selector = Model_1.objects.all() last_row = queryset_selector.last() values_selector = last_row.name_1 select_1 = request.GET.get('select', values_selector) qs_select = Model_1.objects.filter(name_1=select_1).order_by('ud') date = [d.date for d …