Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Strange generation of arrays using numpy
I faced such a problem that with one algorithm different arrays are generated for me. Why is this happening to me? def formation(self): tickets = 0.00 new_tickets = 0.00 chanse = {} for item in items: new_tickets = tickets + item.item.quality.chance print(tickets,new_tickets) chanse[item.item.name] = numpy.arange(tickets,new_tickets,0.01) tickets = new_tickets return tickets,chanse And I get a result like this: 0.0 70.0 70.0 145.0 [0.000e+00 1.000e-02 2.000e-02 ... 6.997e+01 6.998e+01 6.999e+01] [ 70. 70.01 70.02 ... 144.97 144.98 144.99] -
How to do CRUD operation in any subpage
Basically i want to do CRUD operation in one specific table Id for example if i am in 'http://127.0.0.1:8000/view/1' this page i want to do crud operation for this specific id and have small table below it. class Allinvoice(models.Model): company_choice = ( ('VT_India', 'VT_India'), ('VT_USA', 'VT_USA'), ) company = models.CharField( max_length=30, blank=True, null=True, choices=company_choice) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) project = models.ForeignKey(Allproject, on_delete=models.CASCADE) invoice_title = models.CharField(max_length=15) invoice_id = models.IntegerField(primary_key=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) invoice_amount = models.IntegerField() invoice_date = models.DateField( blank=True, null=True) invoice_duedate = models.DateField( blank=True, null=True) invoice_description = models.TextField() def __str__(self): return str(self.invoice_id) class Invoicedetails(models.Model): invoice = models.ForeignKey( Allinvoice, on_delete=models.CASCADE) total_amount = models.IntegerField() payment_id = models.IntegerField(primary_key=True) amountreceived = models.IntegerField() amount_left = models.IntegerField() date = models.DateField( blank=True, null=True) paymentmethod = models.ForeignKey( Allpaymentmethod, on_delete=models.CASCADE) def __str__(self): return str(self.payment_id) **So here for each individual Allinvoice table object i want to have multiple Invoicedetails record and with functional based views only,anyone please recommend me any example for such case ** Thanks -
How to connect in django s3 files storage from yandexcloud?
There are s3 from yandex cloud https://cloud.yandex.com/docs/storage/tools/?utm_source=console&utm_medium=empty-page&utm_campaign=storage How kan I configure django to use it ? -
Include foreign key in saving Django-Rest-Framework serializer
I am creating an API with Django Rest Framework. You can give a term to the api, it looks up data on a third party API and then everything should be stored to the database. All is handled in user scope and I have two tables, one with the search term and the ID of the user and another with the data received, which has the search_id as a foreing key. I now want that if you send a term to the API everything is stored and you get the search back, with ID and all dates. so far so good. I am now stuck, where I need to save the third party data to the database. The serializer demands the model object at saving and not the serializer from the user input. I tried around, but can't figure out, what I am doing wrong: models.py: class Search(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) term = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.term class foundTables(models.Model): search = models.ForeignKey(Search, related_name='search', on_delete=models.CASCADE) code = models.CharField(max_length=200) content = models.CharField(max_length=1000) time = models.CharField(max_length=200, blank=True, default='') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.content serializers.py class SearchSerializer(serializers.ModelSerializer): class Meta: model = … -
printing only first return HttpResponse in django
when i use 2 return HTTP Response in views.py in Django it is printing only first return. can anyone help to print the both return in the localhost of Django? -
formset factory with initial values or null
My models.py is rather simple: class Person(models.Model): name = models.CharField(max_length=254) class Question(models.Model): question_text = models.CharField(max_length=254) class Answer(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) question = models.ForeignKey(Question, on_delete=models.RESTRICT) answer_text = models.CharField(max_length =254) And now I want to create form, where user can enter answers for all questions. And the same form would be for editing it... (formset_factory looks properly) But there's a problem.... The user can answer none, all or some questions (I want to add questions after answering it, then user enters form, add some answers, maybe change already answered) So I be stacked if FormFactory should produce Question or Answer form. And how to show all even null answers? -
How to set default and auto_now value for django datetime model field
I want to set a default DateTime for my Django model that will be used in querying data from google fit api. Since this field will be empty in the beginning, the default value will allow for the first query and the auto_now will keep updating as more queries are made. Django seems not to allow both auto_now and default as arguments. Could anyone please assist with a workaround I could use to achieve this? models.py class GoogleStep(models.Model): user = models.OneToOneField(User, related_name='googlestep', on_delete=models.CASCADE) starttime = models.DateField(null=False) endtime = models.DateField(null=False) steps = models.IntegerField(null=False) last_sync = models.DateTimeField(auto_now=True, null=False) class Meta: ordering = ('-starttime',) -
Ajax dropdown not working in django while using adminLTE 3.0.5 template
I am using adminlte3 theme for my django project. In this project I have a form with ajax dependent drop-down control. In ADD PLANT form this drop-down (company) will be populated based on selection of country. But when I am using adminlte3 template it is not working. Please see the github link. https://github.com/shahidpharm/qtrack Can anyone help me? Thanks -
Django-HTML: How can i allow users to add additional input fields (ensuring they are not required)? Something like a + button
Django-HTML: How can i allow users to add additional input fields (ensuring they are not required)? Something like a + button. I only want to display info 1. And only when users press the '+" button, these fields will appear and allow them to add info_2 and info_3. Is this possible? Because do i need to provide like an additional field in the model.py: eg info_4 = ..... info_5 =....... I have searched the Stackoverflow but was unable to find a question and answer very similar to this. Maybe someone can advice on the coding as i believe your input will be very beneficial to both django and html beginners:) models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) info_1 = models.TextField(max_length=300, null=False, blank=False) info_2 = models.TextField(max_length=3000, null=False, blank=False) info_3 = models.TextField(max_length=300, null=True, blank=True) html: <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %} <!-- chief_title --> <div class="form-group"> <label for="id_title">Chief Title!</label> <input class="form-control" type="text" name="chief_title" id="id_title" placeholder="Title" required autofocus> </div> <!-- Body --> <div class="form-group"> <label for="id_body">Full Description</label> <textarea class="form-control" rows="8" type="text" name="body" id="id_body" placeholder="This idea is about..." required></textarea> </div> <div class="form-group"> <label for="id_Info_1">Info_1</label> <input class="form-control" rows="10" type="text" name="Info_1" id="id_Info_1" placeholder="Info_1..." required></input> </div> forms.py class CreateBlogPostForm(forms.ModelForm): class Meta: … -
Django Passwords don't match after changing hasher, can't log in
i need to store my passwords in plain text in database(it is just django practise project) that's why i added a password hasher: lass PlainTextPassword(BasePasswordHasher): algorithm = "plain" def salt(self): return '' def encode(self, password, salt): assert salt == '' return password def verify(self, password, encoded): return password == encoded def safe_summary(self, encoded): return OrderedDict([ (_('algorithm'), self.algorithm), (_('hash'), encoded), ]) It works fine. But the problem is that i can't log in with these passwords, my theory is that django passes already hashed password to verification and that's why passwords dont match. I'm using allauth lib. Anyone have a solution? -
How to get the value of a model form and assign it to its key in another model form
Suppose I have three models A, B, and C. I also created two model forms from these models. I want to know that is there a way to get the value of the B model form and assign it to its key in the c model form in views? class A(models.Model): name = models.CharField(max_length=200) class B(models.Model): name = models.CharField(max_length=200) class C(models.Model): a= models.ForeignKey(A, on_delete=models.CASCADE) b= models.ForeignKey(B, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES) class BForm(ModelForm): class Meta: CHOICES = B.objects.all() model = B fields = ('name',) widgets = {'name': Select(choices=( (x.id, x.name) for x in CHOICES ))} class CForm(ModelForm): class Meta: model = C fields = ('answer',) widgets = { 'answer': RadioSelect(choices=RATING_CHOICES),} def index(request): a1 = A.objects.get(id=1) a2 = A.objects.get(id=2) if request.method == "POST": b_form = BForm(request.POST) form = CForm(request.POST, prefix='a1') form1 = CForm(request.POST, prefix='a2') if (form.is_valid and form1.is_valid()): b_form.save() z = form.save(commit=False) z.a= a1 z.b = # I could not figure out this z.save() z = form1.save(commit=False) z.a = a2 z.b = # I could not figure out this z.save() -
How to correct schemas/ sitemap XML file Url, missing " / " forward slash inbetween in django projects
This is the xml file in which inside URL you can see that some of the tittle inside URL missing forward slashes, kindly let me know if you have a way to include those inside it: <url> <loc>http://example.**comAccountant**</loc> <lastmod>2020-12-21</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.**comProject** Budgeting Analysis</loc> <lastmod>2020-12-24</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.comAccounts Officer</loc> <lastmod>2020-12-24</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.**comhello** my firen</loc> <lastmod>2021-01-02</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.**com/blog/blogs/**</loc> <changefreq>yearly</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.com/blog/contact/</loc> <changefreq>yearly</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.com/blog/search/</loc> <changefreq>yearly</changefreq> <priority>0.8</priority> </url> </urlset>``` -
Error in Installing spacy en_core_web_lg on Heroku app
Am deploying my ML model on Heroku using Django, I need en_core_web_lg for my application but couldn't install it My requirements.txt is like: .. git+git://github.com/explosion/spacy-models/releases/download/en_core_web_lg-2.1.0/en_core_web_lg-2.1.0.tar.gz git+git://github.com/Prabhat-git-99/text_process_prabhat99.git .. The Error is: ERROR: Command errored out with exit status 128: git clone -q git://github.com/explosion/spacy-models/releases/download/en_core_web_lg-2.1.0/en_core_web_lg-2.1.0.tar.gz /tmp/pip-req-build-nzvnjf6t Check the logs for full command output. -
Playback state control of spotify web player sdk using spotify api
I am creating a webapp using django and react in which multiple user can control playback of a spotify player (play/pause, skip). This is useful in case of a house party or something where people are listening to a common device . I am thinking if i can integrate the spotify web player sdk and all users can listen to synced playback and control at the sametime remotely. I understand single spotify account needs to register that webapp to be used as device. My question is if can i control the state of playback if the page is opened by multiple users so that they listen to a song synchronously. -
How to get current authenticated user id using Vuejs and Django Rest...?
I am using Vuejs as my frontend and I would simply like to get the current logged in user's id from Django Rest and display it. How would I do this? serializer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' view class CustomerRetrieveView(generics.RetrieveAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class CustomerUpdateView(generics.UpdateAPIView): queryset = Customer.objects.all() serializer_class = CreateCustomerSerializer permission_class = permissions.IsAuthenticatedOrReadOnly class CustomerCreateView(generics.CreateAPIView): queryset = Customer.objects.all() serializer_class = CreateCustomerSerializer class CustomerListView(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer url path('customers/<int:pk>', views.CustomerRetrieveView.as_view()), path('customers/update/<int:pk>', views.CustomerUpdateView.as_view()), path('customers/all', views.CustomerListView.as_view()), path('customers/new', views.CustomerCreateView.as_view()), script vue update(event) { event.preventDefault(); this.axios .post(`http://127.0.0.1:8000/api/v1/customers/new`, {'user': **???**, 'phone': this.phone }) .then(response => {console.log(response) ;this.$router.push('/') }) .catch(err => { console.error(err) }) } -
problem of django form in posting request
I'm working on a project and I made a form but when I submit sth it doesn't send it to database although in cmd it shows that request method is post.I really don'tkhow how to deal with it. thats template code: {%extends 'base.html'%} {%block title%} <title>projects</title> {%endblock title%} {%block content%} <div class="container"> </br> <form method="post"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" name="project" placeholder="new project?"> </div> <button type="submit" class="btn btn-primary">add</button> </form> </br> </br> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col"> project-title</th> <th scope="col">update</th> <th scope="col">delete</th> <th scope="col">divide</th> </tr> </thead> <tbody> {% for obj in all_projects %} <tr> <td>{{ obj.proTitle }}</td> <td>{{ obj.done }}</td> <td>Delete</td> <td>Devide</td> </tr> {% endfor %} </tbody> </table> </div> {%endblock content%} any advise will be greatly appreciated:)) -
Error in Paytm Django integration in "production" mode
I was working on to integrate Paytm into my Django project. It worked pretty fine in the demo run, i.e., staging. While I was trying to run it for the production it started throwing errors. The checksum isn't matching in production. Paytm/Checksum.py # pip install pycryptodome import base64 import string import random import hashlib from Crypto.Cipher import AES IV = "@@@@&&&&####$$$$" BLOCK_SIZE = 16 def generate_checksum(param_dict, merchant_key, salt=None): params_string = __get_param_string__(param_dict) salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def generate_refund_checksum(param_dict, merchant_key, salt=None): for i in param_dict: if("|" in param_dict[i]): param_dict = {} exit() params_string = __get_param_string__(param_dict) salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def generate_checksum_by_str(param_str, merchant_key, salt=None): params_string = param_str salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def verify_checksum(param_dict, merchant_key, checksum): # Remove checksum if 'CHECKSUMHASH' in param_dict: param_dict.pop('CHECKSUMHASH') # Get salt paytm_hash = __decode__(checksum, IV, merchant_key) salt = paytm_hash[-4:] calculated_checksum = generate_checksum(param_dict, … -
django module 'appname' has no attribute 'models'
Everything was working fine until today after I deleted venv and re-created it with pycharm. Now, whatever command I run with django, It throws up this error: AttributeError: module 'api_backend' has no attribute 'models' full 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 "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_f rom_command_line utility.execute() File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\models\__init__.py", line 2, in <module> from .data_sheets import * File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\models\data_sheets.py", line 2, in <module> from api_backend.managers.positions import PositionalManager File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\managers\__init__.py", line 1, in <module> from .field_data import FieldDataManager File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\managers\field_data.py", line 3, in <module> import api_backend.models as api_models AttributeError: module 'api_backend' has no attribute … -
Can't be able to emit the event from outside of socket IO context
Here below is my other file logic (apart from socket io context) in which a signal will be called when the user will be deleted by admin. @receiver(models.signals.post_delete, sender=Driverprofile) def delete_user_object(sender, instance, *args, **kwargs): print("Driver going to delete") instance.user.profile.delete() # call socket method loop = asyncio.new_event_loop() loop.run_until_complete(user_deleted(instance.user.id)) loop.close() instance.user.delete() and here below is my socket io context (last method is for user delete in which i want to emit an event to the connected user) #!/usr/bin/env python # from .models import * import asyncio import uvicorn import socketio, pdb import pickle # from registration.models import * sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins="*") app = socketio.ASGIApp(sio) background_task_started = False users = {} async def background_task(): """Example of how to send server generated events to clients.""" count = 0 while True: await sio.sleep(10) count += 1 # io.to(socketid).emit('message', 'for your eyes only'); # pdb.set_trace() await sio.emit('my_response', {'data': 'Server generated event'}) @sio.on('login') async def login(sid, message): global users users[sid] = int(message['userId']) print("Login users", users) filename = 'dogs' outfile = open(filename,'wb') pickle.dump(users,outfile) outfile.close() await sio.emit('my_response', {'data': ''}, room=sid) @sio.on('my_broadcast_event') async def test_broadcast_message(sid, message): await sio.emit('my_response', {'data': message['data']}) @sio.on('join') async def join(sid, message): sio.enter_room(sid, message['room']) await sio.emit('my_response', {'data': 'Entered room: ' + message['room']}, room=sid) @sio.on('leave') async def … -
Python crash course chapter 18. No learning_log directory is created
I'm doing exercises in the 'Python Crash Course' book in Chapter 18. I can't create the learning_log directory and manage.py, init.py, settings.py, urls.py, wsgi.py files. I made the creation of a virtual environment with the command: python -m venv ll_env I am using Windows so I used the command to activate the virtual environment: ll_env\Scripts\activate The environment has been activated because the name (ll_env) is displayed before the prompt. Then I installed the Django framework with the command: pip install django Installed successfully.But when I used the command: django-admin.py startproject learning_log . Unfortunately, the learning_log directory and the previously mentioned files are not created. I installed django version 3.1.4 and the book is version 2.2. Is there a problem here? Is there any other command to create this directory and files? Let me add that I was doing it all in the PyCharm terminal. -
Why doesn't the csrf_exempt work on my view in Django?
I am making a fetch request to one of the Urls as: function like(id){ fetch(`/likepost/${id}`, { method:'PUT', body: JSON.stringify({ 'id':id }) }) .then(response => response.json()) .then(result => { console.log(result) }) and the url maps to this view: path('likepost/<int:post_id>', views.likepost,name='like') and the view is defined as: @csrf_exempt def likepost(request, post_id): if request.method == 'PUT': data = json.loads(request.body) id = data.get('id') post = Post.objects.get(pk=id) post.likes = post.likes+1 post.save() return JsonResponse({'message':'liked succcessfuly'}) else: return JsonResponse({'Message':'request should be post'}) but I am getting this error: Forbidden (CSRF token missing or incorrect.): /likepost/12 even though I have used csrf_exempt, can anyone help me? -
Plotly Dash App in Django throws TypeError on __init__() Positional Arguments
I have been following the example here exactly https://thinkinfi.com/integrate-plotly-dash-in-django/ it works fine if I set the virtual environment up with packages of the exact packages it has specified. However I am trying to follow this method and implement it into an existing Django project, so I would prefer to use the latest versions of the packages. With these versions instead django-plotly-dash==1.5.0 dash==1.18.1 dash-bootstrap-components==0.11.1 dash-daq==0.5.0 dpd-static-support==0.0.5 whitenoise==5.2.0 I got this error Exception inside application: __init__() takes 1 positional argument but 2 were given Traceback (most recent call last): File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/routing.py", line 150, in __call__ return await application( File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/asgiref/compatibility.py", line 33, in new_application instance = application(scope) TypeError: __init__() takes 1 positional argument but 2 were given Does anyone have any ideas how to resolve it? I have a similar setup going fine (except that … -
Django DB cyclic model prevention Queryset
I am working on a project where I need have cyclic entries. Think, a recipe might have a sub recipe and that might have a sub recipe. The issue is one of those sub recipes might have its parents' parent as a child. So I am trying to prevent this or at least not wanting to have to proved the user with an option to select that item. To do this. I wanted to check on the server side if there is cycle. A classic loop detection. So I was going to either implement BFS or DFS, possible DFS to minimize the memory usage and check each child and their child and so forth until I visit all nodes and keep a visited dict to keep the ids of all the models entries I see. The issue is queryset is not providing some of the basic functions to do pop and push. I can convert the query set to list but that could be expensive and run out of memory. It is unlikely to have 100000 depth recipe but in theory it can happen. Is there an alternative to this? I was thinking maybe pass the visited list to filter … -
How many Django models is appropriate?
I'm making a Django project from a pre-existing epidemiological Excel model and I'm not familiar with how best to make use of Django models. The examples in the tutorial seem to fit 'just right' (e.g. one object is obviously the parent of another), and my data does not. My data consists of the following: A country, which has a name, a population of males and a population of females. However the population depends on the year (2019 to 2030). A cancer, which has a type (e.g. Breast cancer), a set of stages (e.g. Stage IV breast cancer). Cancer types interact with countries. E.g. the likelihood of dying from Stage III lung cancer is different in Australia than Uganda. This data currently lives in a bunch of json files, one which has the population per year of countries, one which has the proportion of people in an age group for a country, one which has the likelihood of dying from a cancer etc. I created these json files by exporting them from pandas dataframes, which we took from the lookup tables in Excel. I presume I could import each of these json files as its own model, but I get the … -
How to Change Django InMemoryField to PIL Image object?
Here Take a look at my code : profile_picture = self.validated_data.get('profile_picture',False) if profile_picture: pic = profile_picture.read() Now , I want to crop the image if it's not in a particular resuloution ; i want to convet pic to PIL.Image.Image obj, how do I do that?