Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django Unit Test Assertion Error for Serialization
I am trying to perform the unit test for a feature in my website, whereby the user uploads a JSON file and I test if the JSON file is valid using serialization and JSON schema. When running the following test code I keep getting assertion error. serializer.py class Serializer(serializers.Serializer): file = serializers.FileField(required=True) format = serializers.CharField(required=True) def validate(self, data): is_valid, message = Validation().is_valid( json.loads(data.read())) if (not (is_valid)): raise serializers.ValidationError(message) tests.py class Validation(TestCase): def test_valid_serializer(self): file_mock = mock.MagicMock(spec=File) file_mock.name = 'mock.json' file_mock.content = { 'mockData': [{ "id": 1, "name": "blue", }] } serializer_class = Serializer(data=file_mock.content) assert serializer_class.is_valid() assert serializer_class.errors == {} -
Numbering cells in a grid using opencv python
I have created grids on an image with open cv, so I am trying to number the cells created from 1,2,3,4,5,... the image shows what the result of this code is. Anyone with an idea how to get all the cells numbered in python x = 0 y = 0 k = 0 while x < self.img.shape[1]: cv2.line(self.img, (x, 0), (x, self.img.shape[0]), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1) while y < self.img.shape[0]: cv2.line(self.img, (0, y), (self.img.shape[1], y), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1) y += 100 k += 1 cv2.putText(self.img, str(k), (x,y), font, 1, (0, 255, 255), 1, cv2.LINE_AA) x += 100 enter image description here -
Django refferal link registration
In my project I need to register User1, and then User2 using refferal link from User1. That link should contain access_code unique for each user, for example http://my_site/register?access_code=some_random_code. All users are registered through one view: class UserCreateAPIView(CreateAPIView): queryset = get_user_model().objects.all() serializer_class = UserSerializer User Model: class User(AbstractUser): pair = models.OneToOneField( "self", null=True, blank=True, on_delete=models.DO_NOTHING) access_code = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) So I need: Check if there is an access_code in request body If access_code exists, then find User1 who sent this code Add User1's id to current user(User2) to the field pair Add User2(current) to User1 field pair so both users had references to each other through pair fields -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.