Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Beginner Django: How to order a queryset by a property
I have a model: class Project(models.Model): title = models.CharField("Project title", max_length=128) start_date = models.DateField("Project start date", blank=True, null=True) end_date = models.DateField("Project end date", blank=True, null=True) @property def has_ended(self): return self.end_date is not None and self.end_date < timezone.now().date() And I want to order projects by two fields: start_date (desc) and also show projects that have not ended first. I know I can't ordery by a property, so I tried the following solution: class ProjectViewSet(viewsets.ModelViewSet): queryset = Project.objects.all().order_by("-start_date") queryset = sorted(queryset, key=lambda a: a.has_ended) serializer_class = ProjectSerializer permission_classes = [permissions.IsAuthenticated] which is the one that has already been answered on other posts with this question. However, I still get the following error: AttributeError: 'list' object has no attribute 'model' I also tried using Django annotations like this: queryset = Project.objects.annotate(has_ended=F('start_date')-F('end_date')).order_by('has_ended', '-start_date') But server returns this error: File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 78, in __iter__ django_1 | setattr(obj, attr_name, row[col_pos]) django_1 | AttributeError: can't set attribute I ran out of ideas on how to achieve the behavior I want. Can someone please give me a hand on that? -
Can't delete django-vote
I am working on a small university project. And I want to add voting to my app. I've decided to use django-vote for it. Here is the documentation: https://pypi.org/project/django-vote/ Upvoting works fine. The problem is whenever I want to delete existing vote it doesn't work. I saw this thread Django model: delete() not triggered but I didn't understand it. from vote.models import UP, DOWN ... book = get_object_or_404(Book, id=pk) ... if 'upvote' in request.POST: print("I clicked upvote") if book.votes.exists(request.user.id): print("upvote exists") book.votes.delete(request.user.id) else: book.votes.up(request.user.id) if 'downvote' in request.POST: print("I clicked downvote") if book.votes.exists(request.user.id, action=DOWN): print("downvote exists") book.votes.delete(request.user.id) else: book.votes.down(request.user.id) My model: class Book(VoteModel, models.Model): .... -
Pip Version Upgrade
pip install --upgrade pip I want to update with the command, but I am getting an error, the error is below. Hello, pip install --upgrade pip I want to update with the command, but I am getting an error, the error is below. https://prnt.sc/X_R-RZHqRnzt -
Django Create Model Instance from an Object
I am working on a Django Daily Saving App where Staff User can create Customer Account, and from the list of the Customer Accounts there is link for Deposit where staff user can add customer deposit. The issue is that after getting the customer id to the customer deposit view, I want to create get the customer details from the ID and create his deposit but anytime I try it I see: Cannot assign "<django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x00000129FD8F4910>": "Deposit.customer" must be a "Profile" instance See below my Models: class Profile(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) def __str__(self): return f'{self.customer.username}-Profile' class Account(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True) account_number = models.CharField(max_length=10, null=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f' {self.customer} - Account No: {self.account_number}' class Deposit(models.Model): customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Here are my views: def create_account(request): if searchForm.is_valid(): #Value of … -
how to create Python: Create automated strictly-designed multi-page .pdf report from .html
Can anyone design me Python: Create automated strictly-designed multi-page .pdf report from .html I have foudn this link usfeul but i need someone to do it for me please, here is the link: Python: Create automated strictly-designed multi-page .pdf report from .html not sure where to start? -
How can I detect a file is malicious during upload using VirusTotal API in Django Rest Framework
Working on a Django app. I have files being uploaded by users through the React front-end that end up in the Django/DRF back-end. How can I detect the file is malicious during upload using VirusTotal API in Django Rest Framework. Here are a few sources I am looking at. https://github.com/dbrennand/virustotal-python/blob/master/examples/scan_file.py -
How to get OTP in django admin panel only?
So i am working on REST API and doing KYC verification of aadhar card. This is my code: admin.py def save_model(self, request, obj, form, change): customer_id = obj.customer_id customer_object = Customer.objects.get(id=customer_id) first_name = customer_object.first_name middle_name = customer_object.middle_name last_name = customer_object.last_name customer_name = first_name + " " + last_name date_of_birth = customer_object.date_of_birth aadhar_card = obj.aadhar_card # Send OTP request url = AADHAR_AUTH_URL_OTP_SEND header = { "Content-Type":"application/json", "x-karza-key" : KARZA_TOKEN } payload = { "aadhaarNo": obj.aadhar_card, "consent": "Y" } result = requests.post(url, data=json.dumps(payload), headers=header, verify=False) result_json = result.json() request_id = result_json.get('requestId', '') # Verify OTP request if request_id: otp = input("Enter OTP received on registered mobile number: ") # ask the user to input the OTP url = AADHAR_AUTH_URL_VERIFIED_OTP payload = { "aadhaarNo": obj.aadhar_card, "consent": "Y", "requestId": request_id, "otp": otp } result = requests.post(url, data=json.dumps(payload), headers=header, verify=False) result_json = result.json() status = result_json.get('result', {}).get('message', '') # Save the results to the database if change: obj = aadhar_card.objects.get(pk=obj.pk) obj.aadhar_card = aadhar_card obj.aadhar_request_json = json.dumps(payload) obj.aadhar_response_json = json.dumps(result_json) obj.updated_by = request.user.id status_code = result_json.get('statusCode') if status_code == 101: obj.status = 101 # Verified else: obj.status = 3 # Not Verified obj.save() else: obj.aadhar_card = aadhar_card obj.aadhar_request_json = json.dumps(payload) obj.aadhar_response_json = json.dumps(result_json) obj.added_by = request.user.id … -
Django : use @property in success_url KO . while using it with get_success_url is OK (class based view)
I found a workaround for my issue but I need to know why the first above case doesn't work. I need to pass a parameter (reman_pk) to my view but when I try : class RepairCreateView(LoginRequiredMixin, CreateView): @property def reman_pk(self): return int(self.kwargs['reman_pk']) [...] success_url = reverse_lazy( 'reman:update-reman', kwargs={'pk': reman_pk}) [...] ... I got an error django.urls.exceptions.NoReverseMatch: Reverse for 'update-reman' with keyword arguments '{'pk': <property object at 0x10c20bbd0>}' not found. 1 pattern(s) tried: ['reman/update/(?P[0-9]+)/$'] But when in the same class based view I use : def get_success_url(self, **kwargs): if kwargs != None: return reverse_lazy('reman:update-reman', kwargs={'pk': self.reman_pk}) ... it's OK : an int is well passed in my URL. I tried to pass int(reman_pk) in the first method ... not better. I've already use @property in the past and always got a value (int/str) and not property object. -
what are the good python package for designing a search engine for database?
for example: End user enter a fuzzy input like "Telas", it should match with the database "Tesla" (Example: search a company from a large database) Autocomplete FuzzyMatch Can anyone help me to make a clear logic how to design this? Thank you so much~~ -
Python Django Module Connection promblem
What will i do when 3 modules in Python Django,they are User ,admin,super admin when super admin has power to do CRUD and User only View the product What will i do when 3 modules in Python Django,they are User ,admin,super admin when super admin has power to do CRUD and User only View the product -
How to implement a common function in Django for same URL pattern?
I want to have a common function for APIs' of the same pattern which should run that function and then the API's function. For example, I want to call the API - api/student/details which would return the user details and there are a lot of APIs with the pattern - api/student/*. For all the APIs with this pattern, I want to check if the user in request body is a valid student. And then it should call the function associated with api/student/details. How do I implement this in django? -
Django, Error 404, Not Found: /products/5 GIVE me Your hand
I have quation regarding Django, I tried to solve it myself during 2 days, but I haven't any ideas about this problem, can YOU help me? I read a book about Django, and there is example: urls.py from django.urls import re_path from django.urls import path from firstapp import views urlpatterns = [ re_path(r'^products/?P<productid>\d+/', views.contact), re_path(r'^users/(?P<id>\d+)/?P<name>\D+/', views.about), re_path(r'^about/contact/', views.contact), re_path(r'^about', views.about), path('', views. index), ] views.py from django.http import HttpResponse def index(request): return HttpResponse("<h2>Main</h2>") def about(request): return HttpResponse("<h2>About site</h2>") def contact(request): return HttpResponse("<h2>Contacts</h2>") def products(request, productid): output = "<h2>Product № {0}</h2>".format(productid) return HttpResponse(output) def users(request, id, name): output = "<h2>User</h2><h3>id: {О} " \ "Name:{1}</hЗ>".format(id, name) return HttpResponse(output) But after using this link(http://127.0.0.l:8000/products/5), I get this text: Using the URLconf defined in hello.urls, Django tried these URL patterns, in this order: ^products/?P\d+/ ^users/(?P\d+)/?P\D+/ ^about/contact/ ^about The current path, products/5, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. And this thing in terminal: Not Found: /products/5 [08/Feb/2023 12:17:13] "GET /products/5 HTTP/1.1" 404 2597 I need Your help! I tried to delet code about: re_path(r'^products/?P<productid>\d+/', views.contact), re_path(r'^users/(?P<id>\d+)/?P<name>\D+/', views.about), and I …