Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django webpack_loader: `Regex` Undefined?
I've updated a Django app to Python 3.9 and Django 4.0, and I'm getting an error on launch: TypeError: expected string or bytes-like object I tracked it down to this function in python3.9/site-packages/webpack_loader/loader.py: def filter_chunks(self, chunks): filtered_chunks = [] for chunk in chunks: ignore = any(regex.match(chunk) for regex in self.config['ignores']) if not ignore: filtered_chunks.append(chunk) return filtered_chunks On the line ignore = any(regex.match(chunk)..., regex is undefined. I ran brew upgrade python, but Homebrew said: Warning: python 3.9.13_1 already installed What am I missing? -
How can I aggregate strings by concatenate in Django annotate?
I have the followed model in Django: class Click(models.Model): url = models.ForeignKey(Url, on_delete=models.CASCADE) browser = models.CharField(max_length=255) platform = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want to build a query to get the total clicks per day on the current month, along with browsers and platforms concatenated. For example: [ { 'created_at__day': 28, 'browsers': 'Chrome, Firefox', 'platforms': 'Windows, Linux', 'clicks': 4 } ] What I did until this moment was that query: queryset = Click.objects.filter( url=url_instance, created_at__month=datetime.now().month ).values('created_at__day', 'browser').annotate( clicks=Count('created_at'), ) How can I concat every browser and platform, only grouping by created_at__day? -
Is Django 500 error Invalid HTTP_HOST header a security concern?
I have a custom Django web app sitting behind an NGINX proxy server. I am seeing occasional errors come through from my Django server with messages like Invalid HTTP_HOST header: 'my.domain.com:not-a-port-number'. The domain name provided is not valid according to RFC 1034/1035. where the part after the colon has been a variety of wack garbage like, my.domain.com:§port§/api/jsonws/invoke my.domain.com:xrcr0x4a/?non-numeric-port-bypass my.domain.com:80@+xxxxtestxxxx/ my.domain.com:80@+${12311231}{{12311231}}/ I am able to replicate a similar error using curl where the request url and the host header are different: curl https://my.domain.com --header 'Host: my.domain.com:not-a-port-number' I suspect that these are likely coming from our network security scanning software trying to find vulnerabilities in our custom web apps, but I am a little surprised that NGINX allows these requests to make it through to my Django server, especially if, as the 500 error output suggests, these are invalidly formatted headers. Trying to prepare for the worst, is there anything I should change or be concerned about with this for the sake of security? Is there a best practice for this situation that I am unaware of? Should NGINX be filtering out these sorts of requests? For my own convenience it would be nice to not to see the noise of these … -
Django - how to give Javascript table information to create a network Graph?
I have a model which stores Network Stats including Nodes. I want to display that rendered in HTML. Here is my table interfaceModel Interface IPaddress Hostname AE1 1.1.1.1 A AE1 2.2.2.2 B AE2 3.3.3.3 C AE2 4.4.4.4 D AE3 5.5.5.5 E AE3 6.6.6.6 F I am using highcahrts Network Graph to draw a Network Graph https://www.highcharts.com/blog/tutorials/network-graph/ Here is the Code which displays the following demo graph <style> #container { background: #1f1f1f; min-width: 320px; max-width: 500px; margin: 0 auto; height: 500px; } </style> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/networkgraph.js"></script> <div id="container"></div> <script> Highcharts.chart('container', { chart: { type: 'networkgraph', marginTop: 80 }, title: { text: 'Network graph' }, plotOptions: { networkgraph: { keys: ['from', 'to'], } }, series: [{ marker: { radius: 30 }, dataLabels: { enabled: true, linkFormat: '', allowOverlap: true }, data: [ ['Node 1', 'Node 2'], ['Node 1', 'Node 3'], ['Node 1', 'Node 4'], ['Node 4', 'Node 5'], ['Node 2', 'Node 5'] ] }] }); </script> How can i replace the data in the JS data array looping from my Interfacedatabase hostname? It is a direct single straight connection with no inter connections A>B>C>D>E>F data should look something similar as follows data: [ [A, B], [B, C], [C, D], [D, E], … -
How to make search of list with none english letters?
I am making e-commerce website on ( React.js - client )and ( Python Django - client ). I am trying to make a search feature for list of all products and the queries are none-english. Whenever I try to search, my none-english query gets into hell knows what. For example I input query "текст" and it turns to / search / %D1%82%D0%B5%D0%BA%D1%81%D1%82. Expected: / search / текст. And of course my api cannot find any product with this query.. @api_view(["GET"]) def searchData(request, q): searchedData = Product.objects.filter(Q(title__icontains=q)) data = ProductSerializer(searchedData, many=True).data return Response(data) This is my search view. path('search/<str:q>/', views.searchData) This is my path. I hope for any kind of help. Thanks! -
Model and code changes to get query results from a DB with multiple lookup tables
The Django app I am building manages client information. The short version of this question is how do I build a Django query that equates to this sql statement... select cl.id, cl.first, cl.last, ad.zipcode, ph.phone_number, em.email_address from client.clients as cl join client.addresses as ad on cl.id=ad.client_id join client.phones as ph on cl.id=ph.client_id join client.email_addresses as em on cl.id=em.client_id where cl.status_id=1 and ad.type_id=1 and ph.type_id=1 and em.type_id=1; ...given the following models, starting with an abbreviated client: class Client(models.Model): id = models.IntegerField(primary_key=True) last = models.CharField(max_length=32) first = models.CharField(max_length=32) The address model: class Address(models.Model): id = models.IntegerField(primary_key=True) client = models.ForeignKey( 'Client', on_delete=models.DO_NOTHING, blank=False, null=False) type = models.ForeignKey( AddressType, on_delete=models.DO_NOTHING, blank=False, null=False) street = models.CharField(max_length=32, blank=True, null=True) city = models.CharField(max_length=32, blank=True, null=True) state = models.CharField(max_length=2, blank=True, null=True) zipcode = models.CharField(max_length=10, blank=True, null=True) The phone model: class Phone(models.Model): id = models.IntegerField(primary_key=True) client = models.ForeignKey( 'Client', on_delete=models.DO_NOTHING, blank=False, null=False) type_id = models.ForeignKey( PhoneType, on_delete=models.PROTECT, blank=False, null=False) is_primary = models.BooleanField country_code = models.CharField(max_length=5) phone_number = models.CharField(max_length=16) The email address model: class EmailAddress(models.Model): id = models.IntegerField(primary_key=True) client = models.ForeignKey( 'Client', on_delete=models.PROTECT, blank=False, null=False) type_id = models.ForeignKey( EmailType, on_delete=models.PROTECT, blank=False, null=False) email_address = models.CharField(max_length=128, blank=False, null=False) And finally, the ClientListView that should contain the queryset: class ClientListView(ListView): model = … -
TypeError: test_admin_login() missing 1 required positional argument: 'self'
I'm writing test cases for my Django-based rest APIs. The problem is in the method of testcase class. I want to use test_admin_login method in the setuptestdata method. And I'm unable to do that. I'm getting error that I mentioned in the title. class MyTests(TestCase): allow_database_queries: True client = APIClient() @classmethod def setUpTestData(cls): # client = APIClient() # AUTHENTICATION # response = cls.client.post(reverse('auth'),data={"username":"admin","password":"ppoopp00"},format='json') value = cls.test_admin_login() print(value) cls.auth_token = cls.test_admin_login(cls) # CREATE PROJECT response = cls.client.post( reverse('projects:project_create'), data={"platform_subscriber_entity":"NucoinTest"}, format='json', HTTP_AUTHORIZATION="JWT "+cls.auth_token ) cls.project_key = response.data["platform_subscriber_id"] def test_admin_login(self): """ Ensure we can create a new account object. """ url = reverse('auth') response = self.client.post(url,data={"username":"admin","password":"testpass"},format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 2) return response.data["access"] -
How to add "AND" clause to OUTER JOIN in Django ORM?
I have a query constructed in Django that is almost correct. Here is my call: all_companies = Company.objects.filter(Q(employees=None) | Q(employees=user.id)).annotate(username=F('employees__auth__username')).all().order_by('id') What this produces is the following: SELECT "main_company"."id", "main_company"."schema_name", "main_company"."name", "main_company"."subdomain", "main_company"."migration_id", "auth_user"."username" AS "username" FROM "main_company" LEFT OUTER JOIN "main_company_employees" ON ("main_company"."id" = "main_company_employees"."company_id") LEFT OUTER JOIN "main_user" ON ("main_company_employees"."user_id" = "main_user"."id") LEFT OUTER JOIN "auth_user" ON ("main_user"."auth_id" = "auth_user"."id") WHERE ("main_company_employees"."user_id" IS NULL OR "main_company_employees"."user_id" = 1) ORDER BY "main_company"."id" ASC; However this query does not work exactly the way I intended. What I would like is this: SELECT "main_company"."id", "main_company"."schema_name", "main_company"."name", "main_company"."subdomain", "main_company"."migration_id", "auth_user"."username" AS "username" FROM "main_company" LEFT OUTER JOIN "main_company_employees" ON ("main_company"."id" = "main_company_employees"."company_id") AND ("main_company_employees"."user_id" = 1) LEFT OUTER JOIN "main_user" ON ("main_company_employees"."user_id" = "main_user"."id") LEFT OUTER JOIN "auth_user" ON ("main_user"."auth_id" = "auth_user"."id") WHERE ("main_company_employees"."user_id" IS NULL OR "main_company_employees"."user_id" = 1) ORDER BY "main_company"."id" ASC; Note the difference in the first LEFT OUTER JOIN. How can this be achieved (other than the obvious raw query which I am trying to avoid)? -
Django auto increment fields
I have 2 columns named Serial and Bag I need them to be auto incremented but based on each other and also based on the user that will update the record, so every bag should have 100 serial and reset the number automatically after reaching 100, then start again with Bag number 2 and put 100 serial in it and reset. Thanks -
Django ViewSet serializer_class is being ignored
I have two models: ModelA and ModelB, with their corresponding serializers ModelASerializer and ModelBSerializer In a specific viewset, called MyViewSet i have the follwing structure: class MyViewSetRoot(viewsets.ModelViewSet): http_method_names = ["get"] # The returned values are of type "ModelA", so I need it to use that serializer serializer_class = ModelASerializer queryset = "" Finally, in my actual view, I do something like this: class MyViewSet(MyViewSetRoot): get(self, request: HttpRequest, *args, **kwargs) -> Response: ModelA_queryset = ModelA.objects.all() return Response( data=ModelA_queryset, status=status.HTTP_200_OK, ) I would expect in that case for the queryset to be serialized using the ModelASerializer that I specified in the serializer_class field. However, I get the error Object of type ModelA is not JSON serializable If I do this instead: class MyViewSet(MyViewSetRoot): get(self, request: HttpRequest, *args, **kwargs) -> Response: ModelA_queryset = ModelA.objects.all() serialized_queryset = ModelASerializer(ModelA_queryset, many=True) return Response( data=serialized_queryset.data, status=status.HTTP_200_OK, ) It works just fine, but I want to avoid serializing explicitly in the view. Any ideas on what could be actually going on? Am I forced to serialize explicitly in this case? -
URLS.PY and VIEWS.PY slug removal
I tried to word this specifically but the dilemma is as follows: The image will not load as the slug is being added on the detail page, but loads fine in the index.html. post.image is the code you should be looking for... works in index.html but not post_detail... Something is off in the views/urls.. tried many combos but still getting my brain wrapped around the intricacies of url patterns. I need the image in the detail to point to http://127.0.0.1:8000/static/placeholder_cake.PNG and not 'http://127.0.0.1:8000/carrot-cake/static/placeholder_cake.PNG (basically without the slug).. Thanks to anyone that assists! index.html <div class="col-md-8 mt-3 left"> {% for post in post_list %} <div class="card mb-4"> <div class="card-body"> <img class="card-img-top" src="{{ post.image }}" alt="Card image cap"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p> <p class="card-text">{{post.content|slice:":200" }}</p> <a href="{% url 'post_detail' post.slug %}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% endfor %} </div> post_detail.html {% extends 'base.html' %} {% block content %} <!-- {% load static %} --> <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-3 left top"> <div class="card-body"> <h1>{% block title %} {{ objest.title }} {% endblock title %}</h1> <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p> <!-- /carrot-cake/static/placeholder_cake --> … -
Django migrate column is not the same data type as referencing column
I have the below model which is an existing DB model and through Django's inspectdb management command the below model is created. class ExistingLegacyModel(models.Model): period = models.TextField(db_column="Period", blank=True, null=True) key = models.AutoField(db_column="Outloo", primary_key=True) class Meta: managed = False db_table = "table_name" and currently, I'm trying to create a model with a field foreign key reference to the existing legacy DB model class TestModel(models.Model): period = models.ForeignKey( ExistingLegacyModel, on_delete=models.CASCADE, db_column="Key", ) so when I run the makemigrations command the migration file is successfully getting created with no issue. below is the migration file content. class Migration(migrations.Migration): initial = True dependencies = [ ('historical', '0011_phoenixcontractprice'), ] operations = [ migrations.CreateModel( name='TestModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('period', models.ForeignKey(db_column='Key', on_delete=django.db.models.deletion.CASCADE, to='app.ExistingLegacyModel')), ], ), ] so now when i run the migrate command now, it is failing and giving the below error. django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'table_name.OutlookKey' is not the same data type as referencing column 'version_testmodel.OutlookKey' in foreign key 'version_testmodel_OutlookKey_eb16c31c_fk_table_name_OutlookKey'. (1778) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)") I'm stuck with this issue for the past couple of days and I searched all the internet … -
Pagination from django_tables2 not rendering
I am relatively new in Django and could not find any answer here on why my table from django_tables2 is not rendering nice pagination buttons. Here follows the codes: models.py class IDOC(models.Model): on_delete=models.SET_NULL, null=True) sample_id = models.CharField(max_length=200) lon = models.FloatField(null=True, blank=True) lat = models.FloatField(null=True, blank=True) dp_position = models.IntegerField(null=True, blank=True, verbose_name='DP Position [-]') def __str__(self): return self.sample_id tables.py class IDOCTable(tables.Table): sediment_depth_m = NumberColumn() wl_m = NumberColumn() H_m = NumberColumn() idoc_mgl = NumberColumn() temp_c = NumberColumn() idoc_sat = NumberColumn() class Meta: model = IDOC template_name = "django_tables2/bootstrap-responsive.html" views.py def view(): idoc_objects = IDOC.objects.all() idoc_show = flutb.IDOCTable(idoc_objects) context = { 'idoc_table': idoc_show, } return render(request, 'flussdata/query.html', context) flussdata/query.html {% extends 'base.html' %} {% load django_tables2 %} {% block content %} <div class="row"> <div class="col-md"> <div class="row"> <div class="card card-body"> <h3>Intragravel Dissolved Oxygen Content</h3> {% render_table idoc_table %} </div> </div> </div> </div> Then, my tables is rendered like this: Instead of the way it should, which I believe is like this: -
Simple JWT Usage
I have my Django backend authentication working (tested using curl and postman) but something eludes me. When sending test requests, the docs show username and password data being sent: curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "davidattenborough", "password": "boatymcboatface"}' \ http://localhost:8000/api/token/ but, if I try to send email and password instead, the response says that the username is a required field. Where and how can I change that behavior? Thanks! -
Can two models reference each other by ForeignKey?
I have two models class Customer(models.Model): name = models.CharField(max_length=255, unique=True) default_contact = models.ForeignKey("CustomerContact", verbose_name="...", related_name="default_contacts", null=True, on_delete=models.SET_NULL) etc. And class CustomerContact(models.Model): customer = models.ForeignKey(Customer, related_name='contacts') user = models.OneToOneField(User, related_name='user_contacts', on_delete=models.SET_NULL) address = models.ForeignKey(CustomerAddress, ....) In this example Customer points to CustomerContact. At the same time CustomerContact points to Customer. My coworker says that pointing Customer points to CustomerContact violates the OneToMany nature of ForeignKey. What am I doing wrong? -
Search and page functionality disappearing for any additional data tables on webpage
Strange issue, but for some reason whenever I add any additional data tables to my site on the same page, the additional tables populate just fine but are missing the search and page functionality. I am using datatables.net for it. What could be the reason for this? I see in the example on https://datatables.net/examples/basic_init/multiple_tables.html that it should work just fine.enter image description here {% block css %} <!-- Custom styles for this page --> <link href="{% static 'vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet"> {% endblock %} <div class="row"> <div class="container-fluid"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Data Table 1</h6> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%"> DATA IS HERE ON MY MACHINE </table> </div> </div> </div> </div> </div> <div class="row"> <div class="container-fluid"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Data Table 2</h6> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%"> DATA IS HERE ON MY MACHINE </table> </div> </div> </div> </div> </div> {% endblock %} {% block js_body %} {% include 'theme/components/charts_scripts.html' %} <script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script> <script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script> <script src="{% static 'js/demo/datatables-demo.js' %}"></script> {% endblock %} -
Model object not creating from inside except block or right before raising exception
Something very strange is happening in my Django app. When I try to run the following code Model.objects.create(**obj) before raising an exception OR run the same code inside an except block, the code runs without any issue, but I cannot see the object in the database. Running the Model.objects.all() also doesn't return anything. This is the complete code: def has_permission(self, request, view): try: serializer = VerifyOTPRequestSerializer(data=request.data) serializer.is_valid(raise_exception=True) otp = request.data.pop("otp") flow = request.data.pop("flow") primary_phone = request.data.get("contact_detail", {}).get( "primary_phone", "" ) if OTPFailedAttempts.objects.filter(phone=primary_phone).count() > 0: raise Exception("otpAttemptError") return helpers.OTPHelper.verify_otp(primary_phone, otp, flow) except Exception as permission_error: OTPFailedAttempts.objects.create(**{"phone": primary_phone, 'email': email}) return False Is there a particular reason why Django doesn't allow object creation of objects around exceptions or am I doing something wrong? -
How Do I Detect And Properly Display Events On Calendar That Overlaps Months in Python?
I used a tutorial I found online to create an event calendar in Python. I've tried to improve it to schedule events that may have a start and end time range that overlap months. Meaning it may start in June and end in July. I've got it partially figured out...I can display the events based on the start day being lte day in the Python HTMLCalendar module. I can't figure out how to pick up the remaining day for July 1. June displays perfectly. Thanks in advance for any thoughts. Here's my code... HTMLCALENDAR Utility.. class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dropdown=None): self.dropdown = dropdown self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, requests): requests_per_day = requests.filter(start_time__day__lte=day,start_time__month=self.month) d = '' for request in requests_per_day: d += f'<li> {request.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, requests): week = '' for d, weekday in theweek: week += self.formatday(d, requests) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): # … -
How Do I Detect And Properly Display Events On Calendar That Overlaps Months in Python?
I used a tutorial I found online to create an event calendar in Python. I've tried to improve it to schedule events that may have a start and end time range that overlap months. Meaning it may start in June and end in July. I've got it partially figured out...I can display the events based on the start day being lte day in the Python HTMLCalendar module. I can't figure out how to pick up the remaining day for July 1. June displays perfectly. Thanks in advance for any thoughts. Here's my code... HTMLCALENDAR Utility.. class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dropdown=None): self.dropdown = dropdown self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, requests): requests_per_day = requests.filter(start_time__day__lte=day,start_time__month=self.month) d = '' for request in requests_per_day: d += f'<li> {request.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, requests): week = '' for d, weekday in theweek: week += self.formatday(d, requests) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): # … -
How to print out request.body data in django?
Just working through the Django tutorials and playing around with stuff. Was going through the HttpResponse and HttpRequest docs and I'm just trying to print out data to see how things work. However, when I try to print to console the request.body I get nothing back. def detail(request, question_id): current_question_selected = Question.objects.get(pk=question_id) choices_for_question = current_question_selected.choice_set.all() context = {"choices_for_question":choices_for_question, "current_question_selected":current_question_selected} #print(request.META["REMOTE_USER"]) print(request.body) return render(request, 'polls/detailtext.html', context) This is what gets pritned to the screen, the letter 'b' with an empty string [28/Jun/2022 10:59:56] "GET /polls/1/ HTTP/1.1" 200 456 b'' Not sure what i'm missing -
Sending mail now for testing after disabling the less secure app setting in gmail
I was trying to send mail to test one of my Django Rest Framework projects. I know I have to turn on the "Less Secure Apps Permission" for Gmail to receive the mail from the localhost. But Google disabled that setting from June 30. There's no error But I am not receiving the emails. I've tried using the app passwords from gmail but it's not working as well. Now how I can be able to send emails from localhost? -
Django multiple image upload CRUD funcionality with two forms
I want to let the user upload multiple images per product like in an ecommerce application. Therefore I created two models. In forms.py I added the ImageField to the ProductForm. My create_product view seems to work but I do not really know how I can create the update and delete view. Thanks! models.py class Product(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) describtion = models.TextField(null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class ProductImage(models.Model): project = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.FileField() forms.py class ProductForm(ModelForm): image = forms.ImageField(widget=ClearableFileInput(attrs={'multiple':True})) class Meta: model = Product fields = ['title', 'describtion'] views.py def create_product(request): form = ProductForm() profile = request.user.profile if request.method == 'POST': form = ProductForm(request.POST) images = request.FILES.getlist('image') if form.is_valid(): project = form.save(commit=False) project.owner = profile project.save() for i in images: ProductImage.objects.create(project=project, image=i) context = {'form':form} return render(request, 'projects/project_form.html', context) -
Django and OpenApi compliance
We are using Django for our api development and we need to be OpenAPI 3.0 compliant. In this article it is written that "Django Automates generation of OpenAPI 3". Do we need to do anything extra for this or by default the api(developed in Django) is OpenAPI complaint? How can we test/ verify this? -
Django Project, Versioning Management
Is there a way to run single Django app separately? First, why ? As we know, when you make a user upgrade or downgrade your system from UI inside system, if there a crash during replace changed files, then the system will break down. Second, the solution. if the UI of version control run separately, the user can redo the change to make system survive . -
django and matplotlib , how i can see the plot on html
actually when i run my code, i have a visualisation of the plot but not on html How i can see the plot on my html? ''' def inf_norm_detection(df_abs, crop_left, crop_right, clean_param=500): ''' infinum norm outlier detection, it is the first step of outlier detection computes matrix of inf norm (max of absolute values) of the samples one to onother inputs: clean_param (int) - usualy 150-500, smaller means more outliers, df_abs (pandas DataFrame) - data of interest, usualy absorbance or asmptotic data crop_left, crop_right - values to crop the data according to MPF measurments. output: indexes of df_abs that are suspected to be outliers, if none were identified, None is returned ''' X = df_abs.iloc[:, crop_left:crop_right].to_numpy() l = X.shape[0] D = np.zeros((l, l)) idx = range(len(X)) for j in range(1, X.shape[0]): idx = list(set(idx) - {j}) A = X[idx] - X[j] D[j, idx] = np.abs(A).max(1) D = np.maximum(D, D.transpose()) d = D.sum(0) / l diff = np.sort(d)[1:] - np.sort(d)[:-1] if np.where(diff > clean_param * np.median(diff))[0].size != 0: threshold = np.sort(d)[np.where(diff > clean_param * np.median(diff))[0] + 1].min() return df_abs.iloc[np.where(d >= threshold)].index def show_absorbance(df_abs, crop_left, crop_right, clean_param): outliers = inf_norm_detection(df_abs,crop_left, crop_right, clean_param) colors = [color for color in mcolors.CSS4_COLORS.values() if color !='yellow'] …