Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels | Can you do a SQL Query in a Channels Consumer?
i am making a Tool which can show me the Temperature of an Connected thermostat via GPIO. I want to log the temperature by sending the current temperature via an SQL Query to the Django SQLITE DB using Models. It also logs the current time when the temperature was recorded so i maybe later can do graphs or stuff like that. When i do it nothing happens. I dont get an exception in the Webserver Shell or on the webpage itself. The SQL Query im sending simply dosent work. Note that the temperature fuction works i tried it out by only showing the current temperature on the website. Models.py from django.db import models class TempLog(models.Model): temp = models.CharField(max_length=10) time = models.DateTimeField(auto_now_add=True, auto_now=False, blank=False) consumers.py Im using the fuction temp_db to create the SQL Query. The Temperature Data is being saved in the Variable ctemp. And then the function is called in the loop within the consumer. import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from .tempclient import getTempTCP from tcore.models import TempLog async def temp_db(tcptemp): tempdb = TempLog() TempLog.objects.create(temp=tcptemp) class TempConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type" : "websocket.accept" }) i = 0 … -
how to prevent my users from going backward?
I am making an online test application in Django.The flow of the control is: test-> display marks-> Profile. all these three components are working perfectly but the problem is that users after giving the test can press the back button of the browser and go back to the test and change their responses. How can I prevent users from going back to the test? note: I cannot make any custom session token because there are multiple tests so if I make a session token the user will not be able to give any other test. -
Django Multiselectfield works locally but not on server
I've installed multiselectfield on my machine and it works well. I can choose multiple items thanks to multiple checkboxes in admin: Then I had to copy/paste all the files of the project to my VPS using Filezilla. So I have the exact same code and the exact same files locally and remotely. The site works well remotely (the VPS django admin page too). However on the server's django admin page, the multiselectfield widget shows a simple text field instead of an actual list of checkboxes, plus it says Enter a list of values. when I try to validate the form. So, how is it, that with the same code at two different places, the multiselectfield acts differently and how to I fix this ? -
Trying to Run 2 Celery Daemons and Queues with Django and Redis and Apache wsgi
I have two Django 3.0 sites (test and production) running under apache2 2.4.9, mod_wsgi, redis 4.0.9 and celery 4.3.0 as a daemon, and flower 0.9.7 on the same server. The django code base for each site is identical, just different databases. Each site runs in its own virtual environment, but using identical requirements.txt files and python version. Each site has its own wsgi.py file, celery.py file, apache.conf file, /etc/conf.d/celery settings file, /etc/systemd/system/celery.service file, and settings.py file with different settings for the celery daemons. There is only one redis server running, and both daemons talk to that server. If I run each site alone (stop the other site's celery daemon), then the celery tasks all work as expected. If I enable both daemons, then the celery tasks fail with very strange error messages - e.g. in the celery task log file I get "matching query does not exist" for the same code which works when each daemon runs separately, and the same code on my dev machine. I thought the solution would be to make two separate celery queues for each site, which is not working. In the settings.py for each for the 'test' environment I have CELERY_TEST_BROKER_URL = 'redis://:' + … -
Django model design for Stocks
I currently have two models: Stock and Transaction. The stock models values are defined by the total values of the Transaction. E.g. when I buy or sell shares from a stock (Transaction) I want to update my Stock model. The reason for the Stock model is so I don't have to calculate all transactions everytime a Stock instance is viewed. I'm just wondering if this a good way of solving this problem? -
ValueError: Cannot assign "1": "Topic.board" must be a "Board" instance
I know there are a bunch of questions addressing this issue, but I haven't solved it out yet. please any help i tried many solutions but didn't work models.py class Board(models.Model): name = models.CharField(max_length=50,unique=True) description = models.CharField(max_length=150) def __str__(self): return self.name class Topic(models.Model): subject = models.CharField(max_length=255) board = models.ForeignKey(Board,related_name='topics',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='topics',on_delete=models.CASCADE) created_dt = models.DateTimeField(auto_now_add=True) class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_dt = models.DateTimeField(auto_now_add=True) view.py def new_topic(request,board_id): board = get_object_or_404(Board,pk=board_id) if request.method == 'POST': subject = request.POST['subject'] message = request.POST['message'] user = User.objects.first() topic = Topic.objects.create( subject=subject, board=board_id, created_by=user ) post = Post.objects.create( message=message, topic=topic, created_by=user ) new_topic.html {% extends 'base.html' %} {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} <form method="post"> {% csrf_token %} <div class="form-group"> <label for="id_subject">Subject</label> <input type="text" class="form-control" id="id_subject" name="subject"> </div> <div class="form-group"> <label for="id_message">Message</label> <textarea class="form-control" id="id_message" name="message" rows="5"></textarea> </div> <button type="submit" class="btn btn-success">Add</button> </form> {% endblock %} I'm fairly new to Django. How would I go about resolving that? -
Django Progress Bar (with celery not working)
So, I'm making this twitter tweets analyzer for my portfolio website, and I'd figure why not make a progress bar since it takes a while to load and parse the tweets (around 200). How hard could it be? My google search led me to this video using Celery + redis + celery-progress. Okay watched the video then i read the github of celery-progress + two(1, 2) articles regarding the process. seems straightforward. so i set up `celery.py` import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_proj.settings') app = Celery('my_proj') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') and set up the `settings.py` also INSTALLED_APPS = [ ....... 'django_celery_results', # Celery apps 'celery', 'celery_progress' ] . . . CELERY_BROKER_URL = 'redis url' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'redis url' also set up the `init.py` # This will make sure the app is always imported … -
Trying to create a new object based on TypeError: Object of type ItemSerializer is not JSON serializable -
Im trying to get my data from the api and create a new item with it. I am getting an error:] File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type Item is not JSON serializable model # Create your models here. class Item(models.Model): """Make scan class""" # define fields # https://docs.djangoproject.com/en/3.0/ref/models/fields/ name = models.CharField(max_length=100, unique=True) recycleable = models.BooleanField() description = models.CharField(max_length=100) owner = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) barcode = models.CharField(max_length=100, unique=True) def __str__(self): # This must return a string return f"The item named '{self.name}' is {self.description}. It is {self.recycleable} that it is recycleable." def as_dict(self): """Returns dictionary version of Item models and stuff""" return { 'id': self.id, 'name': self.name, 'recycleable': self.recycleable, 'description': self.description, 'owner': self.owner, 'barcode': self.barcode, } views class ScanApiDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes=(IsAuthenticated,) def get(self, request, slug): """Show request""" load_dotenv(find_dotenv()) api_key = os.environ.get("API_KEY") # Locate the scan to show response = requests.get(f"https://api.barcodelookup.com/v2/products?barcode={slug}&formatted=y&key={api_key}") if response: print(response, "my response") item = response.json() for i in range(len(item)): descrip = item['products'][i]['description'] name = item['products'][i]['product_name'] barcode = item['products'][i]['barcode_number'] recycleable = True x = re.search("^Material", descrip) owner = request.user.id data = Item(id, name, recycleable, descrip, owner, barcode) print(type(data), "the data") json_data = json.dumps(data) print(json_data) # # Serialize/create item item = … -
Heroku website shows Server Error (500) when opened
every time I try to open my website on heroku, it shows the error message Server Error (500). All my static files are correctly setup (I know this because I ran python3 manage.py collectstatic). # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And my debug is set to false -
Python variable from django in javascript?
everyone. I am starting to learn javascript and I am stuck on how to send python variables in Django to a javascript file. my views.py file partially looks like this: def mailbox(request, mailbox): # Filter emails returned based on mailbox if mailbox == "inbox": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=False ) elif mailbox == "sent": emails = Email.objects.filter( user=request.user, sender=request.user ) elif mailbox == "archive": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=True ) else: return JsonResponse({"error": "Invalid mailbox."}, status=400) # Return emails in reverse chronologial order emails = emails.order_by("-timestamp").all() return JsonResponse({'allemails' : [email.serialize() for email in emails]}, safe=False) And here is the inbox.js file I want to send the variable allemails: function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; // let x = "Something will be here" var y = {{ allemails }}; //var y = {{allemails|escapejs}}; I also tried this one. //var y = '{{ allemails }}'; also this one but it defines y literally as a string {{ allemails }} // Show the mailbox name// if (mailbox === 'sent') { document.querySelector('#other-view').innerHTML = `<table><tr><td></td></tr><tr><td><h1> ${y}</h1> </td></tr></table>`; } } And a portion of my models.py is here: … -
is it possible to write if conditions inside models and if yes how?
this is my models and i am trying to assign category automatically if the user gets a marks greater than 10 he will get "legendary" category else "gold" category class Intrest(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="uuser") marks=models.IntegerField(default=0) choices = ( ('Legendary', "Legendary"), ('Gold', "Gold"), ) category=models.CharField(max_length=10,choices=choices,blank=True,null=True) def value(self): if self.marks==10: self.category="Legendary" else: self.category="gold" def __str__(self): return f"{self.user}" I have made a value function but its not working can anyone tell me how can I achieve this? -
TemplateDoesNotExist at /accounts/login/ on Heroku
so my Django app works well on my dev local server using py manage.py runserver, but in production, on heroku, when I try to log in using the django's default login system, it returns me an error TemplateDoesNotExist at /accounts/login/. I have searched a while and I came out with some solutions as creating a TEMPLATES variable so the prodution server knows where to find the templates, but I don't have any folder with the django.auth in my project. In my source folder I have one templates folder with all the base template but that´s it, no Registration folder anywhere. How does this works on my local machine but not on heroku? INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', #authentication 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'perfil', 'posts' ] Here is my urls.py file: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from .views import home_view urlpatterns = [ path('profiles/', include('perfil.urls', namespace='perfil')), path('timeline/', include('posts.urls', namespace='posts')), path('', home_view, name='home'), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And here the form where I login: <form action="{% url 'login' %}" method="POST" name="login_form" class="ui form"> {% csrf_token %} <div class="field"> <input name="username" … -
Share auth between django and react
I have a website with the default django authentication system. The whole website is static and I would like to have a couple pages dynamic using React app as frontend. I expect these dynamic pages to make a some http requests to the django server. My understanding is that I can use axios on the frontend and deal with the requests on the backend with Django Rest Framework. I think the current authentication system works fine, how can I make axios requests to DRF using the existing user's session ? -
When running the Django Server getting Bad Request or Path Error
I am creating a Django Project under which I have created an app named as products. I have put some piece of code in the models.py file of this products app i.e. from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=120) image = models.ImageField(upload_to='products', default='bob.png') price = models.FloatField(help_text='in US Dollars $') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name}" After that I have registered the class in the admin.py file of the products app. The code for that is: from django.contrib import admin from .models import Product # Register your models here. admin.site.register(Product) After that I fired the commands: python manage.py makemigrations python manage.py migrate python manage.py runserver After running this last command I am getting the error mentioned in error1. After that I have changed the DEBUG mode to False but after that I am getting error mentioned in error2. I have even changed the ALLOWED_HOSTS field value in the settings.py file to ['*'] or ['127.0.0.1'] but still I am getting the Bad Request error. Please help me in resolving this issue. Thanks -
How to allow users to create users using Django
I'm Working on a small CRM Project, using Django / Rest Framework. I would like to create sub-users options for example a user can create some sub-accounts for the employes for example I don't know what should I do, or from where to start to make it -
Plz can someone help me
I am trying to set a reminder task within my django project using celery but nothing is working I watched multiple videos and searched over github Can someone provide me with details -I downloaded celery and connect redis -create a task reminder that send email But what I want is to send the email before the closed day of the task -
Celery beat is stuck at "writing entries...". Celery worker is working fine
I am starting my celery beat (Django Celery) with the below command but it's not going forward after "writing entries". But the worker is working fine, running both in separate terminal windows. $ celery -A myproject worker -l debug I created another sample Django app and in that beat is working fine. OS: Ubuntu 20.04 -
django-mptt get full tree filtered
New to django and stucked at getting full tree with filter from django-mptt. Could't find anything related to what I want to achive. I created context_proccessor.py and place this code to excess it on every page for my multilevel menu. from .models import TopMenu def get_top_menu(request): top_menu = TopMenu.objects.filter(active=True).order_by('tree_id') return { 'top_menu': top_menu } And in template I use this: <ul> {% recursetree top_menu %} <li> <a href="{{ node.slug }}/">{{ node.title }}</a> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> The result is that I get only root level and child. Not the entire tree. I get the entire tree only if I request TopMenu.objects.all(). But that is not what I want. I want filtered full tree. How to achive this? -
One project my obj.save() returning object how i did not used commit=Fa;se
Below code you will see that uf.save() statement returning the object how ? i did not use uf.save(commit=False) def wash(request): if request.method == 'POST': uf = Userform(request.POST) wf = Profileform(request.POST,request.FILES) if uf.is_valid() and wf.is_valid(): user = uf.save() print(user) wf.instance.user = user wf.save() return HttpResponse("suscess fully crated ") return render(request, 'webpage/washer.html', {'wf': wf, 'uf': uf}) -
I can't get Django to INNER JOIN properly :(
Despite having looked everywhere for similar issues I still cannot make the query working using INNER JOIN with the Django ORM... Sorry if this might sound stupid, but this is my first time with Django on a project and especially the ORM. I have an Articles table with a Users table (named Fellows in my case), the Articles table has it's foreign key on author and references the user_id in Fellows table. class Fellow(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # ID user_id = models.PositiveBigIntegerField(db_column='User_ID', unique=True) # Global User ID. nickname = models.CharField(db_column='Name', max_length=64, db_collation='utf8mb4_general_ci') # Display Name user_password = models.CharField(db_column='User_Password', max_length=256, blank=True, null=True) # Passwd gold = models.IntegerField(db_column='Gold') # Credits faction = models.ForeignKey('Faction', models.RESTRICT, db_column='Faction', default=1) # ID Faction class Meta: managed = False db_table = 'Fellows' def __str__(self): return self.nickname # Test. class Article(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # ID author = models.ForeignKey('Fellow', models.CASCADE, db_column='ID_User', default=1) # Global User ID title = models.CharField(db_column='Title', max_length=32) # Title content = models.TextField(db_column='Content') # Content posted = models.DateTimeField(db_column='Posted') # Date Posted source = models.CharField(db_column='Source', max_length=64, blank=True, null=True) # Source picture url of the article. class Meta: db_table = 'Articles' I tried to get the display name of the related author that posted the article … -
How to check if user exists in database given a name or a phone number in DRF
I need to check if a user exists in the database given their input: either their name or phone number. If the user exists, the user is used to take their order. If the user inputs both their name and phone and they don't exist in the database, I need to create the user. How do I do this? This is the serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' extra_kwargs = { 'email': {'required': True}, 'phone': {'required': True} } def create(self, validated_data): user= User.objects.create( email=validated_data['email'], phone=validated_data['phone'] ) user.save() return user class OrderSerializer(serializers.ModelSerializer): food= FoodSerializer(many=True) class Meta: model = Order fields = ('date','food','phone','email') def validate(self, data): email = data.get('email') phone= data.get('phone') if not email and not phone: raise serializers.ValidationError("Email or phone required") return data def checkuser(self, cliente, data): if data['email'] or data['phone'] in user: return user elif data['email'] or data['phone'] not in user: pass def create(self, validated_data): order = Order.objects.create( email=validated_data['email'], phone=validated_data['phone'], date= validated_data['date'], food= validated_data['food'], quantity= validated_data['quantity'], ) order.save() return order -
Django Permissions with CustomUser
I'm trying to implement class Based views with permissions and they do not seem to connect, although I believe I strictly followed Django User's guide. First: set up of a Custom User model, based on Proxies, in accounts.models class CustomUser(AbstractUser): some_fields... Then, I created a Manager: class EmployeeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(status_type=CustomUser.StatusType.EMPLOYEE) Followed by the type of profile: class Employee(CustomUser): objects = EmployeeManager() class Meta: proxy = True permissions = [("communities.view_region", "Can view region")] Where I set a permission, make the migrations and migrate. After, I create the view: import communities.models as comms class RegionsListView(ListView): model = comms.Region Then, configuration of the url and its view: rom django.urls import path, include import communities.views as views from django.contrib.auth.decorators import permission_required app_name = 'communities' urlpatterns = [ path("regions/list/", permission_required("communities.view_region")(views.RegionsListView.as_view())) Then I log in as an employee and I get an error 403 when calling this url. What did I miss ? Remarks: using permission_required = 'communities.view_region' in the view.py file produces the same result. when logging as a superuser, I get of course the right page. -
Django, dynamically grabbing javascript item
I've got a set up where I have a table generated with HTML, something like this: <tbody> {% for key, value in appointments.appointments.items %} <tr onclick="" class = "green-background appt-row"> <td class = "info-row form-select {{key}}">{{ value.person }}</td> <td class = "info-row {{key}}">{{ value.time }}</td> <td class = "info-row {{key}}">{{ value.number }}</td> <td class = "info-row {{key}}">N</td> <td class = "info-row {{key}}"><button onclick="posted('{{key}}',this)" id="select-button" class="button-decoration-new btn mb-3 form-button">Select</button></td> </tr> </div> {% endfor %} </tbody> and my posted function looks as follows: <script> function posted(key){ console.log("KEY IS", key) test = `appointments.appointments.${key}` first = "{{" test_two = first.concat(test).concat("}}") console.log("test_two is", test_two) console.log(test_two) } </script> I basically am associating each row with a key of a dictionary, and then am trying to print out the dictionary value associated with that key in the javascript. This works if I do, console.log("{{appointments.appointments.106}}") for instance, but, for some reason, when I dynamically generate the string using string interpolation (i.e. `test = `appointments.appointments.${key}` and then apply {{ and }} to the left and right of the string this doesn't work. How can I fix this/what am I doing wrong here? Thanks -
Django - Unable to render data after submitting a form
I'm a begginner in Django. To start I wanted to implement a form and display basic data just below the from fields after submitting the form. Here is my form: class UserIdForm(forms.Form): user1 = forms.CharField(label='User 1 Id', max_length=100) user2 = forms.CharField(label='User 2 Id', max_length=100) Here is the url conf: urlpatterns = [path('', views.check_rights),] Here is my view: def check_rights(request): form = UserIdForm() template_name = 'user_rights/user_form.html' #user1 = form.cleaned_data['user1'] #user2 = form.cleaned_data['user1'] user1 = 'toto' ctx = {'form': form,'user1':user1, 'user2':'titi'} return render(request, template_name, ctx) Yes 2 lines are commented. For the moment I would like to display hard coded values (here 'toto') if I am able to submit the form (which works fine) Finally here is my template: <body> <h1>Compare user rights</h1> <br> <form action="" method="get" type="text"> {{ form }} <input type="submit" value="Submit"> </form> {% if user1 %} <p> User 1 rights are {{ user1 }} </p> {% endif %} Once the form is submitted I'am able to see [...]/user_rights/?user1=user1r&user2=user2r in the url bar from the browser. I don't understand why when I submit the form I am not able to see :"User 1 rights are toto" (My goal in the long run is to query a DB and show the … -
Can't display an image in react from backend django
I want to display an image which I got the src from in the database linked to django on localhost 8000, in react (localhost 3000). here is my view: class NextQuestion(APIView): permission_classes = [IsAuthenticated] lookup_url_kwarg = 'old_questions' def post(self, request, format=None): old_questions = request.data.get(self.lookup_url_kwarg) if len(old_questions): old_questions_q = [Q(id=x) for x in old_questions] questions_valides = Question.objects.exclude(reduce(operator.or_, old_questions_q)) if len(questions_valides) == 0 : return Response("Il n'y a plus de questions disponibles!") else: questions_valides = Question.objects.all() index = randint(0, len(questions_valides) -1) new_question = QuestionSerializer(questions_valides[index]).data return Response(new_question) My serializer: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' My urls: from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ###### path('quiz/', include('quiz.urls')), ] urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And in my settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' In my .js: <Fade in={!toggle} {...(!toggle ? { timeout: 2000 } : {})}> <Paper elevation={0} className={classes.paper}> <img className={classes.image} src={image} alt="La réponse." /> </Paper> </Fade > My variable image has this value: /media/images/quiz/animal-2029280_1280.png It should match the path corresponding to the image, yet it doesn't load. …