Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
stuck on virtualenv / django
I am stuck on the issues with virtualenv/django My django had error in migrations and i messed up with few manipualtions: i updated django by pip i was adding PYTHONPATHs i removed and reinstalled env and my projects i removed all django manually from the Python38-32\lib\site-packages to reinstall etc. I thought i should reinstall virtualenv to start over again, but i can't The error when I am trying to uninstall or install virtualenv below. Any tips or solutions? -
Best backend framework for web and mobile applications?
My company is redesigning its backend. We are an ecommerce style business that also deals with providers. We need to track the delivery of products like Uber Eats does with food. We also have a complex inventory managing system where we need to know the location and stock available of certain products to guarantee speedy delivery. Additionally we need to be able to plan deliveries at certain dates in the future. All these things and other planned features and improvements make the functionality quite complex. We want to design our architecture as microservices, although we might start with components and REST API's for now and split them up into services in the future. We want to support a web application first but will develop a hybrid mobile app in the near future as well. I want our backend to: Be scalable Be able to split into microservices as we increase in complexity. Support web application. Support a Hybrid mobile app. What backend framework is best suited for these needs? -
Save user session after authentication in Django Channels
I'm trying to login a user with the help of Websockets & not the form POST method in views.py. asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from app_name.routing import ws_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)), }) routing.py from django.urls import path from .consumers import WSConsumer, WSNewConsumer, WSDash ws_urlpatterns = [ path('ws/login/', WSConsumer.as_asgi()), path('ws/signup/', WSNewConsumer.as_asgi()), path('ws/dash/', WSDash.as_asgi()) ] consumers.py import json from channels.generic.websocket import WebsocketConsumer from django.contrib.auth.models import User from django.contrib.auth import authenticate from channels.auth import login class WSConsumer(WebsocketConsumer): def connect(self): if self.scope["user"].is_authenticated: print("User is already logged in!") else: self.accept() self.send(json.dumps({'message': 'Hello from SERVER!'})) def receive(self, text_data): try: a_json = json.loads(text_data) except json.decoder.JSONDecodeError: print("String could not be converted to JSON") user = authenticate(username=a_json['uname'], password=a_json['password']) if user is not None: login(self.scope, user) self.scope["session"].save() self.send(json.dumps({'logincode': 'Login Successful'})) else: self.send(json.dumps({'logincode': 'Login Unsuccessful'})) def disconnect(self, close_code): pass class WSNewConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(json.dumps({'message': 'Hello from SERVER!'})) def receive(self, text_data): try: a_json = json.loads(text_data) except json.decoder.JSONDecodeError: print("String could not be converted to JSON") try: user = User.objects.create_user(a_json['uname'], a_json['emailid'], a_json['password']) user.save() self.send(json.dumps({'signupcode': '100'})) except: self.send(json.dumps({'signupcode': '300'})) def disconnect(self, close_code): pass class WSDash(WebsocketConsumer): def connect(self): self.accept() self.send(json.dumps({'message': 'Hello from SERVER!'})) def receive(self, text_data): try: a_json … -
Django annotate query with values from Many To Many Relationship
Following the example on Many To Many relationships for Django: https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/ I want to be able to display in the Django Admin a column on the Article listview which contains the title's of associated Publications. So if I have an article a1 which has publications: Publication(title='Pub 1') Publication(title='Pub 2') I want to see a column in the admin listview showing "Pub 1, Pub 2". I could do this with a custom function on the Admin class: class ArticleAdmin(admin.ModelAdmin): list_display = ['publication_titles'] def publication_titles(self, obj): return ', '.join([pub.title for pub in obj.publications.all()]) But that's an N+1 problem: each Article row will execute a query for each associated publication. I see this in the Django debug toolbar, where I see the number of SQL queries executed go from 9 queries to 33 when rendering 24 articles in the listview. I thought maybe I could do prefetch_related in the queryset: class ArticleAdmin(admin.ModelAdmin): list_display = ['publication_titles'] def get_queryset(self, request): queryset = super().get_queryset(request) queryset.prefetch_related('publications') return queryset def publication_titles(self, obj): return ', '.join([pub.title for pub in obj.publications.all()]) But that seems to have no effect on the number of SQL queries executed. I thought I could use annotate() to annotate the queryset used in the admin, but … -
Django React Web App hosted on Digitalocean loading issue Only Home page show's
I have hosted django react blogging web app, only two pages web app, it works fine locally, but when I host it online, the home page load, but when I go to another page, then page become blank, nothing show's, on reload show just a blink of the page, then show off again. this is the link page to my app http://157.230.15.153/ -
Searching a keyword with number of occurence in django
I want o search for a keyword from the descriptions field with an exact number of occurrences in Django. suppose I am searching the keyword 'Balam' with the number of occurrence '5 times'. what will be the query? if the searching keyword 'Balam' query is : filter(descriptions__icontains='Balam') what will be the query for searching 'Balam' with the exact occurence '5 times'? -
Object accessed through queryset doesn't have the attributes in Django
I have the following three models. Every Record can have many Users and each Record has a Resource. Granted I could be doing something grossly wrong here, but I still can't find the error. class Resource(models.Model): identifier = models.UUIDField(default=uuid.uuid4, unique=True) date_added = models.DateTimeField(default=now) def __repr__(self): return f'Resource: {self.identifier}, Time added: {self.date_added}' class URLResource(Resource): url = models.URLField() def __repr__(self): return f'{self.identifier} URL: {self.url}' class Record(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=SET_NULL, null=True) resource = models.OneToOneField(Resource, on_delete=CASCADE) def __repr__(self): return f'Record {{ User: {self.user}, Resource: {self.resource} }}' Here's the behavior that I get in my django shell >>> user = ... # a valid user In [89]: {each for each in Record.objects.filter(user=user)} Out[89]: {Record { User: dave, Resource: Resource object (9) }, Record { User: dave, Resource: Resource object (11) }, Record { User: dave, Resource: Resource object (12) }} In [90]: {each.resource for each in Record.objects.filter(user=user)} Out[90]: {Resource: 044565d1-9ddd-46a0-ae66-829253b45dd9, Time added: 2021-03-28 17:28:25.252009+00:00, Resource: 0ef18b7d-32f6-48c8-9c61-99f02ba6b6a9, Time added: 2021-03-28 19:08:06.178725+00:00, Resource: b4bb69ba-6f41-4c25-8999-d381d923890e, Time added: 2021-03-28 11:45:21.232911+00:00} Something that doesn't work (but should work) # I get an error!!! In [91]: {each.resource.url for each in Record.objects.filter(user=user)} --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-91-1a5c17d5d743> in <module> ----> 1 {each.resource.url for each in Record.objects.filter(user=user)} <ipython-input-91-1a5c17d5d743> in … -
Djanog Posting data in primary model and connected models in one to many relationship over rest API
I have made a simple model in Django / oAuth / Rest Framework with following three models: MODELS class Pet(models.Model): def nextVaccination(self): NEXT_VAC = 2160 #time in hours expirationTime = self.creationTimestamp + timedelta(hours= NEXT_VAC) return expirationTime petID = models.AutoField(primary_key=True) vaccine = models.ManyToManyField('Vaccine') creationTimestamp = models.DateTimeField(default=timezone.now) nextVacTimestamp = models.DateTimeField(blank=True) def save(self, *args, **kwargs): if not self.nextVacTimestamp: self.nextVacTimestamp = self.nextVaccination() super(Pet, self).save(*args, **kwargs) class Vaccine(models.Model): VACLIST = [('P','parvovirus'),('D','distemper'),('C','hepatitis')] vaccineName = models.CharField(max_length=2, choices=VACLIST, blank=False) class Visits(models.Model): def getUser(request): current_user = request.user return current_user.username check_one = models.BooleanField(null=True) check_two = models.BooleanField(null=True) check_three = models.BooleanField(null=True) notes = models.TextField(blank=True) username = models.CharField(max_length=100, blank=True) def save(self, *args, **kwargs): if not self.username: self.username = self.getUser() super(Visits, self).save(*args, **kwargs) SERIALIZERS class VaccineSerializer(serializers.ModelSerializer): class Meta: model = Vaccine fields = ['vaccineName'] class VisitsSerializer(serializers.ModelSerializer): class Meta: model = Visits fields = ['check_one', 'check_two', 'check_three', 'username', 'notes'] class PetSerializer(serializers.ModelSerializer): visits= VisitsSerializer(source='visits_set', many=True) class Meta: model = Pet fields = ['petID', 'vaccine', 'creationTimestamp', 'nextVacTimestamp', 'visits'] VIEW class PetAPIView(APIView): def get(self, request): pets= Pet.objects.all() serializer = PetSerializer(pets, many=True) return Response({ 'data': serializer.data }) def post(self, request, *args, **kwargs): serializer = PetSerializer(data= request.data) if serializer.is_valid(): serializer.save() return Response({ 'message': 'Message data posted successfully!', 'data': serializer.data }) class VaccineAPIView(APIView): def get(self, request): # pets= Pet.objects.all() vaccine= Vaccine.objects.all() … -
How to return related objects a queryset's values_list instead of just the PKs
Is there a way to neatly return a queryset's values_list of related objects from many objects' related managers at the same time without having to write a loop ? In other words this query: Hospital.objects.first().treatments.all().values_list('treatment_appointments', flat=True) will return me a list of PKs that will look something like this: <QuerySet [1, 32, 35, 21, 30, 28, 29, 13, 56, 58, 59, 60, 61, 66, 67, 87]> Is it possible to write such query that will return the actual objects instead of those PKs or else is it possible to convert simultaneously all those PKs into objects without for using a for loop?? -
How to serialize mutiple querysets in django rest framework?
I have two models that area related to each other. One represents a project and the other one represents the field/area that the project bnelongs to. I have a view that looks like this: class ProjetosArea(generics.ListAPIView): lookup_field = 'id' serializer_class = ProjetosPreviaSerializer pagination_class = ProjectPagination def get_queryset(self): area_id = self.kwargs['id'] area = AreaConhecimento.objects.get(id=area_id) projetos = Projeto.objects.filter(area_conhecimento=area_id) queryset = [area, projetos] return queryset I want to write a serializer for this view that looks like this: { "area": {---fields of the area---}, "projects": [---The projects that belongs to that area---] } How would write a serializer for this? The queryset is a list with the area and the projects belonging to that area -
Django UpdateView doesn't allow empty field
I have django 3 UpdateView class that is supposed to update Employee model. Employee has null=True field, however when I try to save model with this field empty, I got an error that this field should be filled before saving. How can I make UpdateView save null=True fields empty? Here is UpdateView: class EmployeeUpdate(LoginRequiredMixin, UpdateView): model = Employee success_url = "/" form_class = EmployeeUpdateForm template_name = "employee_update_form.html" login_url = "/login" Here is EmployeeUpdateForm: class EmployeeUpdateForm(forms.ModelForm): class Meta: model = Employee fields = ( "first_name", "last_name", "email", "phone", "salary", "role", ) Here is Employee: class Employee(models.Model): ATENDEE = "atendee" VIEWER = "viewer" ROLE_CHOICES = [ (ATENDEE, "Atendee"), (VIEWER, "Viewer"), ] first_name = models.CharField(("FIRST NAME"), max_length=200, null=False) last_name = models.CharField(("LAST NAME"), max_length=200, null=False) email = models.EmailField(null=False) phone = models.CharField(max_length=20, null=True) salary = models.FloatField(default=0, null=False, validators=[validate_salary]) role = models.CharField(("ROLE"), choices=ROLE_CHOICES, default=VIEWER, max_length=12) Basically, I can't save empty phone field via template. -
The way....what is the shortest way to the correct information
how do programers get access to the correct information without having to ask, like what is the way, Let me give an example, in order to use postgres in Django application, You will have to install something called psycopg2, but in Django-postgres documentation https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/ Theres no such thing as "getting started", theres no mention of psycopg2 at all, u will just have to spend a lot time to google it or watch a video, and if google doesn't have the answer or you just didn't search it correctly, you are stuck, And this is only an example, i have encountered many of these situations, and it's so frustrating, I mean i didn't write postgres and i didn't write django either, i don't know how it works unless someone told me, it doesn't feel like im in control, it's not like a math problem or algorithm where you just have to solve it on your own, but you are in control, The problem is some basic information is just too hard to find in the documentation, the way i do it doesn't seem right, Is everyone else doing it like this? or is there a "smart way" to find it? or … -
Cookies do not work after browser close on mobile
I have Vue frontend app and Django Rest Framework backend on the same domain. The app is working fine and this is the only problem. I use Session Cookie for authentication and CSRF Cookie with HTTPOnly = False from which i read a csrftoken value and add it to the X-CSRFToken header in requests to my API. On mobile devices, after closing browser without closing app window, after opening browser in persisted window cookies do not work (which is ok because i know that they should be deleted when browser is closed) , but after making get requests to the api they are not set. -
AttributeError - 'dict' object has no attribute 'split'
Using django-redis I came across the AttributeError when trying to get the cache. My full traceback can be seen here, the part which shows there're problems with django-redis is here: File "/usr/local/lib/python3.9/site-packages/django_redis/cache.py", line 87, in get value = self._get(key, default, version, client) File "/usr/local/lib/python3.9/site-packages/django_redis/cache.py", line 27, in _decorator return method(self, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django_redis/cache.py", line 94, in _get return self.client.get(key, default=default, version=version, client=client) File "/usr/local/lib/python3.9/site-packages/django_redis/cache.py", line 71, in client self._client = self._client_cls(self._server, self._params, self) File "/usr/local/lib/python3.9/site-packages/django_redis/client/default.py", line 41, in __init__ self._server = self._server.split(",") Exception Type: AttributeError at / Exception Value: 'dict' object has no attribute 'split' My project's config file's part which uses caching is: from environs import Env # environment variables setup env = Env() env.read_env() INSTALLED_APPS = [ ... 'debug_toolbar', 'compressor', ... ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ] CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": env.dj_cache_url("CACHE_URL", default="redis://redis:6379/1"), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # django-debug-toolbar import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + "1" for ip in ips] # celery CELERY_BROKER_URL = env.dj_cache_url("CACHE_URL", default="redis://redis:6379/1") CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' I build my project in Docker, so use an according URL for containerization purposes. In addition, I didn't have AttributeError until … -
asyns requests to api in django view
I have a django application and I need to return a value from one api in one view. For example: a person will enter the page, a request will be made to the api and return a value, I wonder should I make requests asynchronously? if a lot of people visit this page, here's my code: import aiohttp import asynsio asyns def get_rate(): url = 'https://api.ratesapi.io/api/latest?base=USD&symbols=GBP' async with session.get(url) as response: json_response = await response.json() return json_response def test_view(request): usd = asyncio.run(get_rate())['ratest]["USD] return render(request, '???.html', {'usd':usd}) it is correct? or no -
Failing when running celery from docker
I'm trying to get celery to work with Django and docker and the building works well but I celery won't run. Any ideas? Here is are the docker-compose logs -f errors Starting django-celery_redis_1 ... done Starting django-celery_db_1 ... done Starting django-celery_flower_1 ... done Starting django-celery_celery_beat_1 ... done Starting django-celery_celery_worker_1 ... done Starting django-celery_web_1 ... done Attaching to django-celery_db_1, django-celery_redis_1, django-celery_celery_worker_1, django-celery_flower_1, django-celery_celery_beat_1, django-celery_web_1 celery_beat_1 | standard_init_linux.go:219: exec user process caused: exec format error db_1 | 2021-03-28 18:18:15.611 UTC [1] LOG: starting PostgreSQL 12.0 on x86_64-pc-linux-musl, compiled by gcc (Alpine 8.3.0) 8.3.0, 64-bit db_1 | 2021-03-28 18:18:15.613 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-03-28 18:18:15.616 UTC [1] LOG: listening on IPv6 address "::", port 5432 celery_worker_1 | standard_init_linux.go:219: exec user process caused: exec format error db_1 | 2021-03-28 18:18:15.648 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" redis_1 | 1:C 28 Mar 2021 18:18:15.425 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis_1 | 1:C 28 Mar 2021 18:18:15.425 # Redis version=5.0.12, bits=64, commit=00000000, modified=0, pid=1, just started redis_1 | 1:C 28 Mar 2021 18:18:15.425 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf redis_1 | … -
Is it necessary to make the channel room name unique in django channels? I have a function which works fine but have some concerns. HELP NEEDED
Hey guys I have made a small feed system which uses websockets and opens at the moment someone visits the website and login, all the new feeds will be send live and is updated realtime to those people who are subscribed to a particular user. I am using django-channels for this and have a non-unique room_name as of now, so that it is accessible to every user who is logged in and visits the website. but is it a good practice to do have a non unique room_name for such a system? Does it affect the performance or becomes obsolete if large number of users visits the website at the same time? OR Should I create a new table with the current user and a manyTomanyField which contains the subscribed users? if that's the case how do I add all the users to a channel group? This is the code I have which is working fine now, async def connect(self): print('connected') user = self.scope["user"] self.user = user room_name = f'sub-feeds' self.room_name = room_name await self.accept() for now, I am checking a condition which returns True if the user is subscribed to me else it returns False. async def external_feed(self, event): … -
React / Apollo: Displaying Error of GraphQL mutation (useMutation hook)
I am having a hard time trying to figure out why I can't show the error of my mutation. I have implemented error codes in my mutation: if location_lat < 0.1 and location_lon < 0.1: return GraphQLError('E_CF_002') now on the client-side, I call the following mutation, which is called onSubmit of a form and I purposefully trigger the error. const [ createEvent, { data: createData, loading: createLoading, error: createError} ] = useMutation(CREATE_EVENT); The error code is successfully returned as seen in my network tab: {"errors": [{"message": "E_CF_002", "locations": [{"line": However, when I try to show the error in a dialogue box {createError && ( <div> <Dialog open={openDialog} onClose={handleClose}> <h3>Sorry, an error occured while creating the event.</h3> <h3>Plese try again later. {JSON.stringify(createError)} </h3> <DialogActions> <Button onClick={handleClose} color="primary"> Okay </Button> </DialogActions> </Dialog> </div> )} I only see: Sorry, an error occured while creating the event. Plese try again later. {} Can anyone help me understand why my error variable does not hold the message etc.? I first tried directly printing createError.message or createError[0].message or even createError.errors and even createError.errors[0] however later on I saw that even the entire JSON is empty by printing JSON.stringify(createError). I haven't been able to find this specific … -
How to output and save two models that are related in django CreateView
I want to showcase and save my recipes. However I have a Recipe model that has a many to many relationship with a recipelist model. my model: class IngredientList(models.Model): name = models.CharField(max_length=100) image = models.ImageField(default='ing.jpg', blank=True, null=True) recipes = models.ManyToManyField('RecipeList', through='RecipeList') def __str__(self): return self.name class Units(models.Model): name = models.CharField(max_length=20, default='') unit = models.CharField(default=None, max_length=5) def __str__(self): return self.name class RecipeList(models.Model): choice = [ ('Italian', 'It'), ('French', 'Fr'), ('Mexican', 'Mx'), ('Trinidad & Tobado', 'TT'), ] name = models.CharField(max_length=100) ingredients = models.ManyToManyField( 'IngredientList', through='ShoppingList') instructions = models.TextField(max_length=3000) serving_size = models.IntegerField() cuisine_type = models.CharField(max_length=100, choices=choice) image = models.ImageField(default='recipe.jpg', blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('recipe-detail', kwargs={'pk': self.pk}) class RecipeList(models.Model): ingredients = models.ForeignKey(IngredientList, on_delete=models.CASCADE) recipe = models.ForeignKey(RecipeList, on_delete=models.CASCADE) unit = models.ForeignKey( Units, on_delete=models.CASCADE, null=True, blank=True) measurement = models.FloatField(default=1) my view: class RecipeCreateView(CreateView): model = RecipeList fields = ['name', 'instructions', 'cuisine', 'serving_size', 'image'] I want to output on the view a form which has: Recipe.name Recipe.RecipeList.measurement - Recipe.RecipeList.unit - Recipe.RecipeList.ingredients Recipe.instructions ... Instead of outputing Recipe.ingredients and not being able to define the unit or measurements for each, I want to be able to save all the ingredients in one form. But i am very weak with databasing, and new to … -
My django site stopped working after a crash and the errors make no sense
I have a large django 3.1 project that was working as of my last git push last Sunday. After that push, I started working on some bash deployment scripts and had a system crash (Ubuntu) related to testing these scripts (bash is not my forte!). I rebooted the machine, and continued working. I started running some tests on the django code and low and behold the working code in my django project is broken in a very weird way. Weirdness #1 - imports not working In one of my save_model functions in the admin.py of one of my apps, I have this line, which on Sunday was working. obj2.computed_sha256 = image_processing_utils.compute_sha256(f) I got a django error message that image_processing_utils was not defined. However, there is an import statement at the top of the admin file from image_processing import image_processing_utils. I copied the import statement to the line above the obj2.computed_sha256 = image_processing_utils.compute_sha256(f) and the save_model function worked correctly. Weirdness #2 - database values incorrect I ran another admin test where a post_delete signal is called. I have these lines: @receiver(post_delete, sender=Face) def auto_delete_face_metadata(sender, instance, **kwargs): # delete the Face metadata when the Face object is deleted doc_id = instance.document.document_id doc_metadata … -
'ordering' refers to the nonexistent field, related field, or lookup 'order'
I am getting this error and couldn't resolve it since 2 hours. If anyone could help. This is my models.py models.py Error : enter image description here -
Handling a null header value
I'm passing a header value to a list endpoint to only get objects after a certain date, this works all fine until the front end pass null as the value. My code for this looks like this; updated = self.request.headers.get("Updated", None) type(updated) if updated is None or updated is "null": .... else: .... If the header value passed is Updated: null this crashes, I've tried comparing to both None and the text null but I still get the error; django.core.exceptions.ValidationError: ['“null” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] As it's falling into the else category, type(updated) prints out null in the terminal but I can't find anywhere where to compare updated to a null value, according to what I've found this should be covered by None. I could fix this on my FE but I feel like this would leave the BE open to a 500 error for no reason. -
Adding payment method and escrow to a site in Python [closed]
How do I add a payment method on a site designed in python django -
Django python problem finding h1 element and title
I am reading the book "TDD in practice" and I follow it, however, when I want to check functional tests, I get this error: ====================================================================== ERROR: test_title (__main__.NewvisitorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\superlists\functional_tests.py", line 19, in test_title header_text = self.browser.find_element_by_tag_name('h1').text File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 530, in find_e lement_by_tag_name return self.find_element(by=By.TAG_NAME, value=name) File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 976, in find_e lement return self.execute(Command.FIND_ELEMENT, { File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 321, in execut e self.error_handler.check_response(response) File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- packages\selenium\webdriver\remote\errorhandler.py", line 242, in che ck_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"h1"} (Session info: chrome=89.0.4389.90) ---------------------------------------------------------------------- Ran 2 tests in 11.605s FAILED (errors=1) I understand that the h1 tag is a problem, but I don't understand why it can't find it. functional_tests.py from selenium import webdriver from selenium.webdriver.common.keys import Keys import unittest class NewvisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Chrome() self.browser.implicitly_wait(4) def tearDown(self): self.browser.quit() def test_can_start_a_list_retrieve_it_later(self): self.browser.get('http://localhost:8000') def test_title(self): self.assertIn('', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('Listy', header_text) inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual(inputbox.get_attribute('placeholder'),'Wpisz rzecz do zrobienia') inputbox.send_keys('Kupić pawie pióra') inputbox.send_keys(Keys.ENTER) table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertTrue(any(row.text == '1: Kupić pawie pióra' for row in rows)) self.fail('Zakończenie testu!') if __name__ == "__main__": unittest.main() home.html <html> <head> <meta charset="UTF-8"> <title>Listy … -
AWS S3 Usage Limit : How to reduce usage?
I have nearly reached my AWS S3 usage limit for the month, after having started it just a couple of weeks ago, and I'm trying to understand why. I've never used AWS before, and I'm a newb in general. I literally have 3 jpegs in storage, nothing else. Is usage solely determined by hrs? I read that hrs are instances where the storage is made available. Right now I have the Django project hosted on Heroku with media on AWS. I am very much still in dev mode, and only need AWS when testing project on Heroku, but most of the time I'm in local env. Given that, I am confused how my usage limit could be nearly reached within a couple of weeks. Any guidance is appreciated.