Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
*ModuleNotFoundError: No module named 'xhtml2pdf'*
I have a simple Django web site when I compile my code I can get this error: ModuleNotFoundError: No module named 'xhtml2pdf' -
Django Many to One + Dynamic Forms
I am working on defining the models for my Django web app, which is a quote generator. Each quote will contain N number of different measurements (driveway, sidewalk, porch, etc) that will be stored and then used to calculate the total price per service. Is there a way I can structure the models to implement DRY so I don't have to code out each element of a quote? Additionally, is there a way in Django forms to allow a variable number of Measurement for each quote? models.py class Quote(models.Model): quoteDate = models.DateTimeField(auto_now_add=True) customerLastName = models.CharField(max_length=80) customerFirstName = models.CharField(max_length=50) ServiceRep = models.ForeignKey( User, on_delete=models.SET_NULL) orderNumber = models.IntegerField() #varying number of Measurements here class Measurement(models.Model): name = models.CharField(max_length=250) description = models.CharField(max_length = 250) length = models.FloatField(blank=True, null=True) width = models.FloatField(blank=True, null=True) flat_fee = models.FloatField(blank=True, null=True) quote = models.ForeignKey(Quote, on_delete = models.SET_NULL) -
Requesting guidance on how to create a Django Admin with multi-tenancy support
I am requesting help to create a custom Django admin site for a multi-tenant B2B ecommerce platform. I am still new to Django and building SaaS like applications. Any help to understanding this will be highly appreciated. I would like this admin dashboard to be able: To create, update, manage each tenant user, where we can update and manage their storefront and their own users and products. Have each tenant have their own admin dashboard that only they have access to, where they can manage their own users and products. To have super admin capabilities to push changes to all tenants. Thank you! -
I am getting a MultiValueDictKeyError when I'm trying to post a multiple choice form field to database
I have a form setup that Is meant to supplement my main signup form by adding more data to the user database, It is a multiple choice form. Here is the specifics of the error I am getting. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/register/more Django Version: 3.2.2 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage', 'register.apps.RegisterConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback (most recent call last): File "C:\Users\david\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('minfo'), another exception occurred: File "C:\Users\david\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\david\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\david\OneDrive\Desktop\Django\myapp\register\views.py", line 19, in moreinfo minfo = request.POST['minfo'] File "C:\Users\david\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /register/more It seems like it has something to do with a line in my views.py file, specifically: minfo = request.POST['minfo'] -
How can i change the location of the Django admin search-box?
enter image description here I want to move the search box and action box on the Django-admin page to the bottom of the page. I already found the Django-admin change_list.html file, but i don't know how to change it... How do I do it? -
How to split groupby fields when deriving queryset results in Django
[views.py] annotations = {} types = ('A', 'B') for type in types: annotations[type] = Count('id', filter=Q(type=type)) annotations[f'R_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Recruiting')) annotations[f'N_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Not yet recruiting'))) counts = Study.objects.filter(is_deleted=0) \ .values('teacher') .annotate(**annotations).values('teacher', *annotations.keys()) By grouping teachers, we got the count for each teacher. Here is the result: <QuerySet [ {'teacher': 'Helen', 'A': 1, 'R_A': 1, 'N_A': 0, 'B': 3, 'R_B': 2, 'N_B': 0}, {'teacher': 'Helen/Jennie', 'A': 0, 'R_A': 0, 'N_A': 0, 'B': 1, 'R_B': 0, 'N_B': 0}, {'teacher': 'Jennie', 'A': 0, 'R_A': 0, 'N_A': 0, 'B': 1, 'R_B': 0, 'N_B': 0}] > However, when grouping teachers, I want to split them based on "/" and add a count for each teacher to output the following results. <QuerySet [ {'teacher': 'Helen', 'A': 1, 'R_A': 1, 'N_A': 0, 'B': 4, 'R_B': 2, 'N_B': 0}, {'teacher': 'Jennie', 'A': 0, 'R_A': 0, 'N_A': 0, 'B': 2, 'R_B': 0, 'N_B': 0}] > However, splitting in values is not possible. If you have a workaround please help me. -
Using ASP.net PasswordHash in Django for authentication
I have a database created by someone using C# .Netframework and now I need to create API using Django and connect this API to the same database. But I can't compare PasswordHash created by .Net with CreateAsync function. I have already researched how CreateAsync works this was very helpful and I tried with Python to get the same hash, but I failed. Can someone help me? python code import base64 import hashlib PassHash = "AQAAAAEAACcQAAAAEJa4CYSXaNB9U7+mWQYqg1GcO/tWRlrvqvBwGWEl/0W7tNKcxTOVUjeBq8OoYWsCEA==" bytes = base64.b64decode(PassHash) salt=bytes[0x0E:0x1E] # bytes from 14 to 29 hash=bytes[0x1E:0x3D].hex() # bytes from 30 to 61 password = "hello world" #this pass in not real password = password.encode() password_hash = hashlib.pbkdf2_hmac("SHA256", salt,password,10000) print(password_hash.hex()) -
swapping entries of 2 records
#models.py class Numbers(TimeStampMixin): name = models.CharField(max_length=20) number = models.IntegerField() def __str__(self): return self.name #Dashboard output NAME NUMBER imageURL1 1 imageURL2 2 imageURL3 3 imageURL4 4 My goal is to allow an admin to determine the position of the image in the table after the fact. So that they can be displayed on the homepage in a different order. (without js) #imageURL? is just an image upload is there a way that when an admin, changes the number of imageURL1 to "2", that then automatically changes the number of imageURL2 to "1" and so on? -
Django/React/Axios Updating an image is sending a string value instead of updating the image
I am trying to develop a website for an alumni organization. I have a table for events with several fields, two of which being image fields. I can successfully create the event with all fields, but I cannot update it like intended. When I try to update, I can only a single field, if I change the picture as well. I think it is sending the URL of where the photo is located as a string, so I get the error "the file is not the expected format, but if I upload an image, it works as intended. I'd like to be able to update other fields without having to also change the picture. The image fields are gallery and banner_image (I'm just trying to get the problem fixed with one for now and they are at the bottom of the form. I have my axios http functions in a seperate file. import React, { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import { getEventById, updateEventById } from "../../../api/apiCalls"; const EventUpdate = () => { const { id } = useParams(); const [event_name, setEventName] = useState(""); const [date, setDate] = useState(""); const [time, setTime] = useState(""); … -
How to change DRF API SlugRelatedField Response template
I have managed to create working model with 2 different serializers, depending what we are doing. Right now, ReadTitleSerializer returns this JSON object: [ { "id": 1, "category": { "id": 1, "name": "Movies", "slug": "movie" }, "genres": [ { "id": 1, "name": "Drama", "slug": "drama" } ], "name": "Drama Llama", "year": "1998-02-02", "description": null, "rating": null } ] And this is response from WriteTitleSerializer: { "id": 1, "category": "movie", "genres": [ "drama" ], "name": "Drama Llama", "year": "1998-02-02", "description": null, "rating": null } How can I make WriteTitleSerializer respond similar to ReadTitleSerializer? I am using SlugRelatedField in WriteTitleSerializer because the JSON input should be list of slugs. Input JSON { "name": "Drama Llama", "year": "1998-02-02", "category": "movie", "genres": [ "drama" ] } serializers.py class ReadTitleSerializer(serializers.ModelSerializer): category = CategorySerializer() genres = GenreSerializer(many=True) class Meta: model = Title fields = '__all__' read_only_fields = ('category', 'genres') class WriteTitleSerializer(serializers.ModelSerializer): category = SlugRelatedField( slug_field='slug', queryset=Category.objects.all(), required=True ) genres = SlugRelatedField( slug_field='slug', queryset=Genre.objects.all(), many=True, required=True ) class Meta: model = Title fields = '__all__' -
how to query a postgres table from a django app using sql
I have created a django application, i am currently inside an aws ec2 instance, to be specific i am trying everything inside the python interpreter, which means after typing **python3**. I have passed all the rds postgres db credentials and it created the connection. and created the table in django as: class Person(models.Model): # just an example .... now from inside the python interpreter import psycopg2 conn = psycopg2.connect(host=host, database=database, user=user, password=password) cur = conn.cursor() cur.execute("""SELECT * FROM Person""") # it fails here row = cur.fetchall() and i am getting the result psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block is there something that i am missing? how can i correctly query the table Person in sql? -
RBAC on DjangoRestFramework
How best to implement RBAC on DRF? I need the database objects to be separated and users to see only those that we will allow to see. A possible example of work: An authorized Backend request, response with all objects that have access -
Django collect static S3 An error occurred (403) when calling the HeadObject operation: Forbidden
I have created a S3 bucket for my Django static files. I am able to display the static files from S3 however when I run the python manage.py collectstatic command I get the error "An error occurred (403) when calling the HeadObject operation: Forbidden" error traceback Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/john/Environments/PRM/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/john/Environments/PRM/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/john/Environments/PRM/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/john/Environments/PRM/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/john/Environments/PRM/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/Users/john/Environments/PRM/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/Users/john/Environments/PRM/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/Users/john/Environments/PRM/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/Users/john/Environments/PRM/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 469, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "/Users/john/Environments/PRM/lib/python3.6/site-packages/botocore/client.py", line 391, in _api_call return self._make_api_call(operation_name, kwargs) File "/Users/john/Environments/PRM/lib/python3.6/site-packages/botocore/client.py", line 719, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden base_settings.py # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings STATIC_URL = … -
How to make calculation inside django annotate?
This one when I run generates error: qs = UserLocation.objects.annotate(distance=0.5 - cos((F('lat')-lat1)*p)/2 + cos(lat1*p) * cos(F('lat')*p) * (1-cos((F('long')-lon1)*p))/2).all() The error it generates is this one: must be real number, not CombinedExpression How can I make that calculation as an annotation -
Django.request is not showing synchronous middleware as docs suggest
I've set up a very simple asynchronous view but it's not working. As per the Django instructions I want to check that it's not my middleware causing the issue. The Django docs say that the django.request logger will disclose which middleware is not working in async. Below is the quote from the official docs. I've set up the django.request logger and it logs an 4xx or 5xx errors (as expected) but that's all. Is this a mistake in the Django docs? https://docs.djangoproject.com/en/4.0/topics/async/ You will only get the benefits of a fully-asynchronous request stack if you have no synchronous middleware loaded into your site. If there is a piece of synchronous middleware, then Django must use a thread per request to safely emulate a synchronous environment for it. Middleware can be built to support both sync and async contexts. Some of Django’s middleware is built like this, but not all. To see what middleware Django has to adapt, you can turn on debug logging for the django.request logger and look for log messages about “Synchronous middleware … adapted”. settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', … -
What is the most efficient way for calculating SLA?
I am trying to figure out how can I improve my code. So basicaly there is a website and there are some events which user can do it. We are giving some summary about event result to user and SLA is one of them. If I want to calculate event SLA, I can do it by retrieving the object and subtracting start_time from end_time. Related Model: class Event(models.Model): ... start_time = models.DateTimeField() end_time = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) ... My code for calculating SLA is below. events = Event.objects.all() tmp_sla = 0 for event in events: time_difference = event.end_time - event.start_time tmp_sla += time_difference // 60 # convert seconds to minute average_sla = tmp_sla // events.count() The problem is there are so many events and many users. This is causing long calculating time. And sometimes I need to use more than one for loop to calculate it. Calculation time taking even longer. Is there any built-in Django function for this? Or how can I improve my codes? Thanks in advance. -
pytest -rP logs twice for each test
I'm building a test suite for a small Django app and am using pytest. When I run the tests with docker-composec -f local.yml run --rm django pytest -rP, it logs each test twice. I added a timestamp to the function being tested (2022-02-20 20:57:32.196975+00:00) and they are identical so I don't think its running the tests twice, but outputting them twice. _______________________________________________________________________________________________________ TestAggregateTiltReadings.test_initial_run _______________________________________________________________________________________________________ ------------------------------------------------------------------------------------------------------------------ Captured stderr call ------------------------------------------------------------------------------------------------------------------ INFO 2022-02-20 20:57:32,196 services 1 140188905805632 2022-02-20 20:57:32.196975+00:00 INFO 2022-02-20 20:57:32,197 services 1 140188905805632 Aggregating 4 new tilt readings ------------------------------------------------------------------------------------------------------------------- Captured log call -------------------------------------------------------------------------------------------------------------------- INFO brew_dash.tilts.services:services.py:33 2022-02-20 20:57:32.196975+00:00 INFO brew_dash.tilts.services:services.py:34 Aggregating 4 new tilt readings _______________________________________________________________________________________________________ TestAggregateTiltReadings.test_initial_run _______________________________________________________________________________________________________ ------------------------------------------------------------------------------------------------------------------ Captured stderr call ------------------------------------------------------------------------------------------------------------------ INFO 2022-02-20 20:57:32,196 services 1 140188905805632 2022-02-20 20:57:32.196975+00:00 INFO 2022-02-20 20:57:32,197 services 1 140188905805632 Aggregating 4 new tilt readings ------------------------------------------------------------------------------------------------------------------- Captured log call -------------------------------------------------------------------------------------------------------------------- INFO brew_dash.tilts.services:services.py:33 2022-02-20 20:57:32.196975+00:00 INFO brew_dash.tilts.services:services.py:34 Aggregating 4 new tilt readings I used cookiecutter-django to start the app and am using the default settings. I'm not sure what configs to share which might be helpful to troubleshoot this. I can add some if there are any ideas. -
How to deploy django, reactjs with oracle 19c in google cloud platform compute engine vm cpanel image?
I am newbie in cpanel. I have developed a webapp with django, reactjs with oracle 19c. This is running smothly in windows 10 local machine. Now i want to use it google cloud platform compute engine with vm cpanel image. Is it possible? Or please suggest me that how does i will run this smoothly. Thanks in advance. -
django serializer field not recognizing attribute clearly defined
when i try to run a view I get this error: AttributeError: Got AttributeError when attempting to get a value for field `inreplytouser` on serializer `ContentFeedPostCommentSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'inreplytouser'. Here is my model: class ContentFeedPostComments(models.Model): inreplytouser = models.ForeignKey(SiteUsers, null=True, related_name='replytouser', blank=True, on_delete=models.CASCADE) inreplytotopcomment = models.BigIntegerField(null=True, blank=True) timecommented = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(SiteUsers, on_delete=models.CASCADE) contentcreator = models.ForeignKey(ContentCreatorUsers, on_delete=models.CASCADE) contentfeedpost = models.ForeignKey(ContentFeedPost, on_delete=models.CASCADE) text = models.CharField(max_length=1000) here is the serializer: class ContentFeedPostCommentSerializer(ModelSerializer): id = IntegerField() inreplytouser = SiteusersSerializer() user = SiteusersSerializer() contentcreator = ContentCreatorSerializer() class Meta: model = ContentFeedPostComments fields = ('id','inreplytouser', 'inreplytotopcomment', 'timecommented', 'user', 'contentcreator', 'contentfeedpost', 'text') here is the view: class ContentFeedPostsComments(APIView): def get(self, request, *args, **kwargs): postid = kwargs.get('postid') contentfeedpost = get_object_or_404(ContentFeedPost, id=postid) topcomments = ContentFeedPostComments.objects.filter(contentfeedpost= contentfeedpost, inreplytotopcomment= None).order_by('timecommented') replycomments = ContentFeedPostComments.objects.filter( contentfeedpost = contentfeedpost, inreplytotopcomment__isnull = False).order_by('timecommented') serializedtopcomments = ContentFeedPostCommentSerializer(topcomments) serializedreplycomments = ContentFeedPostCommentSerializer(replycomments) payload = { 'topcomments': serializedtopcomments.data, 'replycomments': serializedreplycomments.data } return Response(payload) I was reading something about source being passsed into the inreplytouser field of the serializer field but that makes no sense. Your wisdom and knowledge on this situation is greatly … -
Django: Unresolved reference, when trying to import an app
I am having issues with importing other apps and could not find a solution on the internet. I get an Unresolved reference 'name'. Project/urls.py from django.contrib import admin from django.urls import path,include from users import views as user_views #'users' and 'views' are underlined in red from homepage import views as homepage_views #same goes for 'homepage' and 'views' urlpatterns = [ path('',include("homepage.urls")), path('register/',user_views.register), path('admin/', admin.site.urls), ] Project/settings.py INSTALLED_APPS = [ 'homepage.apps.HomepageConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Project Structure Project structure Thanks for your help and let me know if u need more information -
Default date won't set mock date when saving instance
There is an issue mocking the date.today() method when create an instance of the Question model through a ModelForm. The default date that is stored with the instance is date(2022, 2, 20) when it should be date(2021, 12, 9). The import path of the object to patch is "posts.models.date" and models.py in fact has the import statement from datetime import date. What needs to be changed in order for the date to be mocked properly where the instance has the date as defined in the testcase? posts.test.test_forms.py from datetime import date from unittest.mock import Mock, patch class TestDuplicateQuestionPosted(TestCase): '''Verify that a User cannot post two questions with the exact same title in the same day.''' @classmethod def setUpTestData(cls): user = get_user_model().objects.create_user("TestUser") cls.profile = Profile.objects.create(user=user) cls.question = Question.objects.create( title="Question Title 001", date=date(2021, 12, 9), body="This is the extra content about my post: Question__0001", profile=cls.profile ) print(Question.objects.all()) def test_duplicate_question_posted_on_same_day(self): with patch("posts.models.date") as mock_date: mock_date.today = date(2021, 12, 9) data = { 'title': "Question Title 001", "body": "This is the extra content about my post: Question__0001", "profile": self.profile } form = QuestionForm(data) self.assertFalse(form.is_valid()) self.assertTrue(form.has_error("title")) self.assertEqual( form.errors.as_data()['title'][0].message, "Cannot post duplicate question" ) posts.models.py from datetime import date class Post(Model): date = DateField(default=date.today) comment = … -
Getting data from plain HTML form into Django User object
I have created my own plain HTML form and I want to get that data into a view to create the default User object. However , I am not being able to get the data from the form, here is my view : def registerPage(request): if request.method == "POST": print(request.POST.get('name')) print(request.POST.get('useremail')) username = request.POST.get('name') email = request.POST.get('useremail') password = request.POST.get('userpassword') user = User.objects.create_user(username, email, password) return HttpResponse("Printed to the console") else: return render(request, 'store/register.html') The console prints "None" as a result. This the HTML : <form class="mx-1 mx-md-4" method="POST" action="http://127.0.0.1:8000/register"> {% csrf_token %} <div class="d-flex flex-row align-items-center mb-4"> <i class="fas fa-user fa-lg me-3 fa-fw"></i> <div class="form-outline flex-fill mb-0"> <input type="text" id="name" class="form-control" /> <label class="form-label" for="name">Your Name</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <i class="fas fa-envelope fa-lg me-3 fa-fw"></i> <div class="form-outline flex-fill mb-0"> <input type="email" id="useremail" class="form-control" /> <label class="form-label" for="useremail">Your Email</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <i class="fas fa-lock fa-lg me-3 fa-fw"></i> <div class="form-outline flex-fill mb-0"> <input type="password" id="userpassword" class="form-control" /> <label class="form-label" for="userpassword">Password</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <i class="fas fa-key fa-lg me-3 fa-fw"></i> <div class="form-outline flex-fill mb-0"> <input type="password" id="form3Example4cd" class="form-control" /> <label class="form-label" for="form3Example4cd">Repeat your password</label> </div> </div> <div class="d-flex justify-content-center … -
Trouble when parsing JSON string
I'm dumping JSON in Django view and then parsing JSON in JS to get the data. My view.py (Django) ibms = [] for i in range(2, 5): ibm = Mapa(i, wsMapa) ibms.append(ibm.__dict__) ibms = json.dumps(ibms) return render(request, 'mapas/index.html', {'ibms': ibms}) The ibm variable output in Django template is: [{"numeroIbm": "AUTO P"}, {"numeroIbm": "PTB"}, {"numeroIbm": "FAROL"}] My index.html (JS inside) {{ ibms|json_script:"ibms" }} <script> const mydata = JSON.parse(document.getElementById("ibms").textContent); const mydata2 = JSON.parse(mydata); </script> The issue is: I'm having to JSON.parse double times to get the JS object. The variable mydata, despite the JSON.parse, is string typeof. I only get the final result when I JSON.parse for the second time (mydata2). What is happening, pls? Tks in advance! -
build an application with django and a data warehouse
I'm working on a Django application but I don't know how to integrate a data warehouse with Django. in fact is it possible to do this idea? -
In Django, ModelAdmin, what is the difference between save_form() and save_formset()?
Can somebody explain the differences and/or similarities between save_form and save_formset from ModelAdmin? The only things i could find about this is from source code. def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() And the docs have only this about save_formset (https://docs.djangoproject.com/en/4.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset) The save_formset method is given the HttpRequest, the parent ModelForm instance and a boolean value based on whether it is adding or changing the parent object.