Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django subqueries & aggregates
I have three models - Patient, Prescription and Medicine. A Patient can have zero or more Prescriptions and a Prescription can have zero or more Medicines. Medicine has a duration field indicating the days for which the medicine is to be taken. If we have say, two Prescriptions with two Medicines each with durations of 15, 15 and 15, 30 respectively, then the maximum prescription duration for the 2 Prescriptions are 15 and 30 respectively. And the total medication duration for that Patient is 15 + 30 = 45. Now I want to filter the Patient queryset to find all Patients whose total medication duration is at least a certain specified value. Following is the code (using Django 3) I am trying. But, taking the above example, the total medication duration I get is 30, not 45. from django.db import models from django.db.models import Subquery, OuterRef, Max, Sum class Patient(models.Model): name = models.CharField(max_length=300) # ... class Prescription(models.Model): patient = models.ForeignKey( Patient, related_name="prescriptions" on_delete=models.CASCADE ) # ... class Medicine(models.Model): prescription = models.ForeignKey( Prescription, related_name="medicines" on_delete=models.CASCADE ) duration = models.PositiveIntegerField() # ... def get_patients_with(minimum_medication_duration=365): patient_qs = ( Patient.objects .annotate(total_medication_duration=Subquery( Prescription.objects .filter(patient=OuterRef('pk')) .values('patient__pk') .annotate(max_prescription_durations=Subquery( Medicine.objects .filter(prescription=OuterRef('pk')) .values('prescription__pk') .annotate(max_duration=Max('duration')) .values('max_duration') )) .annotate(total_medication_duration=Sum('max_prescription_durations')) .values('total_medication_duration') )) … -
Django Web Scraping
I have a Django project that I am working on, to scrape data from a website and display it on the Django page. The page however takes about 10 seconds to load, because accessing the data from another website isn't quick. My solution to this would be to create a model that stores the data, then updates itself in the background, but I don't know how to execute this. I am also open to other options, I'm pretty new at this :) This is currently what my code looks like, which is too slow: from django.shortcuts import render import requests, json def getNums(): from bs4 import BeautifulSoup import time, urllib.request, requests url = "https://www.worldometers.info/coronavirus/" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") numberContainers = soup.select(".maincounter-number") spanTags = [] for container in numberContainers: spanTags.append(container.findChildren("span")) numbers = [] for container in spanTags: numbers.append(container[0].decode_contents()) return numbers def homeView(request): numbers = getNums() cases = numbers[0] deaths = numbers[1] recovered = numbers[2] context = { "cases": cases, "deaths": deaths, "recovered": recovered, } return render(request, "home.html", context) -
Running executable backgroung program inside server
I'm an intern in a laboratory in my college that works with air quality, and they want me to improve their website that runs one of the programs that air quality researchers use (I think that the program is written in RUST). The way it works right now is that the user uploads some necessary files to the webapp (that is written in Django btw) and then the webapp calls this program, that runs on the server with the uploaded files. The problem is that if the user leave or refresh the page, the background program will stop. I have never dealt with this concept of running other executables in the background of the server, so I'm having some problems understanding it all. I came across the "Celery" package for python, but it seems really hard to implement and I was wondering if there was any other ways of doing this. -
Django 3.1.7 query parameter separators
With the change in Django 3.1.7 to not allow using ; as a default query parameter separator, what is the suggestion moving forward? Is there something else that should be used instead? Where does one specify which query param separators are permitted? There are the release notes for this version. -
Use python's mock patch.object to check if a functions is called
I need to assert if a function is called @requests_mock.Mocker() def test_api_mca_payment_confirmation_call_db_log(self, mocker): mocker.register_uri('GET', requests_mock.ANY, status_code=200, text='test') with patch.object('__name__', 'db_log') as m: r = api_payment_confirmation(txn_no=900) m.assert_called_once() The problem is on the first patch.object parameter, what to put there if my db_log function is not inside any class. It works if i put a db_log function inside a class eg class Sample: @static_method def db_log(): pass And change line to patch.object('__name__', 'db_log') as m: How can i do the same thing for functions outside class -
RegexValidator didn't catch violation of regex
Django 3.1.7 class RenderedCssFile(models.Model): css_pattern = r".*-\d+\.css$" regex_validator = RegexValidator(regex=css_pattern, message=gettext("File name must follow: ") + css_pattern, ) file_name = models.CharField(max_length=255, verbose_name=gettext("File name (eg. main-1.css"), validators=[regex_validator], ) Could you help me understand why a file called 'bootstrap.css' has managed to upload? I estimated it to fail, but it uploaded. I've made a mistake somewhere. My regex: https://regex101.com/r/N5aL0C/1/ I need that only bootstrap-1.css or the like should be accepted. -
Django Signals: Can't Use For Loop?
When i remove the for loop in the signals then it works (creates an object properly) but when i use the for loop it should create an object for each post in the Collection object but this doesn't work. It doesn't even create an object of the Collection_List_Item model. Is there a reason why this for loop doesn't work? Is there a way to work around this? models class Collection(models.Model): posts = models.ManyToManyField(Post, related_name='collection_posts', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection_name = models.CharField(max_length=100) collection_description = models.CharField(max_length=1000, blank=True) collection_likes = models.ManyToManyField(User, related_name='liked_collections', blank=True) collection_image = models.ImageField(upload_to="images/") private = models.BooleanField(default=False) follows = models.ManyToManyField(User, related_name='collection_follows', blank=True) def __str__(self): return self.collection_name class Collection_List_Item(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) saved = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.collection.collection_name signals: @receiver(post_save, sender=Collection) def create_collection_list_item(sender, instance, created, **kwargs): if created: for i in instance.posts.all(): collection_list_item = Collection_List_Item.objects.create(collection=instance, user=instance.author, post=i) collection_list_item.save() -
Performance issues with django-storages + CloudFront
I'm using S3 Buckets for static and media files of my Django app. I have AWS CloudFront "in front" of the Buckets and I have setup django-storages in order to use this CDN to serve me my files. However, my requests are taking too long. It is worth mentioning that I am using HyperlinkedModelSerializer and VersatileImageField. I would expect that my files were retrieved by the CDN but it looks like my app is using boto3 to actually download the files from S3 (and I think this is happening during serialization). Here's some information from cProfile: ncalls tottime percall cumtime percall filename:lineno(function) 174 0.004 0.000 17.172 0.099 /MyProjectPath/env/lib/python3.8/site-packages/storages/backends/s3boto3.py:515(exists) 61 0.003 0.000 16.586 0.272 /MyProjectPath/env/lib/python3.8/site-packages/boto3/s3/inject.py:723(object_download_fileobj) 61 0.001 0.000 16.582 0.272 /MyProjectPath/env/lib/python3.8/site-packages/boto3/s3/inject.py:624(download_fileobj) 62 0.003 0.000 57.723 0.931 /MyProjectPath/env/lib/python3.8/site-packages/rest_framework/serializers.py:507(to_representation) 62 0.000 0.000 57.687 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/serializers.py:53(to_representation) 62 0.000 0.000 57.687 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/serializers.py:42(to_native) 62 0.003 0.000 57.686 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/utils.py:220(build_versatileimagefield_url_set) I don't think the app should be contacting the S3 Buckets directly. Has anyone experienced this? Could this be a because of a misconfiguration or is there any known issue related to DRF/django-storages/VersatileImage that would affect performance this badly? -
How to create two type of users in a django website, re-writting authentication back end
So, this is how i am trying to create the two models: class UserManager(BaseUserManager): def create_user(self, email, username, year, branch, rollNo, password=None): if not email: raise ValueError("Users must have an email") if not username: raise ValueError("Users must have a username") if not year: raise ValueError("Users must specify an year") if not branch: raise ValueError("Users must specify a branch") if not rollNo: raise ValueError("Users must have a roll number") user = self.model( email=self.normalize_email(email), username=username, year=year, branch=branch, rollNo=rollNo ) user.set_password(password) user.save(using=self._db) return user def create_guest(self, username, college, year, email, password=None): if not username: raise ValueError("Please give a valid username") if not college: raise ValueError("Please provide your college") if not year: raise ValueError("Specify your year") if not email: raise ValueError("A valid email needs to be provided") user = self.model( email = self.normalize_email(email), username = username, year = year, college = college ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, year, branch, rollNo, password): user = self.model( email=self.normalize_email(email), username=username, year=year, branch=branch, rollNo=rollNo, password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.set_password(password) user.save(using=self._db) return user class GuestUser(AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date_joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last_login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) … -
How to use two different databases in Django? (SQLite and MongoDB)
For my project, I'm trying to set up two different databases in Django. These databases are SQLite and MongoDB. What I'm trying to do is I'm trying to hold user data in SQLite and for big data, I want to use MongoDB. After so many searches on the internet, I couldn't understand how to do it. I just did this little code in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), }, 'bigdata_db' : { 'ENGINE' : 'mypackage.backends.mongodb', 'NAME' : 'bigdata_db', 'HOST' : '', } Please someone could help me. I'm really trying so hard to understand but it's so complicated for me. Also, in Django SQLite came already set up but here the main issue is how to set up MongoDB and connected two of them. -
Transmit a param into its validator and make migrations?
Django 3.1.7 I've transmitted a param to its validator: class RenderedCssFile(models.Model): char_pattern = r".*-\d+\.css$" file_name = models.CharField(max_length=255, verbose_name=gettext("File name (eg. main-1.css"), validators=[lambda value: GeneralValidator. validate_charfield_against_pattern( value, RenderedCssFile.char_pattern), ], ) I was very glad. But only before migrations were made: Migrations for 'staticassets': staticassets/migrations/0001_initial.py - Create model RenderedCssFile - Create model PhpFile - Create model JsFile - Create model CssFile 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 "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 182, in handle self.write_migration_files(changes) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 219, in write_migration_files migration_string = writer.as_string() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 99, in serialize _write(arg_name, arg_value) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 51, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 271, in serialize return serializer_factory(value).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 199, in serialize return self.serialize_deconstructed(path, args, kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 86, in serialize_deconstructed arg_string, arg_imports … -
Can I control how often the pre-ping connection check is done in SqlAlchemy connection pooling?
Environment / usage case info I have a SqlAlchemy django-postgrespool2 connection pool used to connect to a PostgreSQL database. Problem I'm considering using the pre-ping feature in my SqlAlchemy connection pool. However, I read that the pre-ping check is done for every pool connection checkout. I have done some tests, to me this checkout seems to occur for every SQL command I send to the database. I'm concerned all those pre-ping checks will cause a big overhead/delay if the check is made for every SQL command sent to the database. Question Is there a way to configure how often or after what time the pre-ping check should be made? Or do I have to implement my own solution to customize how often the connection is checked? How? Thanks! -
How should I develop the front-end? (help!) [closed]
So basically I have this idea for a web application where users can upload 'posts' which than will be upload to the 'feed'. So pretty much like all forums, social media applications, etc. Just like for example Reddit, I want the user to have specific options in de 'make-a-post-template' that he/she can fill in. It's a pretty complicated concept if I go in the dept of it, but my real question here is: How should I develop the front-end? Here are some key-points that I take in for the decision: I have never used a front-end framework before (basic knowledge of Javascript). But I'm willing to learn if there is much benefit to gain from it. It's going to be a forum website like Reddit, but for a specific audience. I want to use Django Please help me out here, I'm worried that if I don't use a front-end framework, that the speed of the website will dramatically decrease, and because I'm using diffrent content blocks, to create a 'dashboard' kind of style, that something like React will be very suitable for this. Take a look at the images to get some idea of how it's going to work and … -
How to use existing mysql DB along with its migrations in sql, in the Django? What changes will need to do in the django for using the mysql db?
I am already having one mysql database with a lot of data, of which tables and migrations are written in sql. Now I want to use the same mysql database in django so that I can use the data in that database.I am expecting that there will not be need for making the migrations as I am not going to write the models in Django again, also what will be the changes/modification I will have to do. For eg: as in middlewares?. Can anyone please help me in this? -
Asynchronous computation and save in django 3 models
I have a problem making part of my models asynchronous in Django 3. This is my models.py: class ModelImages(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name="slice_img") img = models.ImageField(editable=False) #other def get_slices(instance): # operations return images_array_list def process_3d_image(sender, instance, created, **kwargs): if created: imgs = get_slices(instance) for img in imgs: # other operations case_img = ModelImages(case=instance, img=name) with transaction.atomic(): case_img.save() post_save.connect(process_3d_image, sender=Case) The code is longer but I reported only the crucial parts. It works correctly but I want to make 'process_3d_image' function asynchronous. I tried Celery, Trio, and others without any result. How could I do it? -
Docker containing a Django application a not saving database after stopping container
I have build a Django application with SQLite database. The database is reinitialized and migrated every time the container is started using docker-compose up losing all the previous data. It also not creating db or any other files. Using the latest version of docker. -
How to display a list of posts in a list of categories in Django
I am looking for my web page to display a list of categories and a list of each post within the category. For example: However, it is looping through and displaying each category and associated post separately, like this: Here is Template: <ul> {% for p in object_list %} <li> {{p.category.name}} <ul> <li> {{p.title}} </li> </ul> </li> {% endfor %} </ul> Model class Category(models.Model): name = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category', null=False) Views class CategoryList(ListView): template_name = 'category_list.html' def get_queryset(self): return Post.objects.all().select_related('category') -
Overriding get() method in Django UpdateView gives 'str' has no attribute get error
I have a Stats model which is related to Django User model with a OneToOne Field. I have an UpdateView: class StatsUpdateView(UpdateView): model = Stats fields = ('stat1', 'stat2', 'stat3') It works fine, but any User is allowed to modify the Stats related to any User, I want a User to onlyupdate the Stats related to him. So I override the get() method in StatsUpdateView like this: def get(self, *args, **kwargs): if self.request.user != Stats.objects.get(pk=kwargs['pk']).user: #checks if the user logged in is the same user related to the Stats with the onetoone field. Works fine. return redirect('homepage:home') else: # if the user match, he can access the update view for his own stats print('user match') return reverse('user:updatestats', kwargs={'pk': kwargs['pk']}) The code runs fine until the else statement, 'user match' gets printed into the console but I get this error while running the server: 'str' object has no attribute 'get' Here's the path: path('updatestats/<int:pk>/', StatisticheUpdateView.as_view(), name='updatestats') -
Logging Output for Session on Webclient
I'm using Django to deploy some of my calculations-modules and allow registered and unregistered users to make use of them. Now I happen so see on the serverlogs sometimes invalid files are uploaded and during the process I'm able to fix it to some degree. These calculation-modules are separated from the Django-Project, but still on the same server. My first thought would be to pass on logging-variables through them and return them in the end of the calculation in the server response. This seems to be a dirty and rather invasive solution as everything is basically protocolled with with the basic logging. Any of my methods would with that get an additional logging-variable. Apparently Output log file through Ajax in Django seems to somewhat fit to what I am looking for but this appears only to show the full logs and not by session (given the case one user has two sessions). The modules in the backend don't have any session-ID, but it wouldn't be too difficult to add it just in the constructors. The Ajax-Module on the Client doesn't seem to be the problem (plenty of sources, like: Django - How to show messages under ajax function), but how … -
Django static files not updating inside docker container
My Django project uses Docker, gunicorn, and whitenoise. I recently altered settings to prepare for deployment, most notably adding configurations for AWS-hosted media files. Now when I run the project locally and collectstatic the static files do not update in the browser. I do, however, see the changes where static files are collected. Things I've tried/double checked: Ensuring I have a shared volume between the container and where static files are kept/updated Adding a step to collectstatic in my Dockerfile Confirming my static files settings Is something about django-storages causing the issue? I thought that previously I was able to make SCSS changes and have them show up by refreshing the browser. But that's not happening. Even running collectstatic inside the container has no effect. # relevant settings.py INSTALLED_APPS = [ ... "whitenoise.runserver_nostatic", "storages", ... ] MIDDLEWARE = [ "django.middleware.cache.UpdateCacheMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ... ] # AWS config (use in production only) USE_S3 = env.bool("USE_S3", default=not DEBUG) if USE_S3: AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", default="") AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", default="") AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", default="") AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = env.str("AWS_S3_REGION_NAME", default="us-east-2") AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } # S3 Public Media Settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' # … -
Django_tables2 + django_filter, edit template of table, reload after POST
I am using django_tables2 and django_filter in my website. I use standard template bootstrap.html but slightly modified. The problem is i can not use 'querystring' or 'render_attrs' anywhere. When I use simply: {% render_table table %} everything works fine. Also when I only display data, it works. Here's my html and the code. First of all, code that works: (home.html) {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% block table-wrapper %} <div class="table-container"> {% block table %} <table class="table table-bordered table-hover w-100 shadow-lg p-3 mb-5 bg-white"> {% block table.thead %} {% if table.show_header %} <thead class="table-dark" {{ table.attrs.thead.as_html }}> <tr> {% for column in table.columns %} <th {{ column.attrs.th.as_html }}>{{ column.header }}</th> {% endfor %} <th style="width:11%">Akcja</th> </tr> </thead> {% endif %} {% endblock table.thead %} {% block table.tbody %} <tbody {{ table.attrs.tbody.as_html }}> {% for row in table.paginated_rows %} {% block table.tbody.row %} <form method="post" action="."> {% csrf_token %} {% for column, cell in row.items %} <td {{ column.attrs.td.as_html }}> {{ cell }} </td> {% endfor %} <td> {% if row.record.zam_status == 0 %} <button type="submit" name="zatwierdz_zam" value ={{row.record.pk}} class="btn btn-dark btn-sm">Zatwierdź</button> <button type="submit" … -
using React JS components in django teamplates though static files (hybrid model) - what's wrong? (newbie JS/React question)
I am new to JS/React/npm/webpack, and fairly new to Django. I am trying to build search experience (i.e. front-end) for my existing Django web application, and I am planning to use elastic/search-ui components for that. I did some research (How to get Django and ReactJS to work together?) and I am following the hybrid model guide (https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/) where static JS files are used in Django templates. I got to the point where I could display some text from JS script in Django template, now I am trying to display imported JS component and I got stuck. This is my code: package.json: ... "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode development" }, ... "devDependencies": { "@elastic/search-ui": "^1.5.1", "babel": "^6.23.0", "babel-loader": "^8.1.0", "react": "^17.0.1", "react-dom": "^17.0.1", "react-scripts": "^4.0.3", "webpack": "^5.26.3", "webpack-cli": "^4.5.0" } webpack.config.js: const path = require('path'); module.exports = { entry: './ui-react-src/index.js', // path to our input file output: { filename: 'index-bundle.js', // output bundle file name path: path.resolve(__dirname, './reviewer/static/ui-react-build'), // path to our Django static directory }, }; django html template I want to load React components to: {% extends "base_generic.html" %} {% block content %} Test React component <hr> {% load static … -
Django _set.all() filter in QuerySet
I have database and I want to extract specific data of specific user from queryset. Now i have this VIEW def index(request): customerByName = Customer.objects.get(name='pablo') shopListById = ShopList.objects.get(transaction_id=1) shpoListSpecific = customerByName.shoplist_set.all() specificProducts = shopListById.shoplistproduct_set.all() context = {'customerByName':customerByName, 'shpoListSpecific':shpoListSpecific, 'shopListById':shopListById, 'specificProducts': specificProducts} return render(request, 'QuickShopperApp/home.html', context) MODELS class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) device = models.CharField(max_length=200, null=True, blank=True) def __str__(self): if self.name: name = self.name else: name = self.device return str(name) class Product(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class ShopList(models.Model): # cart customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) #product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) class ShopListProduct(models.Model): # each ShopList will have multiple ShopListProduct product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) shopList = models.ForeignKey(ShopList, on_delete=models.SET_NULL, null=True) #shoplistitem.shoplist quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.product) template.html <h3>specificProducts: {{specificProducts}}</h3> On my side i see items of specific customer. specificProducts: <QuerySet [<ShopListProduct: Apple>, <ShopListProduct: Cucumber>, <ShopListProduct: Cucumber>]> How can i get only Apple, Cucumber, Cucumber? -
How do I run Lighthouse CLI during tests in Django?
I would like to run Lighthouse CLI during tests in Django. By default, Django tests don't run a server that can respond to HTTP requests, so this is not possible. How can I run Lighthouse CLI during Django tests? -
Elastic Beanstalk: ModuleNotFoundError: No module named 'OpenSSL'
When deploying my app to Elastic Beanstalk it keep returning the error ModuleNotFoundError: No module named 'OpenSSL' when it is installing the python secrets module. I had the same error on my local machine and installed PyOpenSSL to resolve it. I however keep getting this error in elastic beanstalk despite installing PyOpenSSL first in my requirements.txt file .. error log 2021/03/19 11:37:57.559862 [INFO] Collecting pyOpenSSL Using cached pyOpenSSL-20.0.1-py2.py3-none-any.whl (54 kB) Collecting freezegun==1.1.0 Using cached freezegun-1.1.0-py2.py3-none-any.whl (16 kB) Collecting pytest==6.2.2 Using cached pytest-6.2.2-py3-none-any.whl (280 kB) Collecting secrets Using cached secrets-1.0.2.tar.gz (7.9 kB) 2021/03/19 11:37:57.559967 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 1. Stderr: ERROR: Command errored out with exit status 1: command: /var/app/venv/staging-LQM1lest/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py'"'"'; __file__='"'"'/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-azo2b_35 cwd: /tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/ Complete output (12 lines): Traceback (most recent call last): File "/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py", line 10, in <module> import OpenSSL ModuleNotFoundError: No module named 'OpenSSL' requirements.txt pyOpenSSL freezegun pytest secrets