Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What effective technique can I apply to use the get_initial method twice to solve the problem stated below?
I have created 3 models A,B, and C that are linked to each other using foreign key. Model "B" is linked to Model "A" using OneToOne relationship and Model "C" is also linked to Model "B" using "OneToOne" relationship. I then used then "get_initial()" method to set the initial id_field for the form of model "B" using the foreign key conection with model "A". I later repeated the same "get_intial()" to set the initial id field for the form of model "C" using its foreign key connection with B. This worked as projected. How ever upon deleting a record instance in Model "B" with its id=7 as obtained from an instance in model "A", and re-creating a new record in model "B" using that same id=7. When ever I call the get_initial() method form "C" with the id=7 from model "B", I recieve an error message "matching query does not exist." And when I, increment the called id by 1, I get the correct result of the query. I went further to delete 4 more records in model "B" and recreated them with their ids as passed by model "A". And realized when ever I called the get_initial() method to … -
Allow Blank FileField in Django
I have a model where one of the fields is a FileField. The file that should be attached here is not available at the time of creating the Order - so it should be allowed for the user to create an Order without attaching a file here. If you see the code below - I feel like I have setup the model properly to allow this field to be blank, but when I try to submit an Order, I get an error "The 'order_file' attribute has no file associated with it." So what am I missing? models.py class Orders(models.Model): ... order_file = models.FileField(upload_to='web_unit', default=None, null=True, blank=True) def __str__(self): return self.reference since I have default=None, null=True, blank=True I expected that this would work without uploading the file at time of creating the Order object. -
Type Error on uploading image files through django admin
I've created a personal website/blog with python django, and as an admin, I want to create instances of that blog based on the django model and display it to the html page accordingly. That model basically consists of a Title field, TextArea field, and Image field. My app is currently deployed on Heroku, and I'm serving images using AWS S3 Buckets. Locally, when I create a blog instance through the django admin it is successful, but on the deployed app on Heroku, I'm getting this error: expected string or bytes-like object and this is what appears in the console was loaded over a secure connection, but contains a form that targets an insecure endpoint 'http://dpaste.com/'. This endpoint should be made available over a secure connection. I'm unsure if the error has to do with the image field or the entire instance of the blog model. Any ideas on how to approach this? -
Django Many to Many query set relation has unexpected result
When running a filter against a many-to-many relation the result of the field contains unexpected results according to the filter. Note The is_current Foo and Bar will have at most one True for a group of Foo/Bar. Meaning Foo has several that are False ie. not current and same with Bar. I've tried 4 variations Normal filter: just listing out fields to filter Boolean value as True/1 on the filter Q filter prefetch_releated and Q filter # model.py class Bar(Model): is_current = BooleanField() text = CharField(max_length=32) class Foo(Model): is_current = BooleanField() name = CharField(max_length=32) bar = ManyToManyField(Bar) # views.py def index(request): # when viewing the bar objects from the filter result # it will contain bar objects that are both is_current = True & False return Foo.objects.filter(Q(is_current=1) & Q(bar__is_current=1)) The query output looks like this: SELECT app_foo.id, app_foo.is_current, app_foo.name FROM app_foo INNER JOIN app_foo_bar ON (app_app.id = app_foo_bar.bar_id) INNER JOIN app_bar ON (app_foo_bar.bar_id = app_bar.id) WHERE (app_foo.is_current = True AND app_bar.is_current = True) If I modify the query and run it in the dbshell I get what I expected. SELECT app_foo.id, app_foo.is_current, app_foo.name, app_bar.text FROM app_foo INNER JOIN app_foo_bar ON (app_app.id = app_foo_bar.bar_id) INNER JOIN app_bar ON (app_foo_bar.bar_id = app_bar.id) … -
How to bined a detailview field to a form field in django and save into database
I am building this simple system for online voting, where people can vote but will have to pay for their vote cast.My current challenge is how to bined a selected candidate on a page and allowing voters to enter number of votes they went to cast for that candidate on the same page I have tried using SingleObjectMixin but am having problem saving the form in database. And also how can i prepopulate the select candidate to a model field name Nominee model.py class Award(models.Model): STATUS_PUBLISHED = ( ('Closed', 'Closed'), ('Opened', 'Opened'), ) slug = models.SlugField(max_length=150) name = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='award_images') status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed') def __str__(self): return self.name class Category(models.Model): Award = models.ForeignKey(Award, on_delete=models.CASCADE) category = models.CharField(max_length=100,) slug = models.SlugField(max_length=150) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class Nomination(models.Model): Fullname = models.CharField(max_length=120) Category = models.ForeignKey(Category, on_delete=models.CASCADE) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=150) image = models.ImageField(upload_to='nominations_images') def __str__(self): return self.Fullname class VoteAmount(models.Model): Nominee = models.ForeignKey(Nomination, on_delete=models.CASCADE) votes_amount = models.IntegerField(default=0) def __str__(self): return self.votes_amount views.py from django.views.generic import ListView, DetailView, CreateView from .models import Award, Category, Nomination, VoteAmount from .forms import VoteAmountForm from django.urls import reverse from django.http import HttpResponseForbidden from django.views.generic import … -
Django REST Framework Deep Dive - Where is it determined that an enpoint needs an auth token
general django question for those who are more experienced than myself, I'm reading through the code posted for a tutorial on thinkster.io: https://github.com/howardderekl/conduit-django/tree/master/conduit/apps There's an endpoint pertaining to the User model authenticion/models.py that requires an Authorization header for it to return user information defined here in authentication/views.py: class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (UserJSONRenderer,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) My question is how/where is it (supposed to be) determined that an endpoint requires this Authorization. My thought is that it is tied to the permission_classes variable stated in the UserRetrieveUpdateAPIVIiew class above. I dug into the package location where this was imported from (from rest_framework.permissions import IsAuthenticated), but that doesn't appear to contain anything pertaining to an HTTP header: class BasePermissionMetaclass(OperationHolderMixin, type): pass class BasePermission(metaclass=BasePermissionMetaclass): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True ... ... ... class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): return bool(request.user and … -
Whenever I try to load a static file, it gives error 404 not found
Whenever I try to load a static file, it gives error 404 not found. However when checking what directory it looks in it shows /account/login/static/accounts/style.css, when account/login isn't even a directory. The error message is Not Found: /account/login/static/accounts/style.css I've searched everywhere and can't find how to change the directory. Here is the settings.py file: STATIC_URL = '/static/' LOGIN_REDIRECT_URL = '/accounts' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Here is my accounts/urls.py: from django.contrib.auth.views import LoginView from django.urls import path from accounts import views app_name = "users" urlpatterns = [ path('', views.home, name='home'), path('login/', LoginView.as_view(template_name='accounts/login.html'), name="login") ] Here is my tutorial/urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('accounts.urls')) ] And here is my view.py: from django.shortcuts import render, HttpResponse def home(request): return render(r[enter image description here][1]equest, "accounts/login.html")[enter image description here][1] Here is a image of my directory/files: https://i.stack.imgur.com/vdk0X.png -
In Django, how can I build a set of criteria from a list?
I'm using Python 3.7 and Django. Is there a way I can rewrite the below so taht I just execute one query instead of a bunch? def get_articles_with_words_in_titles(self, long_words): result = {} for word in long_words: qset = Article.objects.filter(title__icontains=word.lower()) result.extend( qset ) return result I want to get a unique list of the Article objects that have at least one of the words in them. -
Cannot add CSRF token to XMLhttpRequest for Django POST request
CSRF token is not being added to the header of the XMLhttpRequest. To make sure all the other code works, I've tried using a GET request to the server and everything works as it should. However when I add the CSRF token to the header the code stops running when adding the header. // [PROBLEM CODE] // Initialize new request const request = new XMLHttpRequest(); const currency = document.querySelector('#currency').value; request.setRequestHeader({'csrfmiddlewaretoken': csrftoken}); // [<---HERE] request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); // [<---HERE] request.open('POST', '/convert'); // [THIS WORKS] // Initialize new request const request = new XMLHttpRequest(); const currency = document.querySelector('#currency').value; request.open('GET', '/convert'); request.send(); When I take out the two problem lines of code, setRequestHeader and make a POST request. The error message I get is "Forbidden (CSRF token missing or incorrect.): /convert" -
Dinamically Filtering based on foreign key in Django Admin View
Question regarding admin view editing models. I can't figure out how to dinamically filter a the foreign keys of a TabularInLine model based on the foreign key of the currently edited model. models.py: from django.db import models class A(models.Model): name = models.CharField(blank=False, max_lenght=50) class B(models.Model): fkA = models.ForeignKey(A, on_delete=models.CASCADE) name = models.CharField(blank=False, max_lenght=50) class C(models.Model): fkA = models.ForeignKey(A, on_delete=models.CASCADE) fkB = models.ForeignKey(B, on_delete=models.CASCADE) name = models.CharField(blank=False, max_lenght=50) admin.py: from django.contrib import admin from .models import A, B, C class BInline(admin.TabularInLine): model = B class CInline(admin.TabularInLine): model = C @admin.register(A) class AAdmin(admin.ModelAdmin): inlines = [BInline, CInline] admin.site.register(B) admin.site.register(C) The thing is, I want that in the admin edit view of A, at the inline section of C the dropdown which includes B to list only the models that are associated with the currently edited A model through the foreign key. As it is it lists all the available models in my database. I hope I was clear in my explanation and that anyone is kind enough to help me. Thanks! -
Calling a Django-Rest API from a Django Form
I built a Django-Rest API with an APIView that uploads a file to a folder of a web server. This API is working with Postman as shown in the pictures below. Now, I am working on calling this API from the below HTML form Issue I am facing: the file sent via the form returns the following error "file": [ "No file was submitted." ] Below the code of my application index.html <form action="/file/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input id="audio_file" type="file"/> <input type="submit" value="Upload File" name="submit"/> </form> views.py class IndexView(TemplateView): template_name = "index.html" log = logging.getLogger(__name__) log.debug("Debug testing") def post(self, request): # TODO: fix, empty file error returned after calling post method # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: # https://docs.djangoproject.com/en/2.2/ref/forms/api/#binding-uploaded-files form = FileForm(request.POST, request.FILES) # check whether it's valid: if form.is_valid(): form.save() # redirect to the same URL: return HttpResponseRedirect('/App/index/') # if a GET (or any other method) we'll create a blank form else: form = FileForm() return render(request, 'index.html', {'form': form}) class FileView(views.APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request): … -
Yubikey OTP via Yubicloud not working in DJANGO behind nginx
Using the package django-otp-yubikey to provide Yubikey 2FA for the admin panel in a DJANGO application works without any problems when using GUNICORN, but as soon as we using GUNICORN and NGINX in front of it, the package doesn't work anymore. Tried contacting different versions of the Yubicloud API (1, 1.2, 2). Also tried contacting them with SSL disabled / enabled. This is the nginx configs: location /...../ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/../.../...sock; allow X.X.X.X; deny all; } Getting a 504 gateway timeout when NGINX is in front of the django application, making me believe it might be blocking a the request made to the yubicloud servers. -
Filtering data before rendering- django-filters
I am using django-filters, and i want that data only with status = 1 should be displayed. I will not be showing status in my diplayed table. filters.py class ActiveSimFilter(django_filters.FilterSet): type = django_filters.CharFilter(field_name='name', lookup_expr='icontains') phone_number = django_filters.CharFilter(field_name='phone_number', lookup_expr='icontains') class Meta: model = Sim fields = { } order_by = ["type"] def get_initial_queryset(self): return Sim.objects.exclude(sim_status=1) -
Containerized nginx server return 503 error
I am trying to use nginx as a reverse proxy for running multiple web apps. My files' contents are as below: Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 ENV APP_ROOT /mysite/subdomain.mysite ENV PROD True ADD requirements.txt /requirements.txt ADD Pipfile /Pipfile ADD Pipfile.lock /Pipfile.lock RUN pip install pipenv RUN pipenv install --system --deploy --ignore-pipfile RUN pip install --upgrade pip RUN mkdir -p ${APP_ROOT} WORKDIR ${APP_ROOT} ADD . ${APP_ROOT} COPY mime.types /etc/mime.types EXPOSE 8001 RUN if [ -f manage.py ]; then python manage.py collectstatic --noinput; fi CMD ["gunicorn", "-b", "0.0.0.0:8001", "subdomain.wsgi"] docker-compose.yml: version: "3.7" services: postgres: container_name: subdomain-postgres image: postgres:9.6 ports: - 5432:5432 volumes: - ./pgdb:/var/lib/postgresql/data # .env file contains postgres username, database name and password env_file: .env webapp: container_name: subdomain build: . restart: "always" env_file: .env environment: - VIRTUAL_HOST=subdomain.mysite.com,www.subdomain.mysite.com - VIRTUAL_PORT=8001 - TIMEOUT=300 - HTTP_PORT=8001 - STATS_PORT=8046 volumes: - .:/subdomain.mysite ports: - "8001:8001" depends_on: - "postgres" networks: default: external: name: nginx-proxy As you see from above files I am running services postgres and webapp that are built on python image. My web app is a django project and .env file referenced in above docker files just contain postgresql related variables (username, database name, password and etc.). As of nginx-proxy network, it is … -
I'm not getting all the records for specific month
I'm trying to get all the posts from each month, like July has 11 and August has 1. But at this point when it loops I'm getting one of each month. This will be the result: 2019 Aug (1) Time Lapse Video vs. Time Lapse Photo Test Jul (11) A simple Tutorial about how to add Facebook login in your website. This is my code on the template: {% regroup events by timestamp.year as year_list %} {% for year in year_list %} {{ year.grouper }} {% regroup events by timestamp.month as month_list %} {% for month in month_list %} {{ month.list.0.timestamp|date:"M"}} ({{ month.list|length }}) {% for post in events %} {% if post.timestamp == month.list.0.timestamp %} {{post.title}}<br> {% endif %} {% endfor %} {% endfor %} {% endfor %} I expect to get the rest of month of July. thank you. -
A tourist place can have multiple themes. How to implement this in django models?
This is my current django models . How can I store multiple Themes for a place name Themes are like adventure , beaches , heritage , hill stations etc A place can be both under adventure , beaches from django.db import models class places(models.Model): place_id = models.AutoField(primary_key=True) place_name = models.CharField(max_length=50) city = models.CharField(max_length=50) state = models.CharField(max_length=50) country = models.CharField(max_length=50) description = models.TextField() theme = models.ForeignKey('Theme',on_delete=models.CASCADE) class Theme(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name -
ModuleNotFoundError: No module named 'AppName' in Django
I did install django in server. Instead of installing apps next to the django project folder, I installed them inside the django project folder. (I put them next to the settings.py and wsgi.py) This is structure of django project: BaseFile |__django | |___administrator | | |___ views.py | | |___ urls.py | | |___ ... | | | |___blog | | |___ views.py | | |___ urls.py | | |___ ... | | | |___ __init__.py | |___ settings.py | |___ urls.py | |___ wsgi.py | |___ env |___ manage.py |___ media |___ static |___ templates And this is my settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # MY APPS: 'administrator.apps.AdministratorConfig', 'blog.apps.BlogConfig', ] And when I want to makemigrations I got this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "BaseFile/env/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "BaseFile/env/lib64/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "BaseFile/env/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "BaseFile/env/lib64/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "BaseFile/env/lib64/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, … -
How to show live sensor data using django
I have a production Django application that is being used to view a dashboard of sensor data. Currently my sensors are sending their values to my database via Django REST framework. So I am passing the sensor values in JSON format using python requests, which then saves a record each time it receives the data. This works well when I am sending sensor data every 30 minutes, however I want to see certain sensor data as real-time as reasonable. Would it be practical to keep my existing setup, but just post the sensor data every 2 seconds, and use AJAX to update the page every 2 seconds? Or should I be taking a completely different approach here. Any help is appreciated! -
How to pass extra context (which is base on filtered qs) to django's change list admin view?
Here is how to pass extra context: Django how to pass custom variables to context to use in custom admin template? But what if I need to calculate extra context based on filtered queryset? Django calculates queryset inside changelist_view and doesn't allow to touch that qs afterwards. My current solution is to copy-paste django's changelist_view and inject hook with extra_context_2 which can be calculated based on queryset. But for obvious reasons it's bad approach. Any other ideas? -
AttributeError: 'tuple' object has no attribute 'get'
I have a problem in Django, I really don't know what the error is. The error happens in an UpdateView view, when putting severalinputs in the view, to know precisely where the error is, because I did not find it, the error does not happen in the view as such, I think it is the form : class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['title', 'subtitle', 'image', 'description', 'status'] widgets = { 'title': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Titulo'}), 'subtitle': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Subtitulo'}), 'image': forms.FileInput(attrs = {'class': 'custom-file-input'}), 'description': forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Descripcion'}), 'status': forms.Select(attrs = {'class': 'custom-select'}), } labels = {'title': '', 'subtitle': '', 'image': '', 'description': ''} def __init__(self, *args, **kwargs): self.title_valid = False if 'title_valid' in kwargs: self.title_valid = kwargs.pop('title_valid') super().__init__(args, kwargs) def clean_title(self): title = self.cleaned_data['title'] if self.title_valid: if Course.objects.filter(title = title).exists(): raise forms.ValidationError('Ya existe un curso registrado con ese titulo, elige otro.') return title I could also see that the clean_title method is not executed, layers there the error happens ... View: class CourseUpdateView(UpdateView): model = Course form_class = CourseForm template_name = 'instructor/course_update_form.html' success_url = reverse_lazy('instructor:course:list') success_message = 'Se modificó con éxito el curso "{}".' def get_form(self, form_class … -
Keeping items per page static while paginating
I posed a question and got a quick response (thanks, Bob!) on how to do pagination in Django: Change value for paginate_by on the fly However, as outlined below, I'm having an issue getting the items per page to remain set. I modified my ProdListView.html template to show buttons with page numbers, but, while it works, I'm getting an odd behavior. I have a for loop that I use to put out the page numbers as buttons: {% for i in DataPaginated.paginator.page_range %} {% if DataPaginated.number == i %} <button class="w3-button w3-amber">{{ i }} </button> {% else %} <a href="?page={{ i }}" class="w3-button">{{ i }}</a> {% endif %} {% endfor %} If the pagination is set to the default of ten this works properly and shows three pages (there are 24 items). If I change the pagination to 20, it looks correct at first and shows two pages. However, if I click on the second page, it changes my pagination back to 10, shows three pages again, and places me on the 2nd of the three pages. In the interest of space, you can find the code I'm using in the views.py file and template file, besides the fragment above, … -
Need help on nested Django Rest Framework
I am working on DRF first time and got stuck at one place. This is just a hypothetical example related to issue I am facing: models.py class Manufacturer(models.Model): manufacturer_id = models.CharField(max_length=25, primary_key=True) manufacturer_name = models.CharField(max_length=25) class Car(models.Model): manufacturer = models.ForeignKey( Manufacturer, related_name='manufacturerCars', on_delete=models.CASCADE) car_id = models.CharField(max_length=25, primary_key=True) car_name = models.CharField(max_length=25) Serializers.py class ManufacturerSerializer(serializers.ModelSerializer): class Meta: model = Manufacturer fields = ("manufacturer_id", "manufacturer_name", "manufacturerCars",) class CarSerializer(serializers.ModelSerializer): manufacturer = ManufacturerSerializer() class Meta: model = Car fields = ("car_id", "manufacturer") When I access /api/cars/ endpoint, I get all the details about car including it's manufacturer: car_details = [ { "car_id": "1", "car_name": "abc", "manufacturer": { "manufacturer_id": "1", "manufacturer_name": "XYZ", "manufacturerCars": [ "1", "7", "3", "5" ] } } ] Question: What approach should I take to list all the cars associated with current car's manufacturer -manufacturerCars field in above output- (i.e. details about cars with id 1, 7, 3, 5) ? Do I need to iterate over all the data that I got from /api/cars i.e. car_details to extract details about car id 1, 7, 3, 5 ? Highly appreciate your help! -
Django will not send email confirmation
So I am setting up a site. Users can register but after registration, they are required to verify their email. I have everything set up and it worked fine yesterday. However, today when I went to the site and created a new user, the browser gets stuck on trying to send the confirmation email, it says waiting for 127.0.0.1. at the bottom left of the screen. But the user was created because I can see them in my database. settings.py EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' views.py # Create your views here. def register(request): if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): # Create an inactive user. User will be unable to login until email is verified: user = form.save(commit=False) user.is_active = False user.save() # Send an email to the user with the token using the email template in the template folder. current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string('acc_active_email.html', { 'user': request.user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) # The email is being sent using the SMTP configuration in settings.py to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please confirm … -
Summary of Django nested foreign keys
I have the following models in my Django 2.2 project: class ModelA(models.Model): ModelA_id = models.UUIDField('ModelA ID', default = uuid.uuid4) class ModelB(models.Model): ModelB_id = models.UUIDField('ModelB ID', default = uuid.uuid4) ModelA = models.ForeignKey(ModelA, on_delete=models.CASCADE) class ModelC(models.Model): ModelC_id = models.UUIDField('ModelC ID', default = uuid.uuid4) ModelB = models.ForeignKey(ModelB, on_delete=models.CASCADE,) class ModelD(models.Model): ModelD_id = models.UUIDField('ID', default = uuid.uuid4) ModelC = models.ForeignKey(ModelC, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) As you can see, the models are nested like: ModelD has FK to ModelC ModelC has FK to ModelB ModelB has FK to ModelA If I do this: ModelD.objects.filter(pk=0).select_related('ModelC__ModelB__ModelA') does this mean that all data is queried at once in a single (or limited) data base request? I assume this also means it puts all data references starting at ModelD into memory, correct? My end goal is to summarize how many ModelDs reference ModelC, what (not how many) ModelCs reference ModelB, and lastly what ModelBs reference ModelA. -
ModuleNotFoundError: No module named 'django' in AWS ElasticBeanstalk
I'm getting 500 Internal Server Error when running my python webapp through AWS EBS. The following is shown in the server logs: [:error] Target WSGI script '/opt/python/current/app/ipsite/ipsite/wsgi.py' cannot be loaded as Python module. [:error] Exception occurred processing WSGI script '/opt/python/current/app/ipsite/ipsite/wsgi.py'. [:error] Traceback (most recent call last): [:error] File "/opt/python/current/app/ipsite/ipsite/wsgi.py", line 12, in <module> [:error] from django.core.wsgi import get_wsgi_application [:error] ModuleNotFoundError: No module named 'django' The requirements.txt file is present in the root folder and contains Django==2.2.4 The app works when run on my local machine. It does not work when uploaded to AWS. I have tried creating the environment from the beginning but still get the same error. wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ipsite.settings') application = get_wsgi_application() My main directory structure: -.ipsite/ -ipget/ -__init__.py -models.py -tests.py -views.py -ipsite/ -__pycache__/ -__init__.py -settings.py -urls.py -wsgi.py -.ebextensions/ -django.config -.elasticbeanstalk/ -config.yml -.git/ -manage.py -mysite.db -requirements.txt How do I make my AWS environment recognize django?