Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Admin how to handle erros in save_model():
I have a simple model with a FileField and I want to deal with files before finally saving them. So What I did, was overwriting the save_model() method and everything works. Now I wanted to implement error handling, and I feel I should have used another method to do my validating (maybe clean()?): def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if "file" in form.changed_data: if ok: proceed else: raise Error I need to differentiate between the file types of the uploaded file, before saving them (zips need to unpacked first, then saved and other things). -
Multiple representations of the same instance in DRF
I use DRF to make some datasets from my Django (2.2.24) Backend accessable and use a Listfield-Serializer to show them via my API as a list. qualificatonIds is a many-to-many field in a model with connects a topic-instance with some qualification-instances and vice versa. Serializer: class TopicListField(serializers.ListField): id = serializers.PrimaryKeyRelatedField(source='pk', read_only=True) code = serializers.CharField(source='category.code', read_only=True) qualificationIds = serializers.PrimaryKeyRelatedField(source='qualifications', many=True, default=[], read_only=True) equipmentIds = serializers.PrimaryKeyRelatedField(source='equipments', many=True, default=[], read_only=True) miscEquipment = serializers.CharField(source='misc_equipment', read_only=True) My output a list that includes two diffrent instances of the same database entry, with different primary keys. My expected output is a list with one instance and where the two diffrent primary keys are stored in one list. How can I store them in one instance? Output: "topics": [ { "id": 17, "code": "AAK", "qualificationIds": [ 35 ], "equipmentIds": [ 7 ], "miscEquipment": "" }, { "id": 17, "code": "AAK", "qualificationIds": [ 35 ], "equipmentIds": [ 6 ], "miscEquipment": "" } ] Expected Output: "topics": [ { "id": 17, "code": "AAK", "qualificationIds": [ 35 ], "equipmentIds": [ 6 7 ], "miscEquipment": "" } ] Specific model-part: class QualificationMixin(models.Model): # noinspection PyUnresolvedReferences qualifications = models.ManyToManyField( 'Topic', db_index=True, verbose_name='Voraussetzungen (Kurse)', related_name='%(class)s_list', blank=True, help_text="Welche Kurseinhalte müssen von den Teilnahmern für den … -
How to use CORS in django rest framework?
I have used django-cors-headers for CORS but unable to get CORS to work in a right way. Like from client end I can run code from any host that are not in ALLOWED HOSTS but the request still completes without any CORS error. Can anyone tell me , how can I only allow whitelisted hosts? My settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ["SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! SECURITY_TRUE = True SECURITY_FALSE = False DEBUG = False CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_HSTS_SECONDS = 1 #31536000 ALLOWED_HOSTS = ["127.0.0.1"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # add rest_framework support to the project 'rest_framework', # setting cors policy is needed to make calls from ui to api 'corsheaders', 'mauth' ] MIDDLEWARE = [ # Add cors middleware 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'm.urls' … -
ValueError: Cannot convert mixed to alternative - Sending Email with Python
I am trying to send a styled bootstrap HTML template to email with the help of smtplib and EmailMessage. I have used f string to format the file. But, I am facing ValueError: Cannot convert mixed to the alternative. I could not address the problem. It should have work but couldn't be able to think much. Where did I do wrong?. In emailsender.py import smtplib import imghdr from email.message import EmailMessage #Credentials sender_email = "sender127@gmail.com" password = 'password231' receiver_email = "reciever9882@gmail.com" smtp = smtplib.SMTP_SSL('smtp.gmail.com',465) smtp.login(sender_email, password) message = EmailMessage() #Instantiate EmailMessage with open('/email.png', 'rb') as file_obj: fdata = file_obj.read() ftype = imghdr.what(file_obj.name) print('Type:'+ftype) fname = file_obj.name print('Name of file:'+fname) message["Subject"] = "Email Test" message["From"] = sender_email message["To"] = receiver_email message.set_content("This is a test version!") #message.attach('django notes.pdf') message.add_attachment(fdata, maintype ="image", subtype = ftype, filename=fname) message.add_alternative(f"""\n\n <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"> <div class="container py-4"> <header class="pb-3 mb-4 border-bottom"> <a href="/" class="d-flex align-items-center text-dark text-decoration-none"> <svg xmlns="http://www.w3.org/2000/svg" width="40" height="32" class="me-2" viewBox="0 0 118 94" role="img"> <title>Bootstrap</title> <path fill-rule="evenodd" clip-rule="evenodd" d="M24.509 0c-6.733 0-11.715 5.893-11.492 12.284.214 6.14-.064 14.092-2.066 20.577C8.943 39.365 5.547 43.485 0 44.014v5.972c5.547.529 8.943 4.649 10.951 11.153 2.002 6.485 … -
python django testing views NoReverseMatch
while testing the applications logic iam facing this error python ver:3.8.2 django rest_framework:3.12.4 raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'signup' with keyword arguments '{'brandname': 'tcs', 'brandtext': 'tcsit', 'image1': '', 'image2': ''}' not found. 1 pattern(s) tried: ['brand/signup/$'] please suggest a good solution. thanks in advance -
Is it possible to connect MySQL DB from django template?
I want to know whether it is possible to connect mysql db from django template?. {% for product in productLists %} <form onsubmit="addToDB(event);"> {% csrf_token %} <img src="/Media/{{product.product_image}}" alt="{{product.product_name}}"> <h3>{{product.product_name}}</h3> <input type="hidden" name="User_id" class="User_id" value="{{user.User_id}}" /> <button type="submit"> Add to cart </button> </form> {% endfor %} The above code is an html code, Here i want to display the products what are available with the particular product_id, so now by using the product_id I want to get the product details from the database whenever the for loop gets executed. how to do it and is it possible to connect db from django template or else any other alternative method is there to do it? -
Django: how can i display an image from the django database on a template based on an selected option from a form?
I am a beginner with django and I have been struggling for a few weeks to correlate a user's selected option in a form with the data in my database to list the logo of the selected brand and the car model image in the template. So far I have managed to bring and store the data from the selected form in the database (MasinaSelectata model), the data is updated according to the client's ip. Now I need to use the data stored in the (MasinaSelectata model) and list the brand logo in the (Constructor model) and the model image in the (Model model). Which I fail to do due to lack of experience and knowledge. I tried several variants, none of them succeeded, my last attempt is the one below. Models: class Constructor(models.Model): constructor_nume = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=150, unique=True) logo_constructor = models.ImageField(upload_to='photos/selectormasina', blank=True) class Model(models.Model): constructor = models.ForeignKey(Constructor, on_delete=models.CASCADE) model_nume = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=250, unique=True) imagine_model = models.ImageField(upload_to='photos/selectormasina', blank=True) class Versiune(models.Model): constructor = models.ForeignKey(Constructor, on_delete=models.CASCADE) model = ChainedForeignKey(Model, chained_field="constructor", chained_model_field="constructor", show_all=False, auto_choose=True, sort=True) versiune_nume = models.CharField(max_length=300, unique=True) slug = models.SlugField(max_length=350, unique=True) class MasinaSelectata(models.Model): constructor = models.ForeignKey(Constructor, on_delete=models.CASCADE) model = models.ForeignKey(Model, on_delete=models.CASCADE) versiune = models.ForeignKey(Versiune, on_delete=models.CASCADE) … -
Mysql Command Not Found using Powershell on VSCode, but works using CMD
I wanted to use Mysql with the powershell on VSCode, but when I ran the "MySQL -u root -p" command, it showed up like this: On Powershell Vscode I already added the MySQL path in Windows' environment variable and still got the error.. But when I ran the "MySQL -u root -p" on CMD, it worked just fine.. On CMD Any idea how to solve this? Thank you -
Total download count for an item in Django
I am making a website where users can download the freebies. I want to log the total downloads for each item and then display this value in my backend. Currently, I am using this function to allow users to download files from the static folders. MODEL: upload = models.FileField(upload_to ='uploads/') TEMPLATE: <div class="flex items-center justify-center"> <a href="{{item.upload.url}} " class="text-white w-full text-center bg-black p-4 rounded-lg mt-8 hover:bg-gray-800"><button>Download this file | <span class="text-xs text-green-400">{{object.upload.size|filesizeformat}}</span></button></a> </div> -
How to execute raw sql statement for SQL server from django?
Original db query that works: SELECT * FROM [db_name].[dbo].[table] WHERE name IN ( SELECT name FROM [db_name].[dbo].[table] WHERE active = 1 Group by name Having count(*) > 1 ) order by name and when I try to execute it from django as from django.db import connection def fetch_matching_pn_products(): with connection.cursor() as cursor: cursor.execute("SELECT *" "FROM db_name.dbo.table" "WHERE name IN (" "SELECT name" "FROM db_name.dbo.table" "WHERE active = 1" "Group by name" "Having count(*) > 1" ")" "order by name") data = cursor.fetchall() return data returns this error django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'IN'. (156) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '.'. (102)") I have also tried changing db_name.dbo.table in django to [db_name].[dbo].[table] and table with no success. What needs to be changed so the raw query executes correctly? -
Zope.interface in Django
I am from a Java background and now working on a django application. Need your input if I am in the wrong direction. I am trying to implement zope.interface.Interface in my Django application and trying to achieve what interfaces in Java do, but it does not throw any error if the implementer class does not provide the definition of all the methods in the interface. Here is my sample implementation. import zope.interface class MyInterface(zope.interface.Interface): x = zope.interface.Attribute("foo") def method1(self, x): pass def method2(self): pass @zope.interface.implementer(MyInterface) class MyClass: def method1(self, x): return x**2 def method2(self): return "foo" @zope.interface.implementer(MyInterface) class MyClass2: def method1(self, x): return x**2 print(list(zope.interface.implementedBy(MyClass))) print(list(zope.interface.implementedBy(MyClass2))) c = MyClass() print(c.method1(5)) print(c.method2()) d = MyClass2() print(d.method1(5)) Kindly help me find out what am I doing wrong and your kind guidance. Thank you, -
Python Desktop Application with HTML, CSS and JS
I am building an application which is similar to stock market where the prices will change automatically on the front end without the request from the client ( no ajax ). Something like websocket or server side events which pushes the latest price of the stock to the javascript. I can achieve this with django but I dont want to take it as web application instead need to run it as desktop application. Many suggested electron for doing this but my application is already written in python and I have the following questions. How to send stock price change to electron if am using python as a child process inside electron ? Is there any way to implement server-side events or websockets in python code and make it communicate with whenever there is a change electron ? Or is there any framework to do the above other than django to make desktop applications using front end technologies ? -
Django -does apps in django called as micro services?
I'm just learning about microservices and just want to know does django have inbuild microservices ? or the apps/modules which we have inside the django project is said to be microservices? here I have attached project structure where I have more than 4 apps/modules(basket,payments,store,orders) were there. Is these apps are microservices in django? -
Tracking accesses to Django model fields
Given the following model: class A(BaseModel): b_fk = ForeignKey('B', ...) @property def get_dollars(self): return self.b_fk.dollars I want to log each time a field from B table is accessed using the foreign key. So A().get_dollars() should log that dollars field was accessed using the foreign key. For that, I thought of using __getattr__ and wrap the ForeignKey class: class ForeignKeyWithTracking(object): def __init__(self, ...): self.b_fk = ForeignKey('B', ...) def __getattr__(self, attr): # This method is called each time a field from this object is accessed. logger.info('Field accessed: %s', attr) return getattr(self.b_fk, attr) class A(BaseModel): b_fk = ForeignKeyWithTracking('B', ...) The problem is that all I'm seeing are logs like the following: Field accessed: contribute_to_class Field accessed: contribute_to_class Field accessed: contribute_to_class So I don't get the exact dollars field. Do you know why this field is logged and not dollars? -
How to recalculate a field in another model based on the calculations of one model in Django?
There are three models in my project, that are: class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) pattern = RegexValidator(r'(RT|rt|rT|Rt)\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') rt_number=models.CharField(max_length=15, validators=[pattern]) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=0) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) @property def package(self): try: return Package.objects.order_by('id').filter(patient=self.patient).reverse()[0] except Package.DoesNotExist: return None def calculate_approved_discount(self): if(self.package): if self.package.patient_type=='CASH': self.approved_package = self.package.total_package - self.discount else: pass def calculate_base_value(self): if (self.package): process_charge=self.package.total_package*15/100 net_total_package=self.package.total_package - process_charge amount_per_fraction=net_total_package/self.package.max_fractions net_cost=amount_per_fraction*self.done_fractions gross_cost=net_cost+process_charge self.base_value=gross_cost else: self.base_value=self.approved_package def calculate_expected_value(self): if (self.package): if self.base_value<self.approved_package: self.expected_value=self.base_value else: self.expected_value=self.approved_package else: self.expected_value=0 def save(self, *args, **kwargs): self.calculate_approved_discount() self.calculate_base_value() self.calculate_expected_value() super(Receivables, self).save(*args, **kwargs) class Realization(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) cash=models.BooleanField(default=False) amount_received=models.DecimalField(max_digits=10, decimal_places=2, default=0) billing_month=models.DateField(default=None) deficit_or_surplus_amount=models.DecimalField(max_digits=8, decimal_places=2, blank=True) deficit_percentage=models.FloatField(blank=True, default=0) surplus_percentage=models.FloatField(blank=True, default=0) remarks=models.TextField(max_length=500, default="N/A") @property def receivables(self): try: return Receivables.objects.order_by('id').filter(patient=self.patient).reverse()[0] except Receivables.DoesNotExist: return None @property def discharge(self): try: return Discharge.objects.order_by('id').filter(patient=self.patient).reverse()[0] except Discharge.DoesNotExist: return None @property def package(self): try: return Package.objects.order_by('id').filter(patient=self.patient).reverse()[0] except Package.DoesNotExist: return None def calculate_deficit_surplus_amount(self): if (self.receivables): print(self.receivables) self.deficit_or_surplus_amount=self.amount_received-self.receivables.expected_value else: self.deficit_or_surplus_amount=0 def calculate_deficit_or_surplus_percentage(self): if (self.receivables): if self.amount_received>self.receivables.expected_value: self.surplus_percentage=self.deficit_or_surplus_amount/self.receivables.expected_value*100 self.deficit_percentage=0 elif self.amount_received<self.receivables.expected_value: self.deficit_percentage=self.deficit_or_surplus_amount/self.receivables.expected_value*100 self.surplus_percentage=0 elif self.amount_received==self.receivables.expected_value: self.deficit_percentage=0 self.surplus_percentage=0 else: self.surplus_percentage=0 self.deficit_percentage=0 def save(self, *args, **kwargs): self.calculate_deficit_surplus_amount() self.calculate_deficit_or_surplus_percentage() super(Realization, self).save(*args, **kwargs) Now what I want is when a patient is … -
React code does not update on code change
I am serving the react frontend via django. I can see that the code change is updated within the file in the docker container on the digital ocean droplet but the frontend is not updated with the latest change. Here is what I tried. Here is my Dockerfile.prod # pull the official base image FROM python:3.8.12-bullseye # set work directory WORKDIR /usr/src/app # copy project COPY . . # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update \ && apt-get install ffmpeg libsm6 libxext6 -y \ && apt-get install -y netcat \ && apt-get install -y curl \ && curl --silent --location https://deb.nodesource.com/setup_12.x | bash - \ && apt-get install -y nodejs RUN pip install -r requirements.txt # copy entrypoint.sh RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.prod.sh RUN chmod +x /usr/src/app/entrypoint.prod.sh # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.prod.sh"] Here is my entrypoint.prod.sh #!/bin/sh if [ "$DATABASE" = "postgres" ]; then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi (cd frontend && npm install && npm run prod) exec "$@" The output of the container: Waiting for postgres... PostgreSQL started npm WARN frontend@1.0.0 No description npm WARN frontend@1.0.0 … -
How to create VPN client on Django Docker container?
I have a docker-compose file with 3 services; django, postgres and pgadmin. Now i have to connect to new existing external database accessible through a VPN. How can i prepare the django container to connect to this new database ? Thanks in advance. -
Agora Remote view changed when local mute video
this is my html file <div id="remote-video-frame"> <div class="mutedVideo" v-if="remotemutedVideo">{{user}}</div> <div id="remote-video" class="remote-video" v-if="!remotemutedVideo" v-if="remoteJoined" ></div> <div class="content-center waitremote" v-else> <div class="pulse"> <i class="fas fa-phone fa-2x"></i> </div> <p>Waiting {{singleUser}} to response to this video call now.</p> </div> </div> js file handleVideoToggle() { if (this.mutedVideo) { this.localStream.unmuteVideo(); this.mutedVideo = false; } else { this.localStream.muteVideo(); this.mutedVideo = true; } i declared remotemutedVideo in my js file and tried to declare the state of it in handleVideoToggle but its still wont work, how could i get the mute status from the remote there and show to local that remote user muted their video instead of just getting a black screen -
Django POSTing a TimeStamp to REST API
When I create and migrate a Model with a DateTimeField I can create an entry in my database wich lets me pick the Date I want to log manually. Now I created a Post method to add new entries to my db, but how would I automatically add a Timestamp like the AutoField 'ID' ? -
Django : OPENPYXL data in html django template
I have an excel sheet . I need to get the data , so I used open pyXl . But now , I don't know how to display that data. How do I use it in my html? -
Why can't create superuser
how can I solve this problem in django[duplicate admin showing][1] "raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin" -
Ho to replace default error page in Django?
I have a Django app and in the main urls.py I have the handler500 = 'common.view_utils.custom_500' which is supposed to display my custom error page. The code of the custom_500 is as follows def custom_500(request): logger.error(sys.exc_info()) t = loader.get_template('500.html') type, value, tb = sys.exc_info() return HttpResponseServerError(t.render(request, { 'exception_value': value, 'value': type, 'traceback': traceback.format_exception(type, value, tb) })) However when I tried to test it and raised an Error from the view class then Django displayed the default A server error occurred. Please contact the administrator. error page. I thought if an Error is raised in the code then that is supposed to be a 500 error which will be handled but mu custom error handler but obviously I am mistaken. Could you please help me what I am missing here? Thanks, V. -
Decoupled authentication for multiple applications
I am researching authentication models that would allow me to: Have a single user account managed by the main application, where I can login using various methods (including OAuth): auth.main-app.com Have multiple sub-applications, each with its own unique domain, that use the main application for authenticating users. The sub-applications would have their own separate databases, for app-specific data, some of which would be correlated with the users found in the main-app.com. Notes Planning on using: Kong as an ingress Gateway. Django for all apps. Question Is there an existing authentication solution that could cover these requirements? -
Django Filter error select form invalid data
hi i have a problem with filtering a select field. I know the problem lies in the form but I don't understand what I need to change to make it work. Someone can give me the solution or can tell me how I can test a form with print because I don't understand how to be able to test it. form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['dati_esercizio'].queryset = models.DatiEsercizi.objects.none() if 'gruppo' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) self.fields['dati_esercizio'].queryset = DatiEsercizi.objects.filter(gruppo_single = gruppo_id) except (ValueError, TypeError): pass views def caricamento_esercizi(request): gruppo_id = request.GET.get('gruppo') gruppo_name = DatiGruppi.objects.get(dati_gruppo = gruppo_id) esercizi_add = DatiEsercizi.objects.filter(gruppo_single = gruppo_name) context = {'esercizi_add': esercizi_add} return render(request, 'filtro_esercizi.html', context) file html $("#id_gruppo-dati_gruppo").change(function(){ var gruppoId = $(this).val(); var url = $("#creazione_scheda").attr("data-esercizi-url"); $.ajax({ url: url, data:{ 'gruppo': gruppoId }, success: function(data){ $(".esercizi select").html(data); } }); }); model class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) def __str__(self): return self.nome_gruppo class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) -
Create an instance of
My class is called Listing ValueError at /listing/3/ Cannot query "Clothes,Adidas,👏🏻 super quality!,50.00,http://www.pngall.com/wp-content/uploads/2016/06/Adidas-Shoes.png,Ninja ,2021-12-31 00:00:00+00:00": Must be "Listing" instance. Please explain in a simpler form I'm not sure I understand. Do I need to create an instance of the Listing class?