Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/DRF Pagination using paginate_queryset doesn't return key, value but only keys in result
I've added pagination handling on one of my views using PageNumberPagination from DRF, using the paginate_queryset method works only after converting the result dict to a tuple, it's structure is like the following: { "key": {"other": "dict inside"}, "key2": {"other": "dict inside"}, "key3": {"other": "dict inside"}, } Pretty simple struct, the problem is that the result does return the correct data, but only their keys, I would like the result data to be key, value as the above structure instead of just keys. Is there an easy way of doing that? For reference I also already override PageNumberPagination with a custom class like this: class CustomPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'controller': { 'count': self.page.paginator.count, 'previous': self.get_previous_link(), 'next': self.get_next_link(), }, 'results': data }) And in my view to paginate: class ApiView(APIView, CustomPagination): page_size = 10 def get(self, request): # [...] pagination = self.paginate_queryset(tuple(result), request, view=self) return self.get_paginated_response(pagination) Where result is the original dict mentionned above converted to a tuple. -
Django - Link to download bringing me a past file
I have a regular Django project working fine for year and links for many download Microsoft Excel templates. The thing is I've change one of them, and when I click to download it, it downloads me the older spreadsheet (I've deleted it on my server). But if I access on an incognito browser, it downloads me the newest version. What should I do to solve this, is it something related to time expiration of cookies or something like this? Thank you in advance! -
Dynamically choices for microservices in django rest (best practices)
I have a microservice A which asks microservice B about what type of products can microservice A receive as it's choices for some CharField, for example, "Type". And I have some options, where to make the actual request to microservice B: 1)Model level (CharField(choices=TYPES)) 2)Serializers level 3)View level of the microservice A. So, when I'm adding some new type to microservice B "Type" model instance, I have to restart microservice A to receive this new option to create. But as it comes to the "list" ViewSet action, I can receive new types dynamically by just refreshing this page in browser, because of GET request So the question is: how to build this kind of connection between two microservices to avoid restarting the microservice A server to receive new options. I'll be glad to get some best practices. P.S. I heard about brokers, but at start level, I'm trying to get the actual mechanism of how it all works. After that I can build up comfortness, reliability and other features that comes with brokers -
Django: Alternate input forms for models in admin?
I'm basically asking if there's an equivalent to adding data kinda like how you'd create a new instance of a class using a classmethod instead of using init. My example is a publication input form - you can either add the data manually, or you can enter a key code (a DOI in this case), make a request to a central database, which will pull the rest of the data for you. Outside of Django, I'd implement it this way: from datetime import date class Publication: title: str = "" date: date = date.today() url: str = "" doi: str = "" publication_name: str = "" authors: list[str] = [] @classmethod def add_publication_manually(cls, title, pub_date, url, pub_name, authors, optional_doi): ob = cls.__new__(cls) ob.date = pub_date ob.title = title ob.url = url ob.publication_name = pub_name ob.authors = authors ob.doi = optional_doi return ob @classmethod def add_publication_from_crossref(cls, doi): import requests ob = cls.__new__(cls) # parse output from requests return ob if __name__ == "__main__": pub_list = [] pub = Publication.add_publication_manually("...") pub_list.append(pub) pub_doi = Publication.add_publication_from_crossref("doi") pub_list.append(pub_doi) I have a similar Django model set up, and I can add entries to the database using the "manual" method in the admin, but now I want … -
How to do model data validation in django
I would like when creating and editing a product to validate the data directly in the model in adminpanel and forms and if validated return an error more or less like this: models.py class Book(Product): GENRE_CHOICES = ( ('Fantasy', 'Fantasy'), ('Sci-Fi', 'Sci-Fi'), ('Romance', 'Romance'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Criminal', 'Criminal'), ('Biography', 'Biography'), ) author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) def save(self): try: Book.objects.get(author=self.author, title=self.title, genre=self.genre) raise ValueError("Author, title and genre must not be repeated") except ObjectDoesNotExist: super().save() Author, title and genre cannot repeat as tuple. Of course, overriding the save() method throws me an error when I try to use the already created model to add to the cart, etc.... Please help me on how I should do it. Thank you all -
Not show any product after submit
#React Code function RecScreen() { const \[budget, setBudget\] = useState(products); const \[items, setParts\] = useState(\[\]); const handleInputChange = (event) =\> { setBudget(event.target.value); }; const handleSubmit = async (event) =\> { event.preventDefault(); const response = await fetch(`/api/products?price=${budget}`); const data = await response.json(); setParts(data.product); }; return ( \<div\> <h1>PC Parts Recommender</h1> \<form onSubmit={handleSubmit}\> \<label\> Enter your budget: \<input type="number" value={budget} onChange={handleInputChange} /\> \</label\> \<button className='btn btn-warning rounded ms-1' type="submit"\>Recommend Parts\</button\> \</form\> <ul> {items.map(product =\> ( <li key={product.id}>{product.name} - ${product.price}</li> ))} </ul> \</div\> ); } export default RecScreen;' In this I tried to create a recommendation where user enter budget and he will get all parts of pc with in budget. #Django Code @require_GET def get_parts(request): budget = request.GET.get('budget') parts = [ {'id': 2, 'category': 'power supply', 'price': 8000}, {'id': 3, 'category': 'gpu', 'price': 400}, {'id': 4, 'category': 'mouse', 'price': 100}, {'id': 5, 'category': 'case', 'price': 50}, {'id': 8, 'category': 'ram', 'price': 80}, {'id': 9, 'category': 'processsor', 'price': 70}, ] parts_within_budget = [part for part in parts if part['price'] <= int(budget)] sorted_parts = sorted(parts_within_budget, key=itemgetter('price')) return JsonResponse(sorted_parts, safe=False) help me in this code after submit it not show any product in screen In this I tried to create a recommendation where user enter … -
Error when updating one field only Django Update method
I have a usecase model which has two foreign keys: kpi and usecase_type I created a method to update those two fields from dropdown list, The method only updates if I update all the fields (shows an error if update one dropdown list) , any idea what could be the reason? My views.py: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) context = {"usecase_details":usecase_details[0], "usecase_types": UsecaseType.objects.all(), "usecase_kpis": Kpi.objects.all()} if request.method == "POST": usecase_type = request.POST['usecase_type'] kpi = request.POST['kpi'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.usecase_type_id=usecase_type usecase_details.kpi_id=kpi usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) return render(request, 'UpdateUsecase.html', context) except: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) my template: <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex "> <div class="card-body d-flex "> <div class="row mb-4"> <div class="card-body"> <div class="row col-12"> <div class="mb-4"> <h4 class="h4 uc-header">Edit usecase details:</h4> </div> <!-- <li role="separator" class="dropdown-divider border-black mb-3 ml-3"></li> --> <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="project-name">Usecase Type:</label> <select name="usecase_type" class="custom-select my-1 mr-sm-2" id="usecase_type"> <option value="0" selected>{{usecase_details.usecase_type.usecase_type_name}}</option> {% for usecase_type in usecase_types %} <option value="{{ usecase_type.usecase_type_id }}">{{ usecase_type.usecase_type_name }}</option> {% endfor %} </select> … -
can you add hidden field to django orm object?
I am fairly new to django so bear with me. but is it possible to implement something similiar to laravel's hidden array: $hidden = ['password', ] in django? I intend to use it in the same manner as the laravel code, to hide the password field from being returned everytime i get a user object from the database. I searched all over the internet for a solution for this but i couldn't find anyone mentioning the topic. -
Want to get popular user
I need help with a Django app am working on, so I am trying to get popular users. I want to archive this by getting all the likes on the post a particular user has created. -
Unable to update models with File field on Django admin or through post method
I have a Django application in the production environment. It works fine when I use runserver by IP address, even in the production environment. but when I try to access it through domain it does not allow me to update the file field (Image Field) the request takes too long and I keep getting <method 'read' of 'lsapi_wsgi.InputStream' objects> returned NULL without setting an error in my error log and it does not even allow me to login to Django admin page on PC's(only Mobile). full trace error SystemError at /admin/accounts/user/1/change/ <method 'read' of 'lsapi_wsgi.InputStream' objects> returned NULL without setting an error Request Method: POST Request URL: https://dev.temarico.com/admin/accounts/user/1/change/ Django Version: 4.1.7 Exception Type: SystemError Exception Value: <method 'read' of 'lsapi_wsgi.InputStream' objects> returned NULL without setting an error Exception Location: /home/temaricocom/virtualenv/API/Backends/3.8/lib/python3.8/site-packages/django/core/handlers/wsgi.py, line 28, in _read_limited Raised during: django.contrib.admin.options.change_view Python Executable: /home/temaricocom/virtualenv/API/Backends/3.8/bin/python Python Version: 3.8.12 Python Path: ['/home/temaricocom/API/Backends', '', '/home/temaricocom/API/Backends', '/opt/alt/python38/lib64/python38.zip', '/opt/alt/python38/lib64/python3.8', '/opt/alt/python38/lib64/python3.8/lib-dynload', '/home/temaricocom/virtualenv/API/Backends/3.8/lib64/python3.8/site-packages', '/home/temaricocom/virtualenv/API/Backends/3.8/lib/python3.8/site-packages'] Server time: Sun, 19 Mar 2023 09:45:19 +0300 -
creating user based collaborative filter in Django
I want to create a User-Based collaborative filter for an e-commerce here are my steps Create an event model with foreign key relation to a product and a user first I create an event and a recommendation model class Event(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name="user_event_set") product = models.ForeignKey('product.Product', models.CASCADE, related_name="product_event_list") created_at = models.DateTimeField(auto_now_add=True) class EventType(models.IntegerChoices): seen = 1, "Visited the product page" cart = 2, "Added to cart" bought = 3, "User purchased the product" searched = 4, "User searched for the product" event_type = models.IntegerField(choices=EventType.choices) class Recommendation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name="user_recommended_set") product = models.ForeignKey('product.Product', models.CASCADE, related_name="product_recommended_set") created_at = models.DateTimeField(auto_now_add=True) now to get similar product here's my code: to get similar users, I get all users def get_similar_users(user, limit=5): all_users = User.objects.exclude(id=user.id).prefetch_related('user_event_set') similarities = [(other_user, calculate_similarity(user, other_user)) for other_user in all_users] similarities.sort(key=lambda x: x[2], reverse=True) return [user_similarity[0] for user_similarity in similarities[:limit]] calculate the similarity using this function: def calculate_similarity(user1, user2): user1_events = set(user1.user_event_list.values_list('product_id', flat=True)) user2_events = set(user2.user_event_list.values_list('product_id', flat=True)) intersection = user1_events & user2_events union = user1_events | user2_events similarity = len(intersection) / len(union) if len(union) > 0 else 0 weight = intersection.aggregate(weight=models.Sum('event_type')) #return by event priority return similarity, weight I'm using the weight to sort the users by it … -
django.core.serializers.base.DeserializationError: Problem installing fixture '/opt/my-api/mynetwork_common/fixtures/emoji-groups.json'
I'm running Django rest api with django 3.2 and docker on GCP Ubuntu 22.04. I'm getting an error when I run the web server container : django.core.serializers.base.DeserializationError: Problem installing fixture '/opt/my-api/mynetwork_common/fixtures/emoji-groups.json' The detailed trace is here : my-api-webserver | Traceback (most recent call last): my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/serializers/json.py", line 69, in Deserializer my-api-webserver | objects = json.loads(stream_or_string) my-api-webserver | File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads my-api-webserver | return _default_decoder.decode(s) my-api-webserver | File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode my-api-webserver | obj, end = self.raw_decode(s, idx=_w(s, 0).end()) my-api-webserver | File "/usr/local/lib/python3.8/json/decoder.py", line 355, in raw_decode my-api-webserver | raise JSONDecodeError("Expecting value", s, err.value) from None my-api-webserver | json.decoder.JSONDecodeError: Expecting value: line 11 column 28 (char 266) my-api-webserver | my-api-webserver | The above exception was the direct cause of the following exception: my-api-webserver | my-api-webserver | Traceback (most recent call last): my-api-webserver | File "manage.py", line 25, in <module> my-api-webserver | execute_from_command_line(sys.argv) my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line my-api-webserver | utility.execute() my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute my-api-webserver | self.fetch_command(subcommand).run_from_argv(self.argv) my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv my-api-webserver | self.execute(*args, **cmd_options) my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute my-api-webserver | output = self.handle(*args, **options) my-api-webserver | File "/usr/local/lib/python3.8/site-packages/modeltranslation/management/commands/loaddata.py", … -
How can I use python django
I am sorry if the answer is obvious but I wasn't so sure and would like to get a clear answer on this, lets say I want to make a website with like chatbots in it, can I use the frontend to be html and css and than use python django to link backend with a database like AWS. If this is possible how exactly could I do this, also is there a better way to do this. I mostly want to do this as I want to learn more about backend coding, if there are better things to focus on please let me know. Thank you all. I have made a front end with html/css but now I am trying to learn django to see what I can do further. I haven't done anything with JS or AWS. -
Django CreateView ManyToManyField register error
class Categories(models.Model): name = models.CharField(max_length=125) class Companies(models.Model): name = models.CharField(max_length=125) class CompanyRights(models.Model): company = models.OneToOneField(Companies, on_delete=models.CASCADE, related_name='coms') category = models.ManyToManyField(Categories, related_name='cats') date = models.DateField(auto_created=True) class Products(models.Model): cat = models.ForeignKey(CompanyRights, on_delete=models.CASCADE) company = models.ForeignKey(Firmalar, on_delete=models.CASCADE, related_name='procom') I am using class based CreateView. I save the category rights of the company that registered the product to CompanyRights. The company shows data from this table for product Categories while registering products. When I try to save a product: Cannot assign "3": "Products.cat" must be a "CompanyRights" instance. zeq, thanks -
403 Forbidden in Xcode Simulator but works fine with Xcode Canvas Preview
I'm wrote a Login page with SwiftUI, and a backend with Django(both running in my laptop) the login api works fine no matter using Postman or in Xcode Canvas Preview but when I run the Xcode Project with Simulator, the Login func would fail the backend returns 403 forbidden Funny thing is, it works fine until yesterday, and I didn't change the code, just suddenly it won't work in the simulator Can anyone tell me what's going on here? and how can I fix it? Thanks! I tried to disable the csrf middleware in Django setting.py, and it didn't work -
Cannot pass CSRF token in post request from react to django rest framework api
I am making a django/react website. I am trying to make a post request to my backend api using a CSRF token in the header of the request. Genre.js // I have an endpoint that is supplying the CSRF token, and I am fetching that on the frontend, and then making the post request. import React, { useState, useEffect } from "react"; function Genres() { const [genres, setGenres] = useState([]); useEffect(() => { fetch("/api/genres/") .then((response) => response.json()) .then((data) => setGenres(data.genres)) .catch((error) => console.log(error)); }, []); function handleClick(genre) { const query_params = { genre: genre, }; console.log(query_params); fetch('/api/get_csrf_token/') .then(response => response.json()) .then(data=> {fetch("/api/search/", { method: "POST", headers: { "Content-Type": "application/json", 'X-CSRFToken': data.csrftoken, }, body: JSON.stringify(query_params), }) .then((response) => response.json()) .then((data) => console.log(data))}) .catch((error) => console.log(error)); } return ( <div> <div className="genre-list-container"> <ul className="genre-list"> {genres.map((genre) => ( <li className="genre" onClick={() => handleClick(genre)} key={genre} > {genre} </li> ))} </ul> </div> </div> ); } export default Genres; views.py // I have a view to get the token def get_csrf_token(request): return JsonResponse({'csrfToken': request.COOKIES['csrftoken']}) settings.py // These are the lines I've added MIDDLEWARE =[ 'corsheaders.middleware.CorsMiddleware', ... 'django.middleware.csrf.CsrfViewMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True API_ALLOWED_HOSTS = ['http://localhost:3000'] CSRF_TRUSTED_ORIGINS = ['http://localhost:3000'] My error: [18/Mar/2023 22:36:14] "GET /api/get_csrf_token/ HTTP/1.1" 200 … -
Django models, How do you pass datetime instead of a Datefield to validators?
I realize that validators need to be simple, however, I still rather use them instead of using the "clean/save functions" for this case. What I have is a model called user (aka an employee) that has a joinDate and an exitDate. exitDate can be empty, however, when they are filled they need to be AFTER the joinDate (obviously). class user(models.Model): joinDate = models.DateField() exitDate = models.DateField(null=True, blank=True, default=None, validators=[secondDateAfterFirstDateValidator(joinDate)]) And the validator is a function that returns a function, just like it was recommended by this post Is it possible to have validators with parameters? def secondDateAfterFirstDateValidator(joinDate): def innerfn(value): if value < joinDate: raise ValidationError("The exitDate must be after the joinDate") return innerfn The error I get is: '<' not supported between instances of 'datetime.date' and 'DateField' Now, the value that is being passed is what the validator is passing, which is the value of the DateField that the validator is being passed to (which is the exitDate). And this gets automatically converted from models.Datefield to 'datetime.date'. However, it seems that when you pass to the validator the joinDate, it does not convert it to an instance of 'datetime.date' and keeps it as a models.Datefield. How do I resolve this … -
How can I integrate a Quasar Vue.js application into my Django project?
I have a Django project that serves as the back-end for my application, and I want to use Quasar as the front-end framework. I have already created a Quasar application using the quasar create command and it works fine when I run it separately. Now, I want to integrate this Quasar application into my Django project so that it can be served by Django's development server. `STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/dist/spa') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') from django.http import JsonResponse def my_api_view(request): # handle the API call here # return a JSON response data = {'message': 'Hello, world!'} return JsonResponse(data) ` -
CQRS: Should I extend my write model with some denormalized read fields?
I'm writing an app based on event sourcing and CQRS principles. The app is basically a "transaction tracker" and to exemplify the problem we can think that each Transaction is linked to an Asset. class Asset(models.Model): code = models.CharField(...) current_price = models.DecimalField(...) sector = models.CharField(...) ... def get_roi(self, percentage: bool = False) -> Decimal: # Expensive calculation using several joins in multiple tables return self.transactions.roi(incomes=self.incomes.sum(), percentage=percentage)["ROI"] class Transaction(models.Model): asset = models.ForeignKey(to=Asset, on_delete=models.CASCADE, related_name="transactions") ... class Income(models.Model): asset = models.ForeignKey(to=Asset, on_delete=models.CASCADE, related_name="incomes") ... My list endpoints for the assets has several fields that are costly to calculate in a normalized DB. Those fields changes if: a Transaction is created or deleted an Income is created or deleted current_price changes In order to scale and for several other reasons that you probably already know I want to separate those computational-costly fields from the write model. My questioning arises from the fact that a read model would have to have some fields that will probably never change and that has no relation with the events above. For example, I have a report that aggregates the ROIs per sector. With a read model I must have a sector field to generate this report. If … -
installation of Django => install virtual environment => set Virtual environment
I can't setting up the virtual environment will allow you to edit the dependency which generally your system wouldn’t allow virtualenv env_site 'virtualenv' is not recognized as an internal or external command, operable program or batch file. I want to set up a virtual environment will allow me to edit the dependency wich generally your system wouldn't allow -
Validation error when try to update table with uuid foreign key, django 4.2
This may be easy, but I have not been able to solve the issue I have 2 models wwith oneToMany relation. I am try to update the child table using foreign key of parent table, but it is returning this error: ValidationError at /StudentParentsAssign/01b93b30-e5fb-49f8-9394-94a824b7a099/ ['“c0ea3f3e-bb79-4fc5-9fd9-6bce341324d1,” is not a valid UUID.'] Below is my code: Models.py #Modeles.py class Student(models.Model): #std_matricule = models.CharField(verbose_name='Student matricule', max_length=6, null=False, unique=True, primary_key=True) std_matricule = models.CharField(verbose_name='Matricule', unique=True, max_length=16, null=False, blank=False, help_text='Matricule of the student') std_parents = models.ForeignKey(Parents, on_delete=models.DO_NOTHING, related_name='Parents', unique=False, null=True, blank=True, verbose_name='Student parents') class Parents(models.Model): father_surname = models.CharField(verbose_name='Father surname', max_length=128, null=False, blank=True, help_text='Student Father surname as in the birth certificate') father_firstName = models.CharField(verbose_name='Father name', max_length=128, null=False, blank=True) parent_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) .... view.py #view.py def StudentParentsAssign(request, pk): # parents_list = Parents.objects.all().order_by('father_surname') std = Student.objects.get(student_id = pk) if std.std_parents not in (None, ''): # parentsList = Parents.objects.all().order_by('father_surname') context = {'studentObj': std} return render(request, "students_management_app/student_template/student-single.html", context) else: if request.method == "POST": perents_id = request.POST.get('radio') Student.objects.filter(pk=pk).update(std_parents=perents_id) parentList = Parents.objects.filter(parents_deleteStatus=False).order_by('-parent_createDate') context = {'parentList': parentList} return render(request, "students_management_app/student_template/student-parents-list.html", context) url.py #url.py path('StudentParentsAssign/<uuid:pk>/', views.StudentParentsAssign, name = 'student-parents-list'), Template #Template {% block content %} <h1>List of all parents</h1> {% if parentList %} <form action="", method="POST"> {% csrf_token %} <button type="submit">Assign the … -
How to load Plotly graphs fast in a webpage?
I am using Django to create my first website. I have some complex plots made with Plotly which get passed to the render function as html (saved using to_html function). For example: def sample_plot(): import numpy as np import pandas as pd import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Barpolar( r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5], name='11-14 m/s', marker_color='rgb(106,81,163)' )) fig.add_trace(go.Barpolar( r=[57.5, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5, 55.0], name='8-11 m/s', marker_color='rgb(158,154,200)' )) fig.add_trace(go.Barpolar( r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0], name='5-8 m/s', marker_color='rgb(203,201,226)' )) fig.add_trace(go.Barpolar( r=[20.0, 7.5, 15.0, 22.5, 2.5, 2.5, 12.5, 22.5], name='< 5 m/s', marker_color='rgb(242,240,247)' )) fig.update_traces(text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W']) fig.update_layout( title='Wind Speed Distribution in Laurel, NE', font_size=16, legend_font_size=16, polar_radialaxis_ticksuffix='%', polar_angularaxis_rotation=90, ) return fig.to_html(config={'displayModeBar': False}) Just passing this plot to the webpage increases loading time by 2.1 seconds (using local server and same conditions). I have a few plots as complex as this one so the loading times make the webpage unusable. Is this behaviour expected? Is there a better approach than using to_html to render the Plotly graphs? or is Plotly a non starter for webpage plots? Sorry if it is a basic mistake, it is my first website. -
How can I properly save dropzone files from existing django form and get it from DB when need?
I am trying to handle drag&drop uploads with my django app and facing lack of actual information about dropzone + django. Previously I used just a multiple upload, as you could see below, and it worked great, but it is a time to handle drag&drop thing, cause it a way more convenient. I handled it to be inside my main form, but I totally don't understand how I suppose to save this files and get them from DB in template, when I need it. Maybe, somebody can help me with that? Don't be too angry on me, I am not an experienced JS user.. models.py class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField( max_length=200, ) ... class PostImages(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='images', ) file = models.FileField( upload_to="posts/images", validators=[], ) views.py class PostCreateView(AuthRequiredMixin, SuccessMessageMixin, View): template_name = 'create_post.html' model = Post form = PostCreationForm success_url = reverse_lazy('index') success_message = _('Post created successfully') def get(self, request, *args, **kwargs): form = self.form() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() form.save() for img in request.FILES.getlist('images'): data = img.read() new_file = PostImages(post=new_post) new_file.file.save(img.name, ContentFile(data)) … -
How to speed up or parallize a django function with multiple sequential filters and inserts?
I am doing some backtesting in python and have my DB models in Django set up as follows. One is a stock DB keyed by the symbol and one is a price DB keyed by symbol + date. Something like this: Stock DB: FB MSFT Goog Price DB: FB | 1/1/2023 | 150.0 FB | 1/2/2023 | 151.0 FB | 1/3/2023 | 160 I then run my backtesting algo to do something like for stock in stock_list: prices = Price.objects.filter(stock=stock) backtest = run_backtest(prices) Basically trying to optimize this for 500-1000 tickers and what I've noticed is the biggest bottleneck is "Price.objects.filter(stock=stock)" since it has to fetch brand new prices for each backtest. How can I best speed up the filters? Should I try something like loading 5 symbols at a time and then filtering from that? Or a second thread to fetch the next symbol as the first backtest is running? Is there something I'm missing here? I feel like I can speed this up 10-20x easily. Thanks! -
Django doesn't display that user exist
I learned Django from course but I have a problem. I can register and login. If password's doesn't match it display validate error but it doesn't display an error if user exist. OK. My view's method looks like this def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] sex = form.cleaned_data['sex'] user = Account.objects.create_user(username=username, email=email, password=password, sex=sex) user.save() messages.success(request, 'Udało Ci się zarejestrować!') return redirect('register') context = { 'form': form } return render(request, 'accounts/register.html', context) else: form = RegistrationForm() context = { 'form': form } return render(request, 'accounts/register.html', context) My forms password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'Enter Password', 'class': 'form-control' })) confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'Confirm Password', 'class': "form-control" })) class Meta: model = Account fields = ['username', 'sex', 'email', 'password'] def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control' def clean(self): cleaned_data = super(RegistrationForm, self).clean() password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError( 'Password doesn not match!' ) And models class MyAccountManager(BaseUserManager): def create_user(self, username, email, sex, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') if not sex: …