Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
X.MultipleObjectsReturned: get() returned more than one X -- it returned 2
I have a model, Chapter, linked to the Book model through a ForeignKey. One of it's fields, the integer field, number, is "slugified" to make the slug field, chapter_slug. The problem is my DetailView. When I call it the error "raise self.model.MultipleObjectsReturned(books.models.Chapter.MultipleObjectsReturned: get() returned more than one Chapter -- it returned 2!" That happens when I have more than one chapter 1, in this case, in two different books. class Chapter(models.Model): manga = models.ForeignKey(Manga, on_delete=models.PROTECT) number = models.IntegerField(default=1) name = models.CharField(max_length=200, blank=True) chapter_slug = models.SlugField(null=True) ... def get_absolute_url(self): return reverse('chapter', kwargs={'manga_slug': self.manga.manga_slug, 'chapter_slug': self.chapter_slug}) def save(self, *args, **kwargs): if not self.chapter_slug: self.chapter_slug = slugify(self.number) return super().save(*args, **kwargs) ... path('book/<slug:book_slug>/chapter/<slug:chapter_slug>/', views.ChapterView.as_view(), name='chapter'), class ChapterView(DetailView): model = Chapter template_name = books/chapter.html' context_object_name = 'chapter' slug_field = 'chapter_slug' slug_url_kwarg = 'chapter_slug' ... Even tough I know what the problem is I can't solve it. I've tried changing my DetailView but I got the error "NameError: name 'request' is not defined" and I'm not sure if it would work even without that error. class ChapterView(DetailView): model = Chapter.objects.get(id=request.get('chapter_id')) template_name = 'mangas/chapter.html' context_object_name = 'chapter' slug_field = 'chapter_slug' slug_url_kwarg = 'chapter_slug' ... -
Django not generating prefixe or form ID in formset
I have a formset for creating criteria which generates the fields properly with an ID like this: <textarea name="form-0-criteriaDescription" cols="40" rows="10" class="textarea form-control" id="id_form-0-criteriaDescription"></textarea> However in a new formset these identifiers are not being generated properly, and each form field has the same identifier. For example, the comment always has the ID id_comment rather than a specific identifier for each form. <textarea name="comment" cols="40" rows="10" class="textarea form-control" required="" id="id_comment"></textarea> This is causing the POST data to be incorrectly formatted and so the form cannot be validated or saved or anything. The view code which generates the forms is as follows, I'm more than happy to add more details if need be, and thank you in advance for any pointers. formset = FeedbackFormset(queryset=Feedback.objects.none()) # Create a list of dictionaries containing the criteria description and the form instance feedbackForms = [] for criterion in criteria: feedbackForm = FeedbackForm() feedbackForm.fields['criteriaLevelID'].queryset = criterion.criterialevel_set.all() #limits choices for criteria Level feedbackForms.append({'form': feedbackForm, 'description': criterion.criteriaDescription}) context = {'submission': submission, 'feedbackForms': feedbackForms, # 'prefixes': [form.prefix for form in formset.forms], } return render(request, 'markingApp/createFeedback.html', context) -
Can't run selenium driver on ec2
I collect reviews through a parser that uses chromedriver , I run parsing in a celery task on the server, i faced the following error (The process started from chrome location /home/ubuntu/.../chromedriver is no longer running, so ChromeDriver is assuming that Chrome has crashed.) this is the path returned by the ChromeDriverManager. Do I need to somehow install and configure the Google browser on the server? Here my chrome options: chrome_options = Options() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--headless") # Adding argument to disable the AutomationControlled flag chrome_options.add_argument("--remote-debugging-port=9222") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_argument("start-maximized") # Exclude the collection of enable-automation switches chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_argument("window-size=1280,800") # Turn-off userAutomationExtension chrome_options.add_experimental_option("useAutomationExtension", False) path = ChromeDriverManager().install() chrome_options.binary_location = path #"/home/ubuntu/chromedriver" service = Service(path) driver = webdriver.Chrome(service=service, options=chrome_options) -
APACHE SOLR version 7.4 integrating with django haystack
I m trying to integrate apache solr into my django application to use as the search functionality. I have generated the schema.xml file and rebuild the index. When i try to search for a term in my application, I m getting the following error: app_label, model_name = raw_result[DJANGO_CT].split(".") AttributeError: 'list' object has no attribute 'split' Please help on how to fix this thank you! I am using apache solr version 7.4. I m using windows! -
create consistant department name and code
I have a department model in django: from django.db import models class Departement(models.Model): name = models.CharField(max_length=128, db_index=True) code = models.CharField(max_length=3, db_index=True) I'd like to create a fixture with factory_boy with a consistent department name and code. Faker has a department provider which returns a tuple with the code and the department (ex for french: https://faker.readthedocs.io/en/master/locales/fr_FR.html#faker.providers.address.fr_FR.Provider.department) I have created a DepartmentFixture class but fail to understand how to use an instance of faker to call the faker.derpartments() method then populate the code/name fields accordingly. -
AttributeError: 'Settings' object has no attribute 'decode'
Trying to migrate using on django and I have read the documentation and still getting an attribute error which I don't know how to debug _init_.py def __getattr__(self, name ,): """Return the value of a setting and cache it in self.__dict__.""" if (_wrapped := self._wrapped) is empty: self._setup(name) _wrapped = self._wrapped val = getattr(_wrapped, name ,) -
How to fix an error with opening the API in the browser?
I am developing a project for react + django, using docker, docker launches a backend application at address 0.0.0.0:8000, 3 days ago everything worked fine, but today there was such an error. At the same time, requests through postman pass successfully. File entrypoint.sh File docker-compose Logs docker I tried to give a different address, switch to the last commit, change ports in the hosts file. The container itself starts successfully, but there is no access from outside. I suspect that the matter is that the host is blocked, but I do not know how to check it. -
Django: Trying to create an average from a "ratings" field from two different models
Forgive me, this may be long: Using the Python shell, I have figured out how to accumulate an average from the ratings field from two different models: Review, the initial review posted by a user; and AddedReview, additional reviews from other users posted to the initial Review. (The code below is targeting a specific Review: (id=13)): >>> from django.db.models import Sum, Count >>> >>> added_ratings_sum = Review.objects.filter(id=13).aggregate(Sum('addedreview__rating')) >>> >>> added_ratings_sum {'addedreview__rating__sum': 27} >>> >>> for i in added_ratings_sum.values(): ... a_r_sum = i ... print(a_r_sum) ... 27 >>> >>> type(a_r_sum) <class 'int'> >>> >>> orig_ratings_sum = Review.objects.filter(id=13).aggregate(Sum(‘rating')) >>> orig_ratings_sum {'rating__sum': 9} >>> >>> for j in orig_ratings_sum.values(): ... r_sum = j ... print(r_sum) ... 9 >>> >>> total_sum = a_r_sum + r_sum >>> total_sum 36 >>> >>> ratings_count = review1.addedreview_set.count() + 1 >>> ratings_count 4 >>> >>> ratings_avg = total_sum / ratings_count >>> ratings_avg 9.0 The results are returned perfectly. However, when I add this code (reconfigured for all of the Reviews) in my home() view: def home(request, pk): ... added_ratings_sum = Review.objects.get(id=pk).aggregate(Sum('addedreview__rating')) for i in added_ratings_sum.values(): a_r_sum = i orig_ratings_sum = Review.objects.get(id=pk).aggregate(Sum('rating')) for j in orig_ratings_sum.values(): r_sum = j total_sum = a_r_sum + r_sum ratings_count = Review.objects.get(id=pk).addedreview_set.count() + 1 ratings_avg … -
Using a non-editable field in a formset
I have a model class Application(models.Model): ... few fields ... pub_date = models.DateTimeField(.., auto_now_add=True, ..) For create few objects i'm using FormSet class ApplicationForm(forms.ModelForm): ... ApplicationFormSet = modelformsetfactory(..) Field "pub_date" add automatically in new objects. Also i'm using FormSet for update my forms. This is showed in the view: def applications_list(request): applications = Application.objects.all() if request.method == 'POST': formset = ApplicationFormSet(request.POST, queryset=applications) if formset.is_valid(): formset.save() formset = ApplicationFormSet(queryset=applications) return render(request, 'applications/applications_list.html', {'formset': formset}) In template i use table with: {% for form in formset.forms %} and {% for field in form.visible_fields %} for show all objects and update it. But i can't bring to content "pub_date" because it's field not editable and cannot be added to form (formset) How i can add "pub_date" (non-editable) in one line with other fields of forms? -
Django/Python: How to use the If-Statement
I would like to, If a file is selected, that a image is shown. I wrote the {% if file.selected %} myself, because I couldn't find anything online. I know this ptompt is wrong, but just to get an Idea, If someone selects a file, it should show the image, else the text. I just need the right prompt. <div class="mystyle"> <div class="titleit"> <input contenteditable="true" placeholder="An Interesting Titel... " type="text" name="title" maxlength="100" required id="id_title"> </div> <br><br><br> <div class="options"> {% if file.selected %} <img class="preview" src="/media/fitmedia/california.jpg"> {% else %} <p class="p-text">Upload a Picture or Video </p> <input class="fileit" type="file" name="file" required id="id_file"> {% endif %} </div> </div> -
Django Crispy Forms cancel button
I have a Django Crispy Form that I want to add a cancel button to. Unlike the answers here and here, however, the user can get to the form via multiple pages, so I need to send them back to the page they came from if they cancel, not send them to a static page. How can I accomplish this? -
find deleted records
I have a Django application that processes a weekly CSV dump of 1.5 years of data and stores it in a PostgreSQL database. The data contains a primary key column and an uploadDate column, among other columns. If a record is deleted from the source, the new dump won't have this record, but the record will exist in my database. I want to use pandas or sql to sort the data by uploadDate in ascending order and compare the records from the older file with the next consecutive one. If there are records in the old file that do not exist in the next one, it means those records were deleted. How can I solve this using sql or python pandas? enter image description here import pandas as pd def find_deleted_records(df: pd.DataFrame, primary_key: str, upload_date: str) -> pd.DataFrame: """ Find records that were deleted from a database table based on a weekly CSV dump. Args: df (pd.DataFrame): The dataframe containing the table data. primary_key (str): The name of the primary key column. upload_date (str): The name of the upload date column. Returns: pd.DataFrame: A dataframe containing the deleted records. """ # Sort the data by Peildatum in ascending order data … -
Django with django-tenants not copying all static folders to AWS S3 bucket
I have a django-tenants site that I am attempting to prepare for moving to a live server. I want to use an AWS S3 bucket for static files. I have been able to get a few folders the local static directory to copy to the S3 bucket but many are not copied when I run "python manage.py collectstatic." I have the following folders in the static directory: admin, bootstrap, CACHE, constrainedfilefield, core_images, css, django_ckeditor_5, django_extensions, django_tinymce, tagulous, tinymce. However only the following folders are getting copied to the S3 bucket: admin, constrainedfilefield, django_ckeditor_5, django_extensions, django_tinymce, tagulous settings.py file: """ Django settings for config project. Generated by 'django-admin startproject' using Django 3.1.14. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os.path #from environs import Env from django.conf.locale.en import formats as en_formats EMPLOYEE_PERMISSIONS_FILE = 'config.employee_permissions' MANAGER_PERMISSIONS_FILE = 'config.manager_permissions' ADMINISTRATOR_PERMISSIONS_FILE = 'config.administrator_permissions' from importlib import import_module employee_permissions = import_module(EMPLOYEE_PERMISSIONS_FILE).EMPLOYEE_PERMISSIONS manager_permissions = import_module(MANAGER_PERMISSIONS_FILE).MANAGER_PERMISSIONS administrator_permissions = import_module(ADMINISTRATOR_PERMISSIONS_FILE).ADMINISTRATOR_PERMISSIONS # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret … -
Stop addresses been recorded if already exists for customer
I wanted to make my code record an address for a customer when making an order, I wanted this separate from shipping addresses. At the moment I'm struggling to figure out how to stop it continuously recorded the same address if the same customer places and order with the same address. So to put it simply, if address already exists for customer do not add, if it does not exist add it. This is the view that records the address def process_order(request): transaction_id = datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, order_status='P') else: customer, order = guestOrder(request, data) total = float(data['form']['total']) order.transaction_id = transaction_id if total == float(order.get_cart_total): order.order_status = 'C' order.save() if order.shipping == True: ShippingAddress.objects.create( customer=customer, order=order, house=data['shipping']['house'], street=data['shipping']['street'], city=data['shipping']['city'], postcode=data['shipping']['postcode'], ) Address.objects.create( customer=customer, house=data['shipping']['house'], street=data['shipping']['street'], city=data['shipping']['city'], postcode=data['shipping']['postcode'], ) MOdels class Customer(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True,) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) def __str__(self): return '%s %s' % (self.first_name, self.last_name) class Address(models.Model): house = models.CharField(max_length=255) street = models.CharField(max_length=255) city = models.CharField(max_length=255) postcode = models.CharField(max_length=25) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) def __str__(self): return 'Username: %s - Name: %s %s' % ( self.customer.user ,self.customer.first_name, self.customer.last_name) screenshot of issue -
PWA with React & Django
I'm relatively new to web development and I have a PWA question. I have a React project and the PWA can be installed normally if I deploy the frontend project, but I generate a frontend build and leave the folder inside a Django directory, where it forwards requests to index.html. The problem is that after deploying, even though the service-worker and manifest.json are recognized, it is not possible to install the PWA Can anyone explain why? I would like to be able to install the PWA by just deploying the django project with the react build inside it and not leaving the front and backend in different deploys -
Encrypting python scripts in web application for Django and flask
I am working on developing two applications for a client using Flask and Django frameworks. However, I am seeking guidance on encrypting my Python script to ensure the client cannot access my code. Furthermore, I am planning to deploy the applications using Docker Compose with Nginx and Postgres.I would appreciate any feedback on whether this deployment approach is optimal or if there is a better alternative. i found pyinstaller which will convert code to exe but not sure if its optimal way for web application like flask and django -
Django Unit Test for downloading a file
Here are the items from the FileResponse object that was returned when I called the API to download the file (not requests library). I am using django test client. How do I download the Example file.json. from django.test import Client c = Client() response = c.get(<URL>) print(response.items()) ('Content-Type', 'application/json') ('Content-Length', '2') ('Content-Disposition', 'attachment; filename="Example File.json"') ('X-Frame-Options', 'DENY') ('Vary', 'Cookie') ('X-Content-Type-Options', 'nosniff') ('Referrer-Policy', 'same-origin') ('Cross-Origin-Opener-Policy', 'same-origin') The following two statements print empty list print(response.getvalue()) # prints b'[]' print(json.loads(b"".join(response.streaming_content))) # prints b'[] I am trying to get to print the contents of the json file -
HTTPSConnectionPool Error with pip install django
I am trying to install django in my windows pc. but I have same Error every time. I uninstalled python,my ide,disable firewall and antiviruse but my Error till exist. PS C:\Users\toranj> python -m pip install django Collecting django WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl (Caused by ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")) -
How to modify my ORM to show the date in the select?
I would appreciate your help friends since I am new and there are several things that I do not master! I have a data record and a date is saved in each of the records, then I need to display the information depending on the date it was saved, when viewing the date data in my select it is displayed as follows enter image description here This is the code of my forms where I create the select, I imagine that the answer to my problem is to modify the ORM (which I have tried in several ways and I can't do it) and the data must be distinct so that the month does not repeat class Report2Form(Form): reportDate = ModelChoiceField( queryset=ConsElect.objects.values_list('date', flat=True), widget=Select(attrs={ 'class': 'form-control', # ('F , Y') This is how it appears to me as 'April, 2023' }), ) This is my model class ConsElect(models.Model): pgd = models.ForeignKey(TipoPGD, on_delete=models.CASCADE, related_name='conselect') date= models.DateField(default=datetime.now) read_morning = models.IntegerField(default=0) read_day = mod I need help so that my select is as I need! -
Django: django.urls.exceptions.NoReverseMatch: Reverse for 'view_name' not found. 'view_name' is not a valid view function or pattern name
I'm trying to run a test for my view and I get this error: Django: django.urls.exceptions.NoReverseMatch: Reverse for 'create' not found. 'create' is not a valid view function or pattern name. Here is my test: from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from users.models import User class UsersTests(TestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create(chat_id=123456789, language='en') def test_create_valid_user(self): response = self.client.post( reverse('users:create'), data = { 'chat_id': 1234, 'language': 'en' }, format='json' ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(User.objects.count(), 2) users/urls.py: from django.urls import path from . import views app_name = 'users' urlpatterns = [ path('get-all/', views.get_all), path('create/', views.create), path('get-by-chat-id/<int:chat_id>/', views.get_by_chat_id), path('update/<int:chat_id>/', views.update) ] app/urls.py (main urls.py): from django.urls import path, include urlpatterns = [ path('users/', include('users.urls', namespace='users')), ] output of $ python manage.py show_urls: /users/create/ users.views.create /users/get-all/ users.views.get_all /users/get-by-chat-id/<int:chat_id>/ users.views.get_by_chat_id /users/update/<int:chat_id>/ users.views.update I believe the problem comes from reverse function, and I tried a lot of things and couldn't fix it. Please tell me how to fix it. -
TemplateSyntaxError at /posts/post
I want to make the form display the value of the average rating for each post. Вот мой tamplate <a class="nav-link px-2 text-muted" href="{% url 'posts:post_detail' post.id %}"> <h2>{{ post.school_name }}</h2> <p>Average rating: {{ post_ratings.get(post=post).avg_rating }}</p> <p>Автор: {{ post.author }}</p> <p>Опубликовано: {{ post.created_at }}</p> <p>Обновлено: {{ post.updated_at }}</p> <a href="{% url 'posts:post_edit' post.id %}">Редактировать</a> <a href="{% url 'posts:post_delete' post.id %}">Удалить</a> </a> my view def post_list(request): posts = Post.objects.all() post_ratings = Comment.objects.values('post').annotate(avg_rating=Avg('score')) context = { 'posts': posts, 'post_ratings': post_ratings } return render(request, 'post_list.html', context) my models class Post(models.Model): school_name = models.CharField(max_length=200, default='') country = models.CharField(max_length=200, default='KZ') city = models.CharField(max_length=200, default='') content = models.TextField() website = models.CharField(max_length=200, default='') your_email = models.EmailField(default='') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) score = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(1)]) def __str__(self): return self.text def get_absolute_url(self): return reverse('post_detail', args=[str(self.post.id)]) Why am I getting this error? I tried to change the lines in the tamplates <p>Average rating: {{ post_ratings.get(post=post.id).avg_rating }}</p> -
Downloading the 'attachment' from the 'content-disposition'
Here are the items from the FileResponse object that was returned when I called the API to download the file. sample = c.get(<URL>) print(sample.items()) ('Content-Type', 'application/json') ('Content-Length', '2') ('Content-Disposition', 'attachment; filename="Example File.json"') ('X-Frame-Options', 'DENY') ('Vary', 'Cookie') ('X-Content-Type-Options', 'nosniff') ('Referrer-Policy', 'same-origin') ('Cross-Origin-Opener-Policy', 'same-origin') -
How can i limit results of a For Tag link array?
I have a DB query that pulls users order details and lists them as "Transactions" On our main user content dashboard i want to limit these query to only show 5 results. `{% for order in user.userordertokens %} <tr> <td>Order Description</td> <td>{{ order.createdat|date('m/d/Y')}}</td> <td>{{ order.tokenamount|number_format(0, '.', ',')}} GLN</td> <td><span class="fw-bold text-success">{{ order.status}}</span></td> <td> <a href="{{path('dashboard_purchase_details', { transactionId: order.idencoded })}}" class='btn btn-primary'>View Details</a> </td> </tr> {% endfor %}` This is the code im using to pull the data. Can i use a limit [5] type code to limit how many results are shown? `[:5] 0, 5` I have tried the following but both are not working, What am i doing wrong? -
Media images not displaying from AWS S3 in django app
It seems that I've configured all right, and in the dev tools or terminal no errors. Even the file crash icon disappeared. settings.py (i removed the name and other data that shouldn't be public STATIC_URL = "staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" # amazon s3 MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % os.environ.get('') AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_DEFAULT_ACL = 'public-read' AWS_S3_REGION_NAME = '' AWS_S3_VERIFY = True # config/settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images/') MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) models.py index.html {% for auction in allAuctions %} <div class="col"> <div class="card shadow-sm"> <img src="{{ auction.image.url }}" class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false" style="object-fit: cover;"> {% endfor %} my s3 policy also the s3 bucket and how it looks like -
Django - cannot pass error message to context
I have a view responsible for inviting users to note: def invite_user(request, pk): note = get_object_or_404(Note, pk=pk) form = InviteUser() err = False if request.method == 'POST': form = InviteUser(request.POST) if form.is_valid(): username = form.cleaned_data['username'] if User.objects.filter(username=username).exists() and username != request.user.username and not Note.objects.filter(members__contains = [username], id=note.id): notification = Notification(message=f"Do you want to join to {User.objects.get(username=note.user)}'s note: {note.title}?", user=User.objects.get(username=username), note_id=note.id) notification.save() else: print('Error') err = True return redirect('show', pk=note.id) if err: context = { 'form': form, 'error': 'You cannot invite this user!' } return render(request, context) else: context = { 'form': form, } return render(request, context) Template: {% if error %} <h1>{{ error }}</h1> {% endif %} When I pass correct user invitation is sent, but when there is error I see print in console, but there is not h1 with error in templete. What I am doing wrong?