Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when running tests in django and PostgreSQL DB can't create database
I'm having a problem with running unit tests in django while using ElephantSQL, when running command python manage.py runserver everything works just fine, i'm able to connect to the server without any problem but when running the command python manage.py test i'm getting this error: C:\Users\Sman9\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\siteid running initialization queries against the production database when it's not needed (for example, when running tests). Djang warnings.warn( Got an error creating the test database: permission denied to create database Creating test database for alias 'default'... C:\Users\Sman9\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\postgresql\base.py:323: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Got an error creating the test database: permission denied to create database``` my databases setting in settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '####', 'USER': '#####', 'PASSWORD': '#############', 'HOST': 'chunee.db.elephantsql.com', 'PORT':'', } } } -
How to pass request object from one serializer class to other serializer class in Django
I want to access userId of current logged-in user. for that i need to pass the request object from one serialiser to another. Here's my code class ThreadViewSerializer(serializers.ModelSerializer): op = PostDetailViewSerializer(context={'request': request}) class Meta: model = Thread fields = ('id', 'title', 'op', 'group_id', 'type', 'reference_id', 'is_frozen', 'views', 'is_pinned') In PostDetailViewSerializer, I want to pass request object but for that it requires self object. like this request = self.context.get('request') Thus, How can we pass the request object to PostDetailViewSerializer class in ThreadViewSerializer class. Please help me in this. -
Django template JS variable 'safe' method not passing data to custom js file?
I'm trying to pass a google api key into my custom js file in Django, the function is for a AutoComplete google places api search , but at the moment it's not working, if I put the actual key directly into the .getScript function, like: https://maps.googleapis.com/maps/api/js?key=XXX&libraries=places" then the search function works, but with the current setup also intended to hide the api key, it doesn't work, I'm obviously missing something, appreciate any ideas? django settings: GOOGLE_API_KEY = "XXX" base.html <script src="{% static 'js/google_places.js' %}"></script> views.py {'google_api_key': settings.GOOGLE_API_KEY} google_places.js $.getScript("https://maps.googleapis.com/maps/api/js?key=" + "google_api_key" + "&libraries=places") .done(function( script, textStatus ) { google.maps.event.addDomListener(window, "load", initAutoComplete) }) let autocomplete; function initAutoComplete(){ autocomplete = new google.maps.places.Autocomplete( document.getElementById('autocomplete'), { types: ['country', 'locality'], }) } travel.html {% endblock content %} {% block js %} <script type="text/javascript"> var google_api_key = "{{google_api_key|safe}}"; </script> {% endblock js %} also the google_api_key variable is being passed into travel.html , I've checked that and it's working fine. -
Django s3: (403) when calling the HeadObject operation: Forbidden
I wish to allow registered users of a Django app to upload and view files to an s3 bucket. I can use the bucket to collect static images and view them on the site, but when I upload I get a 403 forbidden error. I've looked at the answers here to many similar questions and tried various different s3 bucket policy templates without success. How can I troubleshoot what is going on, and/or how can I get this working? All help grateful received. Two of the policies i have tried: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": [ "arn:aws:s3:::BUCKETNAME", "arn:aws:s3:::BUCKETNAME/*” ] } ] } { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": [ "arn:aws:s3:::BUCKETNAME/*" ] }, { "Effect": "Allow", "Principal": "*", "Action": "s3:GetBucketLocation", "Resource": [ "arn:aws:s3:::BUCKETNAME" ] } ] } From my settings.py AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_STATIC_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'notes/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) AWS_PUBLIC_MEDIA_LOCATION = 'media/public' DEFAULT_FILE_STORAGE = f'{ROOT_NAME}.storage_backends.PublicMediaStorage' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' … -
How to search and filter on multiple related models?
I am creating an search and filter system in which user can type and search related courses and institutions. This is my model structure: Model Structure: Institutions: - Name - Id - email - address ...... etc. Courses: - owner = models.ForeignKey(Institution, on_delete=models.CASCADE) - name - ref - license - overview ..... etc Now by using the above, i have created a search bar in which user needs to type something and then press "search" button or else press "Enter" key. This will show search results. My search code: query = request.GET.get('q') courses = Course.objects.filter(name__icontains=query) institution= Institution.objects.filter(name__icontains=query) queryset_chain = chain(courses,institution) So the problem here is that, I want to display the result as follows. scenario 1: Lets say that course and Institution has same name like "tech". When user search for "tech", I need to show result as follows: Institution Name Course name scenario 2: Lets say that course has name as "tech" but not Institution has that name. When user search for "tech", I need to show result as follows: In this case, I need to show the Course name and also correspondant Institution name: Institution Name Course name scenario 3: where Institution has "tech" as name. But no … -
none type object has no attribute 'replace'
I'm trying to replace None with 0 but I'm getting an error as none type object has no attribute 'replace'. This is what I have tried views.py: def Activity(UserID): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set =cursor.fetchall() data = [] for row in result_set: TaskId = row[0] data.append({ 'TaskId':row[0], 'TaskName' : row[1], 'Source' : row[2], 'Requester' : row[3].replace('None', '0') if row[3] == None else row[3] , 'type' : row[4], 'IsActive':GetCurrentSubTaskSTatus(TaskId), }) print(data) return Response(data[0], status=status.HTTP_200_OK) -
CSRF token is generated in 127.0.0.1:3000 but not in hosted application
I have a question , when i check cookies in 127.0.0.1:3000 i see that the csrf token is present in those cookies like the picture bellow . But when i check it in the hosted app it doesn't appear and i will not be able to get it to perform authentication . i had the same problem with localhost:3000 so how i can fix this problem ? -
Django - Create downloadable Excel file using Pandas & Class Based View
I'm relatively new to Django and have been looking for a way to export my DataFrame to Excel using Pandas and CBV. I have found this code: from django.http import HttpResponse def my_view(request): # your pandas code here to grab the data response = HttpResponse(my_data, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="foo.xls"' return response It's perfect for a FBV model but how can I manage to tweak it to pass it into get_context_data? Here's my code: class ResultView(TemplateView): template_name = 'tool/result.html' # def get(self, request, *args, **kwargs): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user context['result'] = self.request.session['result'] result = context['result'] # Transformation into DF df = pd.DataFrame(result) #to be transformed into Excel File # pprint(df) # Count number of rows nb_rows = df[df.columns[0]].count() context['nb_rows'] = nb_rows # Count number of rows which are errored nb_errors = np.sum(df['IsSimilar'] == True) context['nb_errors'] = nb_errors # Sum all rows total_amount = df['Montant_HT'].sum() context['total_amount'] = total_amount # Sum all rows which are errored rows_errors_sum = df.loc[df['IsSimilar'] == True, ['Result']].sum().values rows_errors_sum = str(rows_errors_sum).replace('[', '').replace(']', '') rows_errors_sum = float(rows_errors_sum) context['rows_errors_sum'] = rows_errors_sum return context I can't manage to make the request within my class ResultView. Could you help me with that? -
Django migration conflict between git branches
Is there any way to adequately merge migrations in django if they happen to be in two different branches in git? So far we have just avoided this -
Django, Postgresql: Deleted some db tables because I didn't want them, created new in Django, can't migrate now
I decided to change the models as they were initially designed, so I didn't want the old tables located in postgresql. I deleted them. I deleted them because otherwise they would be superfluous. But now I can't migrate because Django keeps references to the old tables. My web does make use of the registration authentication db tables so I am wary about doing something drastic like deleting the migrations folder. This is just about the last messages from the console. File "C:\Users\chefv\WEBS\registro\registro\lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\chefv\WEBS\registro\registro\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "users_electricity" does not exist -
google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead : Google Place autocomplete Error
I am trying to add Google place auto suggest, I copied the code from the developer's website to try it out but got the error : google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead. Also I am not getting any place suggestions. https://developers.google.com/maps/documentation/javascript/places-autocomplete google.maps.event.addDomListener(window, 'load', initializeAutocomplete); i have also added script <script src="https://maps.googleapis.com/maps/api/jskey=api_key&libraries=places"></script> I have implemented the same thing in one html it worked successfully, but when I used it on click button which opens a popup (form which has place-input), it gave me this error. Note : I have also tried addEventListener but that's giving me an error : google.maps.event.addEventListener is not a function Do you have any idea why I am getting this error, and how can I fix this? -
sequence item 1: expected str instance, property found
I am working Django app and I came cross where I need to extract a value of booking and pass it to another function to print a pdf doc with some details fields including a total amount of the booking ## defe function to extract deal total amount and to avoid circular import @property def extract_deal_total_amount(): from sook_contact.signals import on_loading_booking_deal deal_values = on_loading_booking_deal('8388945051') convert_to_float = float(deal_values['amount']) * 1.20 return str(convert_to_float) // the in another function elif field_name == OccupationLicenseFieldType.BOOKING_FEE.value: return extract_deal_total_amount -
How Can I get Model record through ID into Django FormView for submition into another Model
I am new to Django and I am working on a Deposit and Withdrawal Project where I am using FormView (Class Based Views) to add Deposit for customers. I have list of customers with a button for deposit where I want that; any time the Deposit button is clicked a form should be displayed with some fields like account number should be disabled and only deposit amount form field active. And once the form is submitted, the record should be add to the deposit table for that customer. Here is my models code: class Customer(models.Model): surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=20, null=True) accountnumber = models.CharField(max_length=10, null=True) address = models.CharField(max_length=30, null=True) phone = models.CharField(max_length=11, null=True) date = models.DateTimeField(auto_now_add=True, null=True) #Get the url path of the view def get_absolute_url(self): return reverse('customer_create', args=[self.id]) #Making Sure Django Display the name of our Models as it is without Pluralizing class Meta: verbose_name_plural = 'Customer' # def __str__(self): return f'{self.surname} {self.othernames} - {self.accountnumber}' class Deposit(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Here is my code for my form: class CustomerDepositForm(forms.ModelForm): #Set Read … -
psycopg2 installing error in cPanel while hosting Django Website with PostgreSQL
Collecting psycopg2 Using cached psycopg2-2.9.3.tar.gz (380 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running egg_info creating /tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info writing /tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-irgb8yga/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
How to query a specific field in a model that has the same name as another field of another model
I'm trying to render the device that has the same name as the Gateway in the query so I created three models (The plant model has nothing to do with this issue so skip it ) as you can see in the models.py : from django.db import models infos_type= ( ('ONGRID','ONGRID'), ('PV','PV'), ('HYBRID','HYBRID'), ) infos_status= ( ('etude','Etude'), ('online','Online'), ('Other','Other'), ) infos_Device= ( ('Rs485','Rs485'), ('lora','lora'), ('Other','Other'), ) class new_Plant(models.Model): name=models.CharField(max_length=20) adress=models.CharField(max_length=50) type=models.CharField(max_length=20,choices=infos_type) location=models.CharField(max_length=50) list_gateway=models.CharField(max_length=50) status=models.CharField(max_length=50,choices=infos_status) def __str__(self): return self.name #class Meta: #db_table="website" class new_Gateway(models.Model): gatewayname=models.CharField(max_length=20) slavename=models.CharField(max_length=20) list_devices=models.CharField(max_length=20) def __str__(self): return self.gatewayname class new_Device(models.Model): Gateway_Name=models.CharField(max_length=20) DeviceName=models.CharField(max_length=20) slavename=models.CharField(max_length=20) adress=models.CharField(max_length=20) baud_rate=models.CharField(max_length=20) connection_type=models.CharField(max_length=20,choices=infos_Device) def __str__(self): return self.DeviceName # Create your models here. Now as I said I want to render in a specific page , the device that Has "Gateway_Name" field same as the Gateway "gatewayname" field. in my views.py this is what I tried but it doesn't work : def gatewaysdevice(request,id): gateway=new_Gateway.objects.get(id=id) result=new_Device.objects.filter(Gateway_Name__contains=new_Gateway(gatewayname)) return render(request, 'website/gatewaysdevice.html',{'result':result}) -
Passing django.core.mail.EmailMultiAlternatives instance as async_task with Django-Q
An E-mail template is build-up and send weekly to more than 2000 email recipients (bcc). I must run it as background since it takes few minutes to get rendering back and that some E-mail provider block Senders because of mass mail in a few period of time. I cannot use SendinBlue or MailChimp or any others for contractual reasons. I use 'django.core.mail.EmailMultiAlternatives' instance in order to add images '(self.attach(img)' and documents '(self.attach_file(filepath)'. After creation all context data like <img src="cid:filename.jpg". I use render_to_string(template_name, request=request, context=context).strip() to get back my filled-in HTML E-mail template. Background running with async_task of Django-Q When I pass my EmailMultiAlternatives instance, I get the error: Traceback (most recent call last): File ".pyenv/versions/3.9.7/lib/python3.9/multiprocessing/queues.py", line 245, in _feed obj = _ForkingPickler.dumps(obj) File ".pyenv/versions/3.9.7/lib/python3.9/multiprocessing/reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) TypeError: cannot pickle '_thread.RLock' object If I build my instance template in the task (but with code redundancy), it works but then since I want to loop over my 2000 recipients to send the mail by chunk of 99 every n minutes (avoid mail server blocking), again, I need to pass the EmailMultiAlternatives instanceas a parameter and I get back the same error. Any idea on how to proceed? -
Pass Django variables to javascripts
I am stuck into a problem, I want to pass django variable to javascripts but I can't. views.py def dashboard_view(request): months_before = 5 now = datetime.utcnow() from_datetime = now - relativedelta(months=months_before) modified_from_datetime = from_datetime.replace(day=1, hour=0, minute=0, second=0, microsecond=0) month = Btdetail.objects.filter(DatePur__gte=modified_from_datetime).count() return render(request, "dashboard.html", {'month': month}) I want to embed month value to javascripts data my html script function is <script> var xValues = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; new Chart("myChart3", { type: "line", data: { labels: xValues, datasets: [{ data: [5,10,20,15,20,5,15,40,10,12,24,35], borderColor: "red", fill: false }] }, options: { legend: {display: false} } }); </script> actually I want to create a Area bar, all things are good but javascript functions cant get value from django database and if there is another way to do this please tell me [1]: https://i.stack.imgur.com/9bJzE.jpg -
Slow spatial join on a single table with PostGIS
My goal is to calculate if a building have at least one shared wall with a building of another estate. I used a PostGIS query to do so but it is really slow. I have tweaked this for two weeks with some success but no breakthrough. I have two tables: Estate (a piece of land) CREATE TABLE IF NOT EXISTS public.front_estate ( id integer NOT NULL DEFAULT nextval('front_estate_id_seq'::regclass), perimeter geometry(Polygon,4326), CONSTRAINT front_estate_pkey PRIMARY KEY (id), ) CREATE INDEX IF NOT EXISTS front_estate_perimeter_idx ON public.front_estate USING spgist (perimeter); Building CREATE TABLE IF NOT EXISTS public.front_building ( id integer NOT NULL DEFAULT nextval('front_building_id_seq'::regclass), type character varying(255) COLLATE pg_catalog."default", footprint integer, polygon geometry(Polygon,4326), shared_wall integer, CONSTRAINT front_building_pkey PRIMARY KEY (id) ) CREATE INDEX IF NOT EXISTS front_building_polygon_idx ON public.front_building USING spgist (polygon) TABLESPACE pg_default; CREATE INDEX IF NOT EXISTS front_building_type_124fcf82 ON public.front_building USING btree (type COLLATE pg_catalog."default" ASC NULLS LAST) TABLESPACE pg_default; CREATE INDEX IF NOT EXISTS front_building_type_124fcf82_like ON public.front_building USING btree (type COLLATE pg_catalog."default" varchar_pattern_ops ASC NULLS LAST) TABLESPACE pg_default; The m2m relation: CREATE TABLE IF NOT EXISTS public.front_estate_buildings ( id integer NOT NULL DEFAULT nextval('front_estate_buildings_id_seq'::regclass), estate_id integer NOT NULL, building_id integer NOT NULL, CONSTRAINT front_estate_buildings_pkey PRIMARY KEY (id), CONSTRAINT front_estate_buildings_estate_id_building_id_863b3358_uniq UNIQUE … -
Authorization: Any Benefit of OAuth2 for First-Party Web and Mobile Clients
I would like to know whether there is any security benefit to using OAuth2 for authorization where all clients are developed, owned and controlled by the API developer/owner/controller; as opposed to using token authentication per Django Rest Framework's Token Authentication. My understanding OAuth is that it was created for the purpose of delegated authorization - allowing third party applications access to your user's data without knowing the user's credentials. It seems to now have become a standard, even where delegation is not required. I do not understand why. Is there any benefit at all where delegation is not required? My setup will be a Django Rest Framework API with a web SPA client and mobile clients. Permissions are associated with user accounts. Users login with email and password. I do not think that this is an opinion question, because I'm not asking which is better, I will make that decision myself, I'm just trying to understand whether there is actually any security benefit at all to the OAuth option. This question might be somewhat open-ended but hopefully is within an acceptable margin since I'm restricting the considerations to security considerations. Developer effort etc are not necessary to discuss. -
Django form for user input to database
I am attempting to have a form which users can create new orders. The user gives the order a name, submits the form and then auto populates the creation date and user who created it. Additionally, I want the form to be on the same page as the contents of the database, so that a list of all orders can be displayed underneath. When the form is submitted, the page should refresh to show the new entry. I need a bit of help tying all this together. At the moment, I am not getting the form displayed on the site for the users to fill in. models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class Order(models.Model): order_name = models.CharField(max_length=100, unique=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) def __str__(self): return self.order_name class Ce_Base(models.Model): ce_hostname = models.CharField(max_length=15) new = models.BooleanField() location = models.TextField() order_reference = models.ManyToManyField(Order) class OrderForm(ModelForm): class Meta: model = Order fields = ['order_name'] views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Order from .models import Ce_Base from .forms import OrderForm @login_required def home(request): context = { 'order': Order.objects.all() } return render(request, 'orchestration/order_create.html', context) @login_required def orderprocessing(request): … -
TypeError: Object of type SMTPAuthenticationError is not JSON serializable
Below is my code for sending email through django but I am getting TypeError: Object of type SMTPAuthenticationError is not JSON serializable error. Anyone can tell me what I am doing wrong? from django.core.mail import send_mail, EmailMultiAlternatives from django.conf import settings @api_view(['POST']) def sendEmail(request, version): print(request.data) emailSubject = request.data['emailSubject'] emailMessage = request.data['emailMessage'] emailRecipient = request.data['emailRecipient'] print(settings.EMAIL_FROM) try: send_mail( emailSubject, emailMessage, settings.EMAIL_FROM, [emailRecipient] ) return Response( { "message": "Email sent successfully" }, status=status.HTTP_200_OK ) except Exception as ex: return Response( { "message": ex }, status=status.HTTP_409_CONFLICT ) Error Response: May 12, 2022 - 16:32:04 Django version 3.1.6, using settings 'bumpdate.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. {'emailSubject': 'Testing Subject', 'emailMessage': 'Testing Message in the email body', 'emailRecipient': 'muzaib.a@origamistudios.us'} hello@bumpdateapp.com [12/May/2022 16:32:40] ERROR [django.request:224] Internal Server Error: /api/v2/sendEmail Traceback (most recent call last): File "D:\PROJECTS\bumpDate\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\PROJECTS\bumpDate\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "D:\PROJECTS\bumpDate\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "D:\PROJECTS\bumpDate\venv\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "D:\PROJECTS\bumpDate\venv\lib\site-packages\rest_framework\renderers.py", line 100, in render ret = json.dumps( File "D:\PROJECTS\bumpDate\venv\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Python39\lib\json\__init__.py", line 234, in dumps return cls( File "C:\Python39\lib\json\encoder.py", … -
How to access dictionary element from html?
I have python dictionary and I wanted to access a deep field of it in html. dictionary - dictionary = {"album":{ "album_type":"single", "images": [ { "height": 640, "url": "https://i.scdn.co/image/ab67616d0000b273358193d702a21397291432ef", "width": 640 }, { "height": 300, "url": "https://i.scdn.co/image/ab67616d00001e02358193d702a21397291432ef", "width": 300 }, { "height": 64, "url": "https://i.scdn.co/image/ab67616d00004851358193d702a21397291432ef", "width": 64 }] } } I wanted to access the image url, I know how to do that in python like- dictionary["album"]["images"][0]['url'] But don't know how to do it in html. NOTE: I am using Django Framework Thanks in Advance! -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 75: invalid continuation byte [closed]
the project works with generated text, but when I start writing text it crashes with an English text it works correctly, but in French I have this error thank you for your help return fp.read() \Python\Python39\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 75: invalid continuation byt lib\site-packages\django\template\loaders\base.py", line 23, in get_template contents = self.get_contents(origin) lib\site-packages\django\template\engine.py", line 158, in find_template template = loader.get_template(name, skip=skip) lib\site-packages\django\template\engine.py", line 176, in get_template template, origin = self.find_template(template_name) lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name)``` -
How to fix ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: when installing python packages on Zorin 16
How to fix ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: when installing python packages on Zorin 16. I was installing postgresql's psycopg2 to connect my postgres Database to Django. I got this error and suddenly every pip package i try gives me the same issue. I check online the answers where too old and can't work. My system is Zorin 16 Debian/Ubuntu. source myenv/bin/activate pip3 install psycopg2-binary ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/dukula/Area/myenv/lib/python3.8/site-packages/psycopg2-2.9.3.dist-info' Consider using the `--user` option or check the permissions. -
How to create a child at the time of creating a parent - Django
I have two models and I don't know how to create an 'ExDocument' child associated with its field extension when creating the parent 'Document'. Document: class Document(models.Model): name = models.CharField(max_length=255) documentId = models.CharField(max_length=50, blank=True, null=True, default=None) text = models.CharField(max_length=2555) owner = models.ForeignKey(User, related_name="Doc_Own", blank=True, null=True, default=None, on_delete=models.CASCADE) author = models.ForeignKey(User, related_name="Doc_Aut", blank=True, null=True, default=None, on_delete=models.CASCADE) def save(self, **kwargs): super().save(**kwargs) def __str__(self): return self.name ExDocument: class ExDocument(models.Model): doc_name = models.CharField(max_length=255, null=True, blank=True) ex_name = models.OneToOneField(Document, related_name='ExDoc', on_delete=models.CASCADE) def __str__(self): return self.ex_name.name def delete(self, *args, **kwargs): super().delete(*args, **kwargs) if self.ex_name: self.ex_name.delete()