Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing Attachment Upload/Delete with S3 Mock and Pytest
I have been doing a lot of research regarding how to use the moto module and etc. However, I still haven't found the solution for my specific case where there are multiple layers of modules that work with boto3 to upload and delete files. I am using Pytest for my project's tests. I am looking into a way to not mess with the actual S3 buckets and files while testing my viewsets. So far, I have failed to circumvent the S3. The specific test in question is 'TestAttachmentViewSet' tests/test_deal/test_views.py import pytest from django.urls import reverse from django.core.files.uploadedfile import SimpleUploadedFile from rest_framework.test import force_authenticate from rest_framework.test import APIRequestFactory from deal.api.views import * pytestmark = [pytest.mark.deal_views, pytest.mark.django_db] factory = APIRequestFactory() class TestAttachmentViewSet: def test_create(self): user = User.objects.first() card = user.card_set.first() url = reverse('attachment-list') newFileName = 'a-new-file' file = SimpleUploadedFile("file.txt", b"this is the test file content") data = { 'card': card.id, 'name': newFileName, 'content_type': 'text/txt', 'file': file } request = factory.post(url, data=data, format='multipart') force_authenticate(request, user=user) view = AttachmentViewSet.as_view({'post': 'create'}) response = view(request).render() assert response.status_code == 201 assert response.status_code == 201 assert json.loads(response.content)["link"].startswith( "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ) def test_destroy(self): attachment = Attachment.objects.first() card = attachment.card user = card.user url = reverse('attachment-detail', args=(attachment.id,)) query_params = f'?card_id={card.id}' request … -
mikemigrations command does not work to make table in database (Django)
I deleted all migrations After that the command doesn't work error -
group by and return zero if no value is present in Django
def get_queryset(self): date = datetime.date.today() queryset = Subscription.objects.filter(created__week=current_week)\ .exclude(user__is_staff=True).exclude(user__clients__domains__isnull=True).values(month=TruncDay('created')).annotate( total_members=Count('created')).order_by('month') return queryset This is my group by function, how I can get zero if no value is present for a particular month -
Django PostgresSQL fuzzy logic search
I am trying to desing a quiz app where contestants can write descriptive or choose from MCQ. For each MCQ I have an answer and for each descriptive question I have a django field called explanation. I want to be able to compare the two texts. The answer of the contestants and explanation field and say how much % the texts match. Is this possible to do ? I haven't tried anything as of yet but as I don't know how to start. Please let me know if you need any additional information. Any idea how to achieve this in python/django with postgres sql as backend ? Thanks -
Why is my django template tag not able to iterate my object across a model
I'm having an issue getting my template to produce a table that includes the models name, a count of the number of child models to that parent, and then a sum of a field in that child model. I've gotten the first two to return the desired output, but the last two only yield an empty space in the cell. Can't figure out where I'm missing it. MODELS.PY FILE class Employee(models.Model): user = models.OneToOneField(User,null=True, blank=True, on_delete=models.CASCADE) username = models.CharField(max_length=200, null=True) firstname = models.CharField(max_length=200, null=True) lastname = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) profile_pic = models.ImageField(default="hulkhoganicon.jpg", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.firstname class Event(models.Model): STATUS = ( ('Appointment Set', 'Appointment Set'), ('Hot Lead', 'Hot Lead'), ('Booked', 'Booked'), ('Lost Sale', 'Lost Sale'), ('X-Dated', 'X-Dated'), ) PACKAGE = ( ('1st Package', '1st Package'), ('2nd Package', '2nd Package'), ('3rd Package', '3rd Package'), ('4th Package', '4th Package'), ) ADDONS = ( ('None','None'), ('2nd Setup', '2nd Setup'), ('Uplighting', 'Uplighting'), ('Monogram', 'Monogram'), ('Intelligent Lighting', 'Intelligent Lighting'), ('Other', 'Other'), ) employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL) eventType = models.ForeignKey(EventType, null=True, on_delete=models.SET_NULL) teamAssigned = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) eventName = models.CharField(max_length=1000, null=True) date_of_event = models.DateField(auto_now=False, null=True) date_of_appt = models.DateField(auto_now=False, null=True) date_booked = … -
Best way to add/alter fields in a form
I have the following model class customer_prices(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE,null=True) price = models.FloatField() image = models.FloatField() function = models.TexField() . . (10 more fields) The fields shown in the homepage is only price thus the other fields are assigned manually, based on the values in a dataframe returned by a self-written some_util_function() e.g @login_required def add_price(request): cleaned_data = form.cleaned_data df = some_util_function(cleaned_data["price"]) form.user_id = user.id form.image= df["image"] . . form.save() messages.success(request, "Price added") return redirect("my_html") return render(...) As we can see each form-field is updated by form.field=df["field"] thus I wonder, if there is another (better way) of doing that? I have thought about the two following ways: Instead of form.field=value then form.cleaned_data["field"] = value Since I have all the data in a dataframe, simply push that dataframe to the given DB e.g df.to_sql("my_table_name"). I know (2) is working, but I think it's better to keep the database changes to Django, and not some mix between pushing data self and let Django handle it. -
django-filter return null queryset when wrong parameters
I'm creating a simple API. models.py class TestModel(models.Model): tenor = models.IntegerField(db_column="tenor_field") currency = models.CharField(max_length=6, db_column="currency_field") value = models.FloatField(db_column="value_field") serializer.py class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TestModel fields = [ 'tenor', 'currency', 'value'] views.py class TestView(viewsets.ReadOnlyModelViewSet): queryset = TestModel.objects.all() serializer_class = TestSerializer filterset_fields = ['tenor','currency'] when I call https://10.1.33.70/api/v1/base-rates/floating/?currency=**EUR**&tenor=**10** I get HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "tenor": 10, "currency": "EUR", "value": 0.6 } ] and it is ok. When I call https://10.1.33.70/api/v1/base-rates/floating/?currency=**EUR**&tenor=**xxx** I get HTTP 400 Bad Request Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "tenor": [ "Enter a number." ] } and it's also ok, because tenor is integer. But when I call https://10.1.33.70/api/v1/base-rates/floating/?currency=**USD**&tenor=**10** I get HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [] because in database are only EUR position (not USD). Is it possible to get a "HTTP 400 Bad Request" if I give a value to the "currency" parameter that is not in the database or can I define what values can be given to the parameter and otherwise a "HTTP 400 Bad Request". Thanks :) -
Django request.Get.get('page') returning none
Trying to use a paginator in a view. Getting none from page = request.GET.get('page'). As is, the call to paginator limits posts on a page properly, but any call to page sequence henceforth fails. Pages will display, but there will be nothing form pagination.html displayed. For clarity, Base.html is the base template from which all others inherit. This code is based off of the django manual. Is there something else that needs to be setup to give the requests querydict a key of 'page' or a better way to paginate? views.py from django.shortcuts import render, get_object_or_404 from .models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def post_list(request): object_list = Post.published.all() #a list of the posts paginator = Paginator(object_list, 4) # 4 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request,'blog/post/list.html',{'page': page,'posts': posts}) pagination.html <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page.number }} of {{ page.paginator.num_pages }}. </span> {% if page.has_next … -
Serializers Django
Hello I want to connect two models through serializers. I have one connection and it works very well, because the primary key belongs to UsuarioDetailSerializer and the foreign key to ComentarioSerializer. class ComentarioSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ['id', 'contenido_comentario','fecha_comentario',] model = Comentarios class HabilidadSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ['id', 'nombre_habilidad',] model = Habilidad class UsuarioDetailSerializer(serializers.ModelSerializer): detail = serializers.SerializerMethodField() usuario_comentado = ComentarioSerializer(many=True) habilidad = HabilidadSerializer() class Meta: model = Usuario fields = [ 'id', 'id_usuario', 'nombre_usuario', 'apellido_usuario', 'descripcion_usuario', 'direccion_usuario', 'foto_usuario', 'detail', 'usuario_comentado', 'habilidad', ] def get_detail(self, obj): return reverse('usuario_detail',args=(obj.pk,)) The other connection that I want to do, is between the serializer UsuarioDetailSerializer with HabilidadSerializer, but I can't do that because the primary key belong to HabilidadSerializer and the foreign key to UsuarioDetailSerializer and I don't know how solving this problem. I want to show the data from HabilidadSerializer into UsuarioDetailSerializer. -
Django set cookie domain to requested domain
Our application creates sub domains for users dynamically and has logins in it. I am facing an issue for sessions where the cookie is assigned to domain .mywebsite.com instead I want the cookie to be assigned to the requested subdomain like user.mywebsite.com and. The problem is when I login to 2 subdomains as the cookie is the same, the sessions are invalid for previous one. Example: logged in to user.mywebsite.com logged in to user2.mywebsite.com navigates to user.mywebsite.com and then session gets invalid because the cookie is assigned to domain .mywebsite.com Django: 3.1.1 Platform: Ubuntu 20LTS -
Django form is not valid when LANGUAGE_SESSION_KEY is not english
In my project I set the language thats the user select in the profile (englsih, spanhish, etc) view.py def set_idiom(request): from django.utils import translation user = request.user if request.user.is_authenticated: user_language = user.profile.idiom translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language else: user_language = 'en' translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language print(user_language) return user_language forms.py class CreateCourse(forms.ModelForm): class Meta: model = Courses fields = ('course_name', 'course_cant', 'course_description', 'course_target_lng', 'course_expert_lng', 'course_link_ptn', 'course_start', 'course_end',) widgets = { 'course_name': forms.TextInput(attrs={'placeholder':u'Course name...', 'class': 'form-control'}), 'course_cant': forms.NumberInput(attrs={'class': 'form-control'}), 'course_description': forms.Textarea(attrs={'class': 'form-control'}), 'course_target_lng': forms.Select(attrs={'placeholder':u'Select a target idiom', 'class': 'form-control', }), 'course_expert_lng': forms.Select(attrs={'class': 'form-control custom-select'}), 'course_start': forms.DateInput(attrs={'autocomplete': 'off', 'placeholder':u'Select a date', 'class': 'form-control'}), 'course_end': forms.DateInput(attrs={'autocomplete': 'off', 'placeholder':u'Select a date', 'class': 'form-control'}), } Every time I sumit the info the form is not valid if the user select a diferent idiom as english -
Filter Django Query by Option
I have a simple chart that is displaying some co2 data from a postgres db. I'm attempting to filter the query set by using an select option drop down list within my html, following a few guides I had assumed I could use the following line of code in my view then pass that into my query. query = self.request.GET.get('q') context['carbon'] = Carbon.objects.filter( Q(reading_date=query) ) however no change is happening, I can only think that 1. I'm mistaken with my query logic or above, or the page needs to re-load? models.py class Carbon(models.Model): id = models.AutoField( primary_key=True, editable=False, ) meter = models.BigIntegerField() reading_date = models.DateField() reading_time = models.TimeField() reading = models.DecimalField(max_digits=6,decimal_places=2) class Meta: indexes = [ models.Index(fields=['id','reading_date','reading_time']) ] def __str__(self) -> str: return self.reading views.py from .models import Carbon from django.db.models import Q from django.views.generic import ListView class CarbonDataView(ListView): model = Carbon context_object_name = 'carbon' template_name = 'carbon/chart.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) query = self.request.GET.get('q') context['date'] = Carbon.objects.values('reading_date').order_by('reading_date').distinct() context['carbon'] = Carbon.objects.filter( Q(reading_date=query) ) return context Chart.html (snippets) <form action="" method="get" class="form-inline mt-2 mt-md-0"> <label for="readingDateFormSelect">Reading Date</label> <select class="form-control" id="readingDateFormSelect" name="q"> {% for each_date in date %} <option name="q">{{ each_date.reading_date|date:"M d, Y" }}</option> {% endfor %} </select> </form> <script> … -
Update model field with a link on webpage in django
I am creating a project in which recruiter adds details of candidate which i am saving in candidate table. Recruiter can also see details of all candidates at once after clicking a link, there i have implemented search functionality based on fields of candidate. Now in this display , i want to add a modify link(or button whatever) which will be present at the end of each row of candidate data. On clicking that, a form should open to allow me to entry certain fields i need to update and on submitting the form the corresponding row should get updated in the backend candidate table. Please suggest me a way to accomplish it. def recruiter(request): if request.method == 'POST': form = CandidateForm(request.POST) if form.is_valid(): form.save() else: form = CandidateForm() return render(request,'recruit_app/recruiter.html',{'form': form}) class Candidate(models.Model): Candidate_Name = models.CharField(max_length=70) Skill_Category = models.CharField(max_length=20, choices = SKILL_CHOICES) Account = models.CharField(max_length = 50) Grade = models.CharField(max_length=10, choices = GRADE_CHOICES) Role = models.CharField(max_length=20) Billing_Date = models.DateField() OnBoard_Date = models.DateField(default='2021-01-01') Screening_Phase = models.CharField(max_length=20, choices = SCREENING_CHOICES) Final_status = models.CharField(max_length = 10, choices = SCREENING_CHOICES, default='SELECTED') def __str__(self): return self.Candidate_Name #candidate display: {% extends 'recruit_app/main.html' %} {% block content %} h1 { text-align: center; Candidate List <th>Candidate Name</th> … -
Django Calculate data on related models
I'm new to Django. Just want to know what's the best way to calculate some data of two related models. I've got an Order and OrderLine model so every time I add a new OrderLine item I want to iterate through all OrderLine items for that order and recalculate its total, and update the Order model with that total. Here's my models: class Order(models.Model): """ Order model """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) session_id = models.CharField(max_length=256) subtotal = models.DecimalField( decimal_places=2, max_digits=20, default=0.00) total = models.DecimalField(decimal_places=2, max_digits=20, default=0.00) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return str(self.id) class OrderLine(models.Model): """ OrderLine contains data related to the items added to an order """ order_id = models.ForeignKey( Order, related_name='items', on_delete=models.DO_NOTHING) product_id = models.ForeignKey(Product, on_delete=models.DO_NOTHING) price = models.DecimalField(decimal_places=2, max_digits=20) quantity = models.IntegerField() total = models.DecimalField(decimal_places=2, max_digits=20) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.order_id So I've thought of 2 options: Create a post_save signal in OrderLine which will query all items in OrderLine with order_id of the order that was just saved, iterate through each one, calculate the total and then assign it to the order total and update it Simply create a method in OrderLine call something like recalculate_total. This … -
Is there a way to generate a new random picture every time I loop through using Lorem Picsum?
I loop through my database and generate a card for each item in my database. Everything works fine except all the pictures are the same. Is there a way to get a different random picture for each card generated using Lorem Picsum? {% extends 'blog/base.html' %} {% block content %} <div class="container"> <div class="row"> {% for post in posts %} <div class="col-md-4 pb-4 pt-4 d-flex"> <div class="card"> <img style="height: 225px; width: 100%" src="https://picsum.photos/200" class="card-img-top" alt="..."> <div class="card-body d-flex"> <h5 class="card-title">{{ post.title }}</h5> <br> <p class="card-text"> {{ post.author }}</p> <br> <p class="card-text"> {{ post.description }}</p> </div> <div class="card-footer"> <small class="text-muted">{{ post.date_posted }}</small> </div> </div> </div> {% endfor %} </div> </div> {% endblock %} -
How to get db connection count in flask-sqlalchemy
I was a user of Django. I started using flask not too long ago. flask-sqlalchemy is having many orm. so I want to check db connection count(cf. not Model.query.filter(...).count()) In django, for example, import time import functools from django.db import connection, reset_queries def query_debugger(func): @functools.wraps(func) def inner_func(*args, **kwargs): reset_queries() start_queries = len(connection.queries) start = time.perf_counter() result = func(*args, **kwargs) end = time.perf_counter() end_queries = len(connection.queries) print(f"Function : {func.__name__}") print(f"Number of Queries : {end_queries - start_queries}") print(f"Finished in : {(end - start):.2f}s") return result return inner_func How can I do the same test on the flask? -
Django 1.4 model_instance.save() doesn't change database immediately in admin
Environment Django 1.4 Sqlite3 My understanding I thought model_instance.save() immediately change database. model from django.db import models # Create your models here. class Question(models.Model): name = models.TextField() base_file = models.FileField(upload_to='/Users/a202101054/PycharmProjects/playground') def to_dict(self): return { 'id': self.id, 'name': self.name, } view def get_questions(request): q1 = Question.objects.get(pk=1) q1.name = 'arbitary name' q1.save() return HttpResponse(json.dumps([x.to_dict() for x in Question.objects.all()]), content_type="application/json") It works as expected. when I debug this simple view, I can see q1's name has changed right after I call q1.save() What I did with same model, I created ModelForm and ModelAdmin class QuestionForm(forms.ModelForm): class Meta: model = Question def save(self, commit=True): self.instance.name = 'replace this column!' self.instance.save() # just for the check return super(QuestionForm, self).save(commit) class QuestionAdmin(admin.ModelAdmin): form = QuestionForm list_display = ( 'name', 'base_file', ) admin.site.register(Question, QuestionAdmin) I thought q1's name would be changed after I call self.instance.save() but it stays same. What actually happened I see the changed value after django returns the response... what is happening? when does django commit the change to database? -
How to use a method from another file inside of a function that's inside a class
I'm supposed to get the name and last name of the person that writes their id in a form I wrote. To get the name and last name I was given a function that I'm supposed to use but I don't know how to use it. Where do I call for it and when? This is the file x.py that I have to use: def get_persona(id_requested, ta_sign=None, ta_token=None): try: if ta_sign is None and ta_token is None: ta_sign, ta_token = wsaa.get_ta_sign_token('a13') client = Client(13_wsdl) response = client.service.getPersona( sign=ta_sign, token=ta_token, cuitRepresentada=id_consultante, idPersona=id_requested, ) return serialize_object(response, target_cls=dict) except Fault as e: if e.message == 'No person with Id': return None elif e.message == 'Inactive person': return 'Inactive' print('Error: ', e) return None except Exception as e: print('Error: ', e) return None This is my view so far: from django.shortcuts import render, HttpResponse import requests from django.views import View from .forms import MonotributoForm from .x import get_persona class ConstanciaInscripcion(View): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): if request: form = MonotributoForm(request.POST) get_persona(id_requested) if form.is_valid(): cuit = form.cleaned_data.get('cuit') email = form.cleaned_data.get('email') cuit.save() email.save() return HttpResponseRedirect('app/constancia-inscripcion.html') else: pass # could add a notification here return render(request, 'app/constancia-inscripcion.html') -
How to annotate group of object_set attribute
I have a Post model that has many comments, both comments and post have groups of reactions. I would like to annotate the group of comments under the post. So like: post = Post.objects.filter(pub_date__lte=timezone.now()) comments = post.comment_set.all() comments.annotate(is_liked_by_user=Count('reactions'), filter=Q(reactions__user=self.request.user)) The annotation doesn't break the code however if I try to access comments[0].is_liked_by_user it breaks cause it does not exists. I haven't found anything similar to how this should be done. Any ideas? I am trying to annotate the post.comment_set.all() Here are my models. class Reaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) reaction = models.CharField(max_length=10, default="U+1F44D") content_object = GenericForeignKey('content_type', 'object_id') object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) def __str__(self): return self.reaction class Post(models.Model): post_body = models.CharField(max_length=200) post_title = models.CharField(max_length=120) pub_date = models.DateTimeField('date published', null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) reactions = GenericRelation(Reaction) def __str__(self): return self.post_title def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Comment(models.Model): comment_body = models.CharField(max_length=200) post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, null = True) created_date = models.DateTimeField('date created', null=True, auto_now_add=True,blank=True ) reactions = GenericRelation(Reaction) def __str__(self): return self.comment_body -
How to use special variables in django template?
I want to use dp/L and dp/L-fit variable of dictionary in html table rows in django template. Example: [{'PIR': 3133510.2695076177, 'PVR': 13810.315856115429, 'curve': [{'v': 0.1633026324384349, 'dP/L': 85905.56295072743, 'dP/L-fit': 85818.9286758735, 'error': -0.001008482709130518}]}] When I use {{ dP/L }}, it gives me an error. -
What needs to be defined in main() when I migrate ll_env? Getting a traceback from manage.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() Here is the Traceback: Applying learning_logs.0002_auto_20210304_0207...Traceback (most recent call last): File "manage.py", line 22, in main() -
Authenticate Token In Unittest
I am using this to create unittests for my APIs that are to be accessed by third-party clients through a given token. @pytest.mark.django_db class TestFoodListView: """ Test Food List API """ url_name = "app:food-list" def test_list(self, api_client, token): """ Should return 200 success with data """ key = f"Token {token.key}" api_client.credentials(Authorization=key) url = reverse(self.url_name) response = api_client.get(url) assert response.status_code == 200 But I'am always getting this error upon running pytests, assert 401 == 200. Is there anyway I can authenticate the token this way? -
Django and postgresql in RDS connect well in local, but not in ec2
I created my postgre DB in AWS RDS and migrate it like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': {DB_name}, 'USER': {DB_USER}, 'PASSWORD': {DB_PW}, 'HOST': '{db_name}.{...}.{my_region}.rds.amazonaws.com', 'PORT': '5432', } } It works well in my local computer when I type 'python manage.py runserver' However, it doesn't work in my EC2 instance. Here is the error message. File "/home/ubuntu/myproject/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "{db_name}.{...}.{my_region}.rds.amazonaws.com" (172.31.15.15) and accepting TCP/IP connections on port 5432? Do I have to config other AWS settings? EC2 instance and RDS instance are in same security group.. My security group inbound rule [inboud]: [1]: https://i.stack.imgur.com/WHszq.png [outbound] Type | Protocol| Port range|Destination|Description - optional All traffic| All | All |0.0.0.0/0 | - -
Aggregation MongoDB Query
I've this sample MongoDB data: { "_id":{ "$oid":"603fae76b0fa8ad195e59b43" }, "case_id":1, "Hospital_code":8, "Hospital_type_code":"c", "City_Code_Hospital":3, "Hospital_region_code":"Z", "Available Extra Rooms in Hospital":3, "Department":"radiotherapy", "Ward_Type":"R", "Ward_Facility_Code":"F", "Bed Grade":2, "patientid":31397, "City_Code_Patient":7, "Type of Admission":"Emergency", "Severity of Illness":"Extreme", "Visitors with Patient":2, "Age":"51-60", "Admission_Deposit":4911, "Stay":"0-10" } and what I'm trying to do is to find the case id, hospitals and their departments that have accepted patients as either emergency or urgent admissions and are also displaying extreme symptoms and where the patient's ages are above 60, I've already tried a lot with no luck since this such a complicated one. -
Django Rest Framework Nested Serializer data not being passed to parent serializer
I have 3 models: Report, Chart, and ChartType. Report has many Charts, Chart belongs to Report ChartType has many Charts, Chart belongs to ChartType Those are the only relationships between the models. Here are the models: report.py class Report(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING) organization_id = models.IntegerField() title = models.CharField(max_length=255) chart.py class ChartType(models.Model): name = models.CharField(max_length=255) func_name = models.CharField(max_length=255) module_hash = models.CharField(max_length=255 class Chart(models.Model): chart_type = models.ForeignKey(ChartType, on_delete=models.CASCADE) report = models.ForeignKey(Report, related_name='charts', on_delete=models.CASCADE) And the serializers: class ReportSerializer(serializers.ModelSerializer): charts = ChartSerializer(many=True, required=False) owner = UserSerializer(read_only=True) class Meta: model = Report fields = ('id', 'owner', 'title', 'organization_id', 'charts') def create(self, validated_data): chart_data = validated_data.pop('charts', None) report = Report.objects.create(**validated_data) if chart_data is not None: for chart in chart_data: Chart.objects.create(chart_type_id=chart['chart_type_id'], report=report) return report def update(self, instance, validated_data): chart_data = validated_data.pop('charts', None) instance.organization_id = validated_data.get('organization_id', instance.organization_id) instance.title = validated_data.get('title', instance.title) instance.save() # IF UPDATING OR ADDING A CHART, PASS IN ALL CHARTS. IF NOT MODIFYING # CHARTS, DON'T SEND CHARTS KEY IN REQUEST # CHARTS ONLY NEED CHART_TYPE ID IN REQUEST. # REPORT_ID IS ADDED HERE if chart_data is not None: instance.charts.all().delete() for chart in chart_data: chart_type_id = chart.get('chart_type', chart.chart_type_id) report_id = instance.id Chart.objects.create(chart_type_id=chart_type_id, report_id=report_id) else: instance.charts = instance.charts return instance class ChartTypeSerializer(serializers.ModelSerializer): class Meta: …