Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webhook Django - Local POST requests with Postman fail
I'm trying to receive webhooks within my Django app. I have created my app as follows: models.py : class Webhook(models.Model): """ Class designed to create webhooks. """ name = models.CharField(_('Nom'), max_length=50) url = models.URLField(_('URL')) event = models.CharField(_('Event'), max_length=50) active = models.BooleanField(_('Actif'), default=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING, blank=True, null=True) id_string = models.CharField(_('ID'), max_length=32, blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): current_url = Site.objects.get_current().domain self.id_string = get_random_string(length=32, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') self.url = f'{current_url}/{self.company.id}/{self.id_string}' super(Webhook, self).save(*args, **kwargs) views.py: @csrf_exempt def webhook(request, pk, ref): if request.method == 'POST': print(request.body) return HttpResponse(request.body, status=200) else: return HttpResponse('Failed') urls.py: urlpatterns = [ path('webhook/<int:pk>/<str:ref>', webhook, name='webhook'), ] At the moment, I'm running my app locally. When I create a webhook object, I have the following URL : 127.0.0.1:8002/webhook/4/maPYUvcYZROq60cwJioIrqV5Y5OqXRiy When I try the following POST request: I always end up with the response "Failed". I don't understand why. -
Django converter type works for values >= 2 but not for 0 or 1
I am following a Django course on Udemy and have encountered this issue when trying to use the HttpResponseRedirect for the most basic of tasks. views.py looks like this: from django.shortcuts import render from django.http.response import HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect from django.urls import reverse articles = { 'food': 'Food page', 'politics': 'Politics page', 'sports': 'Sports page', 'finance': 'Finance page', } def news_view(request, topic): try: result = articles[topic] return HttpResponse(result) except KeyError: print(type(topic)) raise Http404('404 GENERIC ERROR') # else: # articles[topic] = f"{(topic.title())} page" # return HttpResponse(articles[topic]) def add_view(request, num1, num2): # domain.com/first_app/3/4 --> 7 result = num1 + num2 return HttpResponse(str(result)) # domain.com/first_app/0 --> food def num_page_view(request, num): topics_list = list(articles.keys()) topic = topics_list[int(num)] return HttpResponseRedirect(reverse('topic-page', args=[topic])) urls.py looks like this: from django.urls import path from . import views # first_app/ urlpatterns = [ # path('<int:num1>/<int:num2>/', views.add_view), path('<int:num>', views.num_page_view), path('<str:topic>/', views.news_view, name='topic-page'), ] I tried typing in all indexes in the browser, 1 by 1, and I get the expected result for anything above 1: http://127.0.0.1:8000/first_app/2 redirects properly to http://127.0.0.1:8000/first_app/sports/ and so on up to 8 (I haven't populated the dictionary with more than 8 pairs). http://127.0.0.1:8000/first_app/0 and http://127.0.0.1:8000/first_app/1 return the custom 404 built into the "news_view" function, and the … -
Django view to export vsdx format
I am currently working on a view that needs to export visio files. I already have a view that exports doc files (see below), but not sure how to do that to return vsdx file as response from docx import Document def get(self, request, *args, **kwargs): document = Document() document.add_heading('Document Title', 0) response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response I'm aware that I need to update the content_type, and the way I need to open the file, but I've tried a few things and the response provided doesn't seem to open properly Any help is appreciated from vsdx import VisioFile def get(self, request, *args, **kwargs): filename = 'test.vsdx' response = HttpResponse(VisioFile(filename), content_type="application/vnd.visio", status=status.HTTP_200_OK) response["Content-Disposition"] = f"attachment; filename=temp.vsdx" return response -
django rest_framework ValueError: Cannot assign "'xx'": "xxx" must be a "xxx" instance
I'm trying to create an API to insert the current user's officeid but failed this is my models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) userid = models.CharField(null=True, max_length=9) officeid = models.CharField(max_length=50, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' I did try to create this def perform_create(self, serializer): serializer.save(office=self.request.user.officeid) but it's giving me an error -
How to deploy django based application in AWS EC2 kubernetes cluster using loadbalancer and map the IP to DNS like godaddy
i have configured Kubernetes cluster in the AWS EC2 instance and using Kubernetes load-balancers exposed my docker based django project app. Please advise unable to connect Postgresql database using pgadmin. NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME master-node Ready control-plane 22d v1.25.3 172.31.0.161 Ubuntu 18.04.6 LTS 5.4.0-1084-aws containerd://1.5.5 worker01 Ready 22d v1.25.3 172.31.0.203 Ubuntu 18.04.6 LTS 5.4.0-1088-aws containerd://1.5.5 After Execute below command error: ** Kubectl cluster-info dump** The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 116, in call response = self.process_request(request) File "/usr/local/lib/python3.9/site-packages/django_tenants/middleware/main.py", line 39, in process_request tenant = self.get_tenant(domain_model, hostname) File "/usr/local/lib/python3.9/site-packages/django_tenants/middleware/main.py", line 27, in get_tenant domain = domain_model.objects.select_related('tenant').get(domain=hostname) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 431, in get num = len(clone) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 262, in len self._fetch_all() File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 51, in iter results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/usr/local/lib/python3.9/site-packages/django_tenants/postgresql_backend/base.py", line 135, in _cursor cursor = super()._cursor() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() … -
Creating a dynamic input field with Django
I'm new to Django and when I press a button on a form, I want to dynamically create a new input field and save it to the database. I have no idea how to do this. Can you help with this? Since I don't know exactly how to do something, I couldn't try anything, but I know the form I need to create in html and javascript, but I have no idea how to save it to the database. -
Error when running "python manage.py runserver"
I'm doing a project where we are using Django to make a sales website. The day we started doing the project, it worked perfectly and there were no errors, but today i opened the project and tried to run the server and got this errors: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\gabri\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\gabri\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\gabri\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\stdimage\__init__.py", line 1, in <module> from .models import JPEGField, StdImageField # NOQA ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gabri\Documents\Django\prj_lojavirtual\venv\Lib\site-packages\stdimage\models.py", line … -
Django/React CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins
I am building a web application using Django for the backend, RestApi for information transfer, and ReactJs for the frontend. When I run a POST request, in which I send data from a form, I get an error: "CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins."This means that Django recognizes the question but rejects it for some unknown reason. ReactJs is using a proxy to work with server data. I've read already solved articles on forum such as article 1, article 2, article 3, article 4, their solutions didn't help me. My request from ReactJs: const item = {tittle : data.target.tittle.value, description : data.target.description.value}; axios({ headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, method : "post", url : "api/articles/", data : item }).catch((e) => {console.log(e)}) Setting.py: CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8000' ] ALLOWED_HOSTS = [ 'localhost', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', ] CORS_ORIGIN_ALLOW_ALL = True class for processing requests in views.py: class ArticleList(generics.ListCreateAPIView): def post(self, request, format=None): serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, format=None): snippets = Articles.objects.all() serializer = ArticleSerializer(snippets, many=True) return Response(serializer.data) -
In Django create a model method which determines an id for all objects that share the same foreign key
Kind of new to Django and while trying to create my first own project, i stumbled upon a problem. I have two different model classes: Star and Planet. Each planet has a foreignkey which belongs to a Star. Now I would like to have a field for Planet, which is basically the id/pk for its star system that is given on creation/discovery. All known planets of the star system already have their star system id and thus the newly created/discovered planet would require an id that is incremented on the last id that was given. Id Star Id in Star System Name 1 Sun 1 Neptune 2 Alpha Centauri 1 Hoth 3 Alpha Centauri 2 Coruscant 4 Sun 2 Earth 5 Sun 3 Jupiter 6 Alpha Centauri 3 Yavin4 7 Sun 4 Venus My models are looking like this models.py: class Star(models.Model): name = models.CharField(max_length=200) class Planet(models.Model): name = models.CharField(max_length=200) star = models.ForeignKey(Star, on_delete=models.CASCADE) def starSystemPlanetId(self): What could work in here? This new Id should be available to be called in a template like this: {% for planets in object_list %} <li> <p>Planet {{planets.name}} is the Nr. {{planets.customer_id}} planet of the star system</p> </li> {% endfor %} I have learned … -
How to calculate aggregate sum with django ORM?
I'm trying to group_by() data based on dates and with every day I want to calculate Count on that day also the total count so far. Sample output I'm getting: [ { "dates": "2022-11-07", "count": 1 }, { "dates": "2022-11-08", "count": 3 }, { "dates": "2022-11-09", "count": 33 } ] Sample output I'm trying to achieve: [ { "dates": "2022-11-07", "count": 1, "aggregate_count": 1 }, { "dates": "2022-11-08", "count": 3, "aggregate_count": 4 }, { "dates": "2022-11-09", "count": 33, "aggregate_count": 37 } ] -
django.core.exceptions.ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] problem
In 'models.py' i have this fields. first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) date_of_brith = models.DateField(default='YYYY-MM-DD', null=True) email = models.EmailField(max_length=50, null=True) When i try to migrate. I get this error. I tryed to delete also the field and I still have the same error django.core.exceptions.ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
Django can't close persistent Mysql connection
Problem: Our Django application includes zipping large folders, which takes too long (up to 48 hours) so the Django connection with the database gets timed out and throws: "MySQL server has gone away error". Description: We have a Django version==3.2.1 application whose CONN_MAX_AGE value is set to 1500(seconds). The default wait_timeout in Mysql(MariaDB) is 8 hours. ExportStatus table has the following attributes: package_size zip_time Our application works this way: Zip the folders set the attribute 'package_size' of ExportStatus table after zipping and save in the database. set the attribute 'zip_time' of ExportStatus table after zipping and save in the database. Notice the setting of the columns' values in database. These require django connection with database, which gets timedout after long zipping process. Thus throws the MySQL server gone away error. What we have tried so far: from django.db import close_old_connections` close_old_connections() This solution doesn't work. Just after zipping, if the time taken is more than 25 minutes, we close all the connections and ensure new connection as: from django.db import connections for connection in connections.all(): try: # hack to check if the connection still persists with the database. with connection.cursor() as c: c.execute("DESCRIBE auth_group;") c.fetchall() except: connection.close() connection.ensure_connection() Upon printing … -
Django: Send mail to admin on every error raised
I have a project where we process data from various sources. My problem is I want a to send email every time there is an error or error raise my me. Currently I do something like this where on every raise I send a email. But I want a system where on every error there would be a email sent. # send an email alert email_content = "Email content" subject = "Subject" if settings.ENVIRONMENT == 'PROD': BaseScraper.email_alert_for_error( subject, email_content, ["admin@mail.com"], ) else: BaseScraper.email_alert_for_error( subject, email_content, ["admin@mail.com"], ) -
duplicate record when combine `distinct` and `order_by`
I'm using filter_backend for ordering my fields, but I have a problem, when I order by product__company__name, the API responds 1 result as me as expected, but with 2 records duplicated. I read the Note in this docs https://docs.djangoproject.com/en/3.2/ref/models/querysets/#distinct that If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned. So how can I resolve this problems ? Thank so much. filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ["product__company__name"] ordering_fields = [ "created", "product__company__name", ] def get_queryset(self): if self.kwargs.get("shelf_type") == "want_to_read": result = ( MyModel.objects.filter( <logic_code> ) return result.distinct() -
insertion command via an API (Django project)
I am developing an e-commerce site using API calls. I would like to insert orders, the idea is after having selected several products on the cart (assume 4 products), I would like to insert them using the API only once, not with a loop. That is to say, I call the API only once and this inserts the 04 products into the database. And not put the API call in the shopping cart session loop, which will call the url 4 times. API Noted that if I remove its rows from the loop, it only inserts the last product url='http://myAPI/Product/postProduct' x=requests.post(url,json=data) Views.py @login_required def postCommande(request): for key,value in request.session.get("cart", {}).items(): data={ 'my_commande':[ { 'date':str(datetime.now()), 'name': request.user.client.name, 'content':[ { 'article':value.get('product_id'), 'designation':value.get('name'), 'quantite':value.get('quantity') } ] } ] } url='http://myAPI/Product/postProduct' x=requests.post(url,json=data) -
How to reverse query a table with foreign keys such that I can get the values of those foreign keys as well?
My models: https://pastebin.com/qCMypxwz How can I query the Variants table from Products table? I want to get the values of image and colors (which is a table itself) from the Variants table. This is what I am doing so far but this is giving me similar queries according to debug tool: productList = Products.objects.prefetch_related('category', 'variants_set__color_id', 'variants_set__image') for productName in productList: products = dict() prod_id = productName.variants_set.all()[0].id products['id'] = prod_id products['category'] = productName.category.category_name products['prod_name'] = productName.prod_name products['brand'] = productName.brand prod_colors = productName.variants_set.all().values_list('color_id__name', flat=True).distinct() prod_images = list(productName.variants_set.all()[0].image.all()) image_list = list() for image in prod_images: image_list.append(image.image_url) products['image'] = image_list products['colors'] = list(prod_colors) price = productName.variants_set.all()[0].price products['price'] = price createdAt = productName.variants_set.all()[0].createdAt products['createdAt'] = createdAt productListDict.append(products) -
How to upload file using many to many field in django rest framework
I have two models. One is article and other is documents model. Document model contains the filefield for uploading document along with some other metadata of uploaded document. Article has a m2m field that relates to Document Model. Article model has a field user according to which article is being which article is being posted. I want to upload file using m2m field, but it gives two errors: "files": [ "Incorrect type. Expected pk value, received InMemoryUploadedFile."] I also tried using slug field, the document does not exists. but i am uploading new file then why saying document does not exist. Please guide me how i can achieve this? Article Model class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=10000, blank=True) files=models.ManyToManyField('DocumentModel', related_name='file_documents',related_query_name='select_files', blank=True) published=models.DateTimeField(auto_now_add=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=mode Document Model class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") document=models.FileField(max_length=350, validators=[FileExtensionValidator(extensions)], upload_to=uploaded_files) filename=models.CharField(max_length=100, blank=True) filesize=models.IntegerField(default=0, blank=True) mimetype=models.CharField(max_length=100, blank=True) created_at=models.DateField(auto_now_add=True) Article Serializer class ArticleSerializer(serializers.ModelSerializer): #serializer for getting username of User created_by=serializers.CharField(source='created_by.username', read_only=True) isFavourite=serializers.PrimaryKeyRelatedField(many=True, read_only=True) tags=serializers.SlugRelatedField(many=True, queryset=Tags.objects.all(), slug_field="tag") readtime=serializers.IntegerField(read_only=True) class Meta: model= Article fields = ["id" , "headline", "abstract", "content", "readtime", "get_published_timestamp", "isDraft", "isFavourite", "tags", 'files', 'created_by' ] Document Serializer class DocumentSerializer(serializers.ModelSerializer): filesize=serializers.ReadOnlyField(source='sizeoffile') class Meta: model=DocumentModel fields = ['id', … -
How to add a column data from one table to another table column field in postgresql using python
I am new to django and postgresql. I have two tables in postgresql. in one table i have two fields ID and Value. i want to add the datas in the ID column to another table column field named value_id. In postgres the tables are from the same schema. I want to do this via python. Is there any way. please help. cur = con.cursor() db_insert = """INSERT INTO "Database"."TABLE_ONE" ("LT_ID_ONE", "LT_ID_TWO") VALUES( (SELECT "LT_ID_ONE" FROM "Database"."TABLE_TWO" WHERE "LT_NUM_ONE" =%s), (SELECT "LT_ID_TWO" FROM "Database"."TABLE_THREE" WHERE "LT_NUM_TWO" =%s) );""" insert_values = (df1.iloc[0, 0], df1.iloc[0, 1]) cur.execute(db_insert, insert_values) I am doing this in django so the above method will not work. can anyone please suggest any way please -
How to implement onfocus() with span tag onclick() event
I have one input type field which is google inspired input type with label animation which have onfocus event and In that one of the Input field has the Password field in which I have to apply eye-toggle functionality with onclick event. I am sharing screenshot of the input type. Input Field When I am trying to implement toggle functionality for password. onclick event is not able to trigger because of onfocus event. Here is the code for toggle. <div class="col-3 inputfield"> <input type="password" id="Password" name="Password" class="inputfield-control" placeholder=" "> <label class="form-label">New Password</label> <div class="input-group-append custom"> <span toggle="#password-field" class="icon ion-md-eye-off field-icon toggle-password show-password-icn" ></span> <br> </div> </div> $(document).on('click', '.toggle-password', function() { $(this).toggleClass("icon ion-md-eye"); var input = $("#Password"); input.attr('type') === 'password' ? input.attr('type','text') : input.attr('type','password') }); Because of the Animation in input field toggle click event is not even triggers. I have try to perform other click event rather then click event, still any of the click event is not working with Animation. -
Python 2.7.16 randomize a list of in with probability
I am using python version 2.7.16 and i want to get the alternative of the random.choices() method of python 3. sample code for latest python version - import random rewards = ['80 credit', '40 credit', '10 credit'] weights = (1000, 2000, 7000) pick = 3 selected_rewards = random.choices(rewards, weights=weights, k=pick) print(selected_rewards) i want this alternative for python version 2.7.16 i have tried everything but unable to find solution for this could anyone help me to get details related this ? -
How to improve the query to exclude referenced objects inside query (mptt model)?
I have the following code where each Song can have Parts and each part can have multiple Genres assigned. from model_utils.models import TimeFramedModel from django.db import models from mptt.models import MPTTModel, TreeForeignKey from mptt.fields import TreeManyToManyField from django.db.models import Prefetch class Song(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Part(TimeFramedModel): # start and end fields via inheritance song = models.ForeignKey(Song, related_name="parts", on_delete=models.CASCADE) genres = TreeManyToManyField(Genre) desc = models.TextField() def __str__(self): return self.start I'm trying to write a query: Input: A set of Genre.ids named in_genres Output: A query set containing the Songs that have a Part of the input Genre.ids and all other Parts excluded. My current query is: for genre_id in in_genres: genre = Genre.objects.get(pk=genre_id) qs = Song.objects.filter(parts__genres__in=genre.get_descendants(include_self=True)).prefetch_related( Prefetch( 'parts', Part.objects.filter(genres__in=genre.get_descendants(include_self=True) ) ) I there a way to improve this query? Is this the best way to achieve this? Any help is highly appreciated! -
How to use image as checkbox html
So basically what I need to do is a login page, with an eye on the password field, so the user can click on the eye icon, and see the password. What I have so far is a simple checkbox: <input type="checkbox" id="box" onclick="reveal()"> and the function to show and hide the password: function reveal() { if (document.getElementById('box').checked) { document.getElementById("id_password").type = 'text'; } else document.getElementById("id_password").type = 'password'; } It works with this solution, but I need to have an Eye-Icon, instead of a simple checkbox. How can I make an Image as the checkbox? -
Django: saving unique value without duplicate it
I'm trying to save unique name in the database but the problem I can save the same with different letters, for example I can save (IT, it, iT, It) I don't want to save it like that. Model: class Service(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=127, unique=True, null=False, blank=False) # that field is_active = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey( "accounts.User", on_delete=SET_NULL, blank=False, null=True, related_name="service_created_by", ) def __str__(self): return f"{self.name}" -
How do I write HTML code in Django's syndication feed framework?
I'm using Django's syndication feed framework to generate RSS for my website, referring to this document I have done the work according to the example it provides, the code is similar to the following, I have not made too many changes. from django.contrib.syndication.views import Feed from django.urls import reverse from policebeat.models import NewsItem class LatestEntriesFeed(Feed): title = "Police beat site news" link = "/sitenews/" description = "Updates on changes and additions to police beat central." def items(self): return NewsItem.objects.order_by('-pub_date')[:5] def item_title(self, item): return item.title def item_description(self, item): return item.description # item_link is only needed if NewsItem has no get_absolute_url method. def item_link(self, item): return reverse('news-item', args=[item.pk]) Then I want to add <a href="test.com">Click to my site</a> in item_description, I made some minor changes. def item_description(self, item): description = item.article_description description = description + "<a href='test.com'>Click to my site</a>" return description But the final generated code is escaped. <description>&lt;a href='test.com'&gt;Click to my site&lt;/a&gt;</description> I don't want to be escaped, what should I do? As far as I know, <![CDATA[MyInfo]]> tags need to be added to the HTML code in the xml, similar to the following. <![CDATA[<a href='http://test.com'>Click to my site</a>]]>" But I don't know how to do this in Django framework. -
Notification Django cannot be display
I am making a notification in Django but it seems to be not working. How can I make a notification whenever a user add a incident report (model: Incident General), it will notify the roles: admin and super admin that a new report for this user is added and when the admin or super admin change the status it will notify the user of the change in status. Can someone help me with this? Thank you Views def ShowNotifications(request): profile = get_object_or_404(UserProfile, user=request.user) notifications = Notification.objects.filter(user=request.user).order_by('-date') context = { 'profile': profile, 'notifications': notifications, } return render(request, 'notifications.html', context) Models class Notification(models.Model): TYPES = ((1, 'Reports'), (2, 'User Accounts'), (3, 'Inbox'), (4, 'Attributes Builder')) incident_report = models.ForeignKey('incidentreport.IncidentGeneral', on_delete=models.CASCADE, related_name="noti_report", blank=True, null=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=TYPES) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) class IncidentGeneral(SoftDeleteModel): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) IF_DUPLICATE = ( ('Duplicate', 'Duplicate'), ('Possible Duplicate', 'Possible Duplicate'), ('Not Duplicate', 'Not Duplicate') ) WEATHER = ( ('Clear Night', 'Clear Night'), ('Cloudy', 'Cloudy'), ('Day', 'Day'), ('Fog', 'Fog'), ('Hail', 'Hail'), ('Partially cloudy day', 'Partially cloudy day'), ('Partially …