Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React-router-dom v6 didn't show page when try to route
Hi guys so I'm trying to learn about react-router-dom newest version which is version 6. I tried to create a basic routing in my react-django app, but it didn't work if I create many Routes, for example when i change my route into 8000/product it will show page not found. Can anyone help me with it ? App.js: import React from "react"; import HomePage from "./components/HomePage"; import Product from "./components/Product"; import ProductDetail from "./components/ProductDetail" import { BrowserRouter as Router, Routes, Route, Outlet, } from "react-router-dom"; const App = () => { return ( <> <Router> <Routes> <Route path="/" element={<HomePage/>}/> <Route path="/product" element={<Product/>}/> <Route path="/productdetail" element={<ProductDetail/>}/> </Routes> </Router> <Outlet/> </> ) } export default App -
Use MultipleChoiceField for class
I want to use multipleChoiceField, to choice from model I have model,Template so ,I did this in forms.py class WorkerForm(forms.ModelForm): templates = forms.MultipleChoiceField( Template.objects.all(), required=False, label='template') However it shows error templates = forms.MultipleChoiceField( TypeError: __init__() takes 1 positional argument but 2 were given I am checking the document here. https://docs.djangoproject.com/en/4.0/ref/forms/fields/ However there are only this, not mentioned about using class instance. -
how to create a custom session for log in user in Django
I am trying to login a user by sending a post request to an endpoint, the endpoint is returning status of 200 means the user information is true, but what i have been doing previously in django is simplify using authenticate method and passing user_phone and password later setting that resul to login(request, user_phone), now I dont know what to do here as here I am getting a response from that api which is just a user id, can we do something custom for this result. -
ERROR django.core.exceptions.ImproperlyConfigured:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Need to return a Single JSON response for two serializers in a customized way
serializers class Consolidated_Final(serializers.ModelSerializer): users = serializers.SerializerMethodField() class Meta: model= Users fields= ['users','id','employee_name','billable_and_non_billable'] def get_users(self,obj): query = Add_Job.objects.all() return Add_Job_Serializers(query, many =True).data views @api_view(['GET']) def final_view(request): q1 = Users.objects.values('id','employee_name','billable_and_non_billable',) query = Consolidated_Final(q1,many=True) return Response(query.data) It is returning me the JSON response as [ { "users": [ { "id": 1, "job_name": "timesheet", "Hours": "12:12:00", "start_Date": "0121-12-12T12:12:00+05:53", "end_Date": "1211-12-12T12:12:00+05:53", "client": 1, "project": 1, "user": 1 }, { "id": 2, "job_name": "Add", "Hours": "12:12:00", "start_Date": "1212-12-12T12:01:00+05:53", "end_Date": "0121-12-12T12:12:00+05:53", "client": 1, "project": 2, "user": 2 } ], "id": 1, "employee_name": "vinoth", "billable_and_non_billable": "Billable" }, { "users": [ { "id": 1, "job_name": "timesheet", "Hours": "12:12:00", "start_Date": "0121-12-12T12:12:00+05:53", "end_Date": "1211-12-12T12:12:00+05:53", "client": 1, "project": 1, "user": 1 }, { "id": 2, "job_name": "Add", "Hours": "12:12:00", "start_Date": "1212-12-12T12:01:00+05:53", "end_Date": "0121-12-12T12:12:00+05:53", "client": 1, "project": 2, "user": 2 } ], "id": 2, "employee_name": "Maari", "billable_and_non_billable": "Billable" }, { "users": [ { "id": 1, "job_name": "timesheet", "Hours": "12:12:00", "start_Date": "0121-12-12T12:12:00+05:53", "end_Date": "1211-12-12T12:12:00+05:53", "client": 1, "project": 1, "user": 1 }, { "id": 2, "job_name": "Add", "Hours": "12:12:00", "start_Date": "1212-12-12T12:01:00+05:53", "end_Date": "0121-12-12T12:12:00+05:53", "client": 1, "project": 2, "user": 2 } ], "id": 3, "employee_name": "Maari", "billable_and_non_billable": "Billable" } ] I need the JSON response as [ { "users": [ { "id": 1, "job_name": "timesheet", "Hours": … -
How to streamline code using for statement when rendering in django's views.py
I'm using django and the code below works inefficiently. Is there a way to shorten the method of creating and appending a list by using a for statement as in the code below? list is used to create graphs in apex chart javascript. [views.py] annotations = {} types = ('A', 'B', 'C', 'D', 'E', 'F') for type in types: annotations[type] = Count('id', filter=Q(type=type)) annotations[f'r_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Recruiting')) annotations[f'N_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Not yet recruiting')) annotations[f'H_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Holding')) annotations[f'C_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Completed')) counts = Research.objects.values('teacher').annotate(**annotations).values('teacher', *annotations.keys()) teacher = []; A = []; B= []; C= []; D= []; E= []; F= []; r_A = []; r_B = []; r_C = []; r_D = []; r_E = []; r_F = []; ... C_E = []; C_F = []; for count in counts: teacher.append(str(count['teacher'])) A.append(str(count['A'])) B.append(str(count['B'])) C.append(str(count['C'])) D.append(str(count['D'])) E.append(str(count['E'])) F.append(str(count['F'])) r_A.append(str(count['r_A'])) r_B.append(str(count['r_B'])) r_C.append(str(count['r_C'])) r_D.append(str(count['r_D'])) r_E.append(str(count['r_E'])) r_F.append(str(count['r_F'])) ... C_E.append(str(count['C_E'])) C_F.append(str(count['C_F'])) return render(request, 'graph.html', { 'teacher': teacher, 'A': A, 'B': B, 'C': C, 'D': D, 'E': E, 'F': F, 'r_A': r_A, 'r_B': r_B, 'r_C': r_C, 'r_D': r_D, 'r_E': r_E, 'r_F': r_F, ... 'C_E': C_E, 'C_F': C_F }) [graph.html] series: [{% if is_recruiting == 'Recruiting' %} { name: 'A', data: {{ r_A … -
Problem installing Django Tech Stack on Apples M1
I just got a new Mac with an M1 chip, but I have problems getting our stack to run. Its a django project, with a few dependencies attached. Most of them being: grpcio google-cloud-vision googlemaps When installing on a fresh M1, using python 3.9.10, i get this error Traceback (most recent call last): File "/Users/tl/work/project/./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/tl/work/project/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Users/tl/work/project/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/Users/tl/work/project/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/tl/work/project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Users/tl/work/project/image_analysis/apps.py", line 8, in ready import image_analysis.signal_handlers File "/Users/tl/work/project/image_analysis/signal_handlers.py", line 6, in <module> from image_analysis.analyze import analyze_images File "/Users/tl/work/project/image_analysis/analyze.py", line 8, in <module> from google.cloud import vision File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/cloud/vision/__init__.py", line 18, in <module> from google.cloud.vision_v1.services.image_annotator.async_client import ( File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/cloud/vision_v1/__init__.py", line 21, in <module> from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/cloud/vision_v1/services/image_annotator/__init__.py", line 18, in <module> from .client import ImageAnnotatorClient File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/cloud/vision_v1/services/image_annotator/client.py", line 27, in <module> from google.api_core import gapic_v1 # type: ignore File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/api_core/gapic_v1/__init__.py", line 18, in <module> from google.api_core.gapic_v1 import config File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/api_core/gapic_v1/config.py", line 23, in <module> import grpc File "/Users/tl/work/project/venv/lib/python3.9/site-packages/grpc/__init__.py", line 22, in <module> from grpc import _compression File "/Users/tl/work/project/venv/lib/python3.9/site-packages/grpc/_compression.py", line 15, in <module> from grpc._cython import cygrpc ImportError: … -
How do I get Multiple Select Value from HTML Form in django?
Actually, I am fetching data from API and displaying the data as form to submit in models <label for="images">Images:</label><br> <select name="images" id="images" multiple> {% for img in images %} <option value="{{img}}">{{img.image_name}}</option> {% endfor %} </select> But When I print(request.POST['images']) Returns {'id': 3, 'image_name': 'abc2', 'image': '/media/blogs/Screenshot_from_2022-02-09_12-04-07_P2JqvW7.png'} Returns The last I have selected Can Anyone Plz Help Me Thanks -
How to add select all checkbox in Django admin panel to all editable column?
I searched in the last day for information about how to add a select/deselect all checkbox into my Django admin panel but I didn't find the solution. I like to have these checkbox for all the columns not just for the first (in this case the user model). I like to manage all the objects with one checkbox click but it is also important to save the choice and if I come back to this site it should show the condition I saved before. I attached an image about what I like to do. -
why i am getting this error?can anyone help me...?
user registration using mysql django This is the error im getting and can't find to resolve it.Can anyone help me, i'm using python django and mysql as database with a custom user model...? AttributeError at /accountregister/ 'Manager' object has no attribute 'create_user' Request Method: POST**strong text** Request URL: http://127.0.0.1:8000/accountregister/ Django Version: 3.2.7 Exception Type: AttributeError Exception Value: 'Manager' object has no attribute 'create_user' Exception Location: /home/akshay/Django/mysite/account/views.py, line 20, in register Python Executable: /home/akshay/Django/my_env/bin/python Python Version: 3.8.10 Python Path: ['/home/akshay/Django/mysite', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/akshay/Django/my_env/lib/python3.8/site-packages'] Server time: Wed, 16 Feb 2022 06:38:41 +0000 Traceback Switch to copy-and-paste view /home/akshay/Django/my_env/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /home/akshay/Django/my_env/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /home/akshay/Django/mysite/account/views.py, line 20, in register user=Newuser.objects.create_user(username=username,Email=Email,pwd1=pwd1,pwd2=pwd2,gender=gender) … ▶ Local vars this is my views.py from django.shortcuts import render from django.contrib.auth.models import * from .models import * from django.contrib import messages def index(request): return render(request,'accounts/index.html') def register(request): if request.method == 'POST': username = request.POST['uname'] Email = request.POST['email'] pwd1 = request.POST['pass1'] pwd2 = request.POST['pass2'] gender=request.POST['gend'] user=Newuser.objects.create_user(username=username,Email=Email,pwd1=pwd1,pwd2=pwd2,gender=gender) user.save() messages.success("user saved successfully....!") return render(request,'accounts/register.html') else: return render(request,'accounts/register.html') this is my models.py................... class Newuser(models.Model): username=models.CharField(max_length=50) Email=models.CharField(max_length=50) pwd=models.CharField(max_length=50) gender=models.CharField(max_length=1) this is my urls.py........................ urlpatterns … -
Django admin stackedinline adding new data
I am using stackedInline for Django admin and when trying to add new data the existing data appears below as new tabs how can I solve that. my model category is as follows class Category(models.Model): '''category model for the genere of the stories''' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100) owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='categories', on_delete=models.CASCADE, null=True, blank=True ) is_primary = models.BooleanField(default=False) parent_category = models.ForeignKey( "self", related_name="children", on_delete=models.SET_NULL, null=True, blank=True, default=None) and my admin is like this class TabedAdmin(admin.StackedInline): model = Category extra = 1 class CategoryAdmin(admin.ModelAdmin): inlines = [TabedAdmin, ] def get_queryset(self, request): queryset = super(CategoryAdmin, self).get_queryset(request) queryset = queryset.filter(is_primary=True).all() # you logic here to `annotate`the queryset with income return queryset and when trying to add new data from the admin the form shows that the first section is empty and all the available categories are listed as like an edit view from the second tab itself. what might be the reason for this? -
Settings.py returning ModuleNotFound error on app that exists
I am relatively new to Django and trying to create a simple app to enable a user to signup and login However when I try to runserver to test what I currently have I run into this error message: ModuleNotFoundError: No module named 'signup.app' This is the structure of my project peerprogrammingplat --- peerprogrammingplat --- signup this is my installed apps in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'signup.app.SignupConfig', ] my views.py from .models import * def register(response): form = UserCreationForm() return render(response, "signup/register.html", {"form":form}) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('register/', signupv.register, name="register"), ] -
[Django]Intermittent unauthorized API requests when using tokens
I am using tokens for Django rest API authentication. I noticed that in the logs, from time to time, there are unauthorized requests. The user that the token created for is set to be superuser, and other requests are successful, so it shouldn't be the problem of the token/permission. Is there some kind of connection pool limit or anything that would cause such unauthorized problem but then recover quickly? I am using 'rest_framework' and 'rest_framework.authtoken'. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } -
React/Django cannot update data in a table without also updating the image field associated with it
I am developing a web application project for an alumni group using react/django and using axios to fetch data. Right now, I am able to Create an event with fields such as (event_name, date, images, etc.). I am also able to update the event details, but my problem is that I cannot update any other fields without also changing the picture. I've handled the null requests through django and when I test on Postman and any api views, POST/PUT/DELETE/GET all work fine, so I believe it's something to be handled in react. The image field is labeled gallery. Below is a js file that contains a form that populates the form inputs with the data from for a particular event. Any help would be appreciated. I've tried to look for other answers, but just because they might be out there, doesnt mean I know where to look or how to interperet that is what I'm doing wrong, seeing im just a beginner. import React, { useState, useEffect } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { getEventById, updateEventById } from "../../../api/apiCalls"; const EventUpdate = () => { let navigate = useNavigate(); const { id } = useParams(); … -
Multiple related foreignkeys
class Flow(models.Model): name = models.CharField(max_length=200) pre_requisite = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL) pre_requisite_status = models.ForeignKey("FlowStepStatus", on_delete=models.SET_NULL, null=True, blank=True, related_name='pre_requisite_status') This gives me one pre-requisite and it's status (pre_requisite_status). But I want to have flexibility for multiple pre_requisite and their respective statuses. How can I modify model to have it? -
Make a route expire in a short time
I am trying to implement a task that for rating services. Users will be receiving a SMS text message including a short link. After click that short link, they will fill out the information and submit. And then I will store those information in the database. That is the requirement, now move on to implement part. I am thinking to generate a route like this: https://www.app.com/{customerId}/?access_token=fdsaf.dsaf.fdsafads Then put it under bitly or short.io. The access_token will only valid for 10 seconds start from the time that the url is generated. Do you think is it good enough for safety ? any suggestion would be highly appreciate. Thank you. -
messages.error doesn't work with fetch js in form, Django
views: if request.method == "POST": user_name = request.POST['user_name'] email = request.POST['email'] password = request.POST['password'] re_password = request.POST['re_password'] if len(user_name) >= 16: messages.error(request, 'Too long') ... js: const form = document.forms["register_form"]; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; form_data = new FormData(form); myHeaders = new Headers() myHeaders.append("X-CSRF-Token", csrftoken) fetch("/account/register/", { headers: myHeaders, body: form_data, method: "POST" }).then(function (response) { if (response.ok) { console.log("successfully registered"); return response.json(); } return Promise.reject(response); }).then(function (data) { console.log(data); }).catch(function (error) { console.warn('Custom Error:', error); }); }) html: <form method="POST" name="register_form" id="register-form"> {% csrf_token %} .... fields .... {% for message in messages %} {{message}} {% endfor %} form working correctly and POST data without reloading page... but problem is about messages.error it doesn't work in template...any problem ? there is any solution to show errors from views in back-end without page refresh ? -
GCC ERROR IN CPanel Terminal Trying to Install Pillow
Please I need help, I am trying to host a Django Project in Cpanel. I have created a Python App (Python 3.8.6) Launched the Virtualenv on Terminal and install django according to my project version (Django 3.2.6) Now Trying to install Dependencies such as Pillow and Mysqlclient, I keep getting the below error. unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory building 'PIL._imagingmorph' extension /opt/rh/devtoolset-7/root/usr/bin/gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -fno-semantic-interposition -pthread -Wno-unused-result -Wsign-compare -ffat-lto-objects -flto-partition=none -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -fno-semantic-interposition -pthread -Wno-unused-result -Wsign-compare -ffat-lto-objects -flto-partition=none -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -I/usr/include/freetype2 -I/tmp/pip-build-hrzlinrf/pillow -I/home/westhfef/virtualenv/humanities/3.8/include -I/usr/include -I/opt/alt/python38/include/python3.8 -c src/_imagingmorph.c -o build/temp.linux-x86_64-3.8/src/_imagingmorph.o unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory error: command '/opt/rh/devtoolset-7/root/usr/bin/gcc' failed with exit status 1 I have tried everything I can, but didn't work. -
How to reference queryset result in Django
The class model I wrote is complex and large, so I can't write all the code here. Please understand. [views.py] separate_line = Assignment.objects\ .values('id')\ .annotate(ABC=Min(F('feedback__ABC_date')))\ .annotate(C1D1_ABC=ExpressionWrapper(Cast(F('feedback__injection_date'), DateField()), output_field=DateField()) - ExpressionWrapper(Cast(F('ABC'), DateField()), output_field=DateField())) \ .values('id', 'C1D1_ABC') Result: <QuerySet [{'id': 3391, 'C1D1_ABC': datetime.timedelta(days=13)}, {'id': 3392, 'C1D1_ABC': datetime.timedelta(days=27)}]> I succeeded in extracting the desired queryset by creating the C1D1_ABC field using id and annotation. ABC_C1D1 = Feedback.objects.values('assignment__research')\ .annotate(separate_sum=Sum(separate_line['C1D1_ABC'], filter=Q(assignment_id__in=separate_line['id'])), separate_count=Count('assignment', distinct=True, filter=Q(assignment_id__in=separate_line['id'])))\ .values('assignment__research__research_name', 'separate_sum', 'separate_count')\ I am trying to apply the queryset result(-> separate_line) to another ORM calculation, but the following error occurs. Error Message: QuerySet indices must be integers or slices, not str. If I replace ['id'] with [0] referring to the error message, the following error message occurs. Error Message: Field 'id' expected a number but got 'id'. -
Attribute Error while importing views in Urls.py in django rest framework
views.py from rest_framework.decorators import api_view from rest_framework import status from django.shortcuts import render from rest_framework.views import APIView from rest_framework import authentication, permissions from django.contrib.auth.models import User from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response from App.serializers import * from App.models import * from App.serializers import * # Create your views here. class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAdminUser] def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames) class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email }) @api_view(['GET']) def consol_overall_view(request): user = Users.objects.values('id','employee_name','billable_and_non_billable',) qs = conso_serializers(user, many= True) proj = Add_Job.objects.values('project','user','client') qs1 = timelog_serializers(proj, many= True) cli = Add_Timelog.objects.values('Date','Hours','project_id') qs2 = time_serializers(cli,many= True) return Response(qs.data+qs1.data+qs2.data,status = status.HTTP_200_OK) urls.py from django.contrib import admin from django.urls import path,include from django.urls import re_path from django import views from App.views import CustomAuthToken from.router import router from rest_framework.authtoken import views from django.views.generic import TemplateView from … -
Is there a way to Connect your Google Reviews into a Django Website?
been looking for a tutorial whereby one can connect automatically the reviews they receive from Google My Business and add them as testimonials to a Django Website. -
Images are not getting displayed on my website (HTML)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>AYNTK</title> </head> <body> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="templates\Slide 1.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img src="templates\Slide 2.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img src="templates\Slide 3.jpg" class="d-block w-100"> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html> I am really new to designing with HTML and CSS... I took this code from Bootstrap website, trying to create a carousel and added the relative path of my images to the img tag as source. The images does not get displayed on the website.. What can possibly be the reason? -
Basic idea to access items in S3 bucket from Browser
I use [django-s3direct][1] to upload file to S3 bucket. Once file is uploaded there comes url appeares here. https://s3.ap-northeast-1.amazonaws.com/cdk-sample-bk/line-assets/images/e236fc508939466a96df6b6066f418ec/1040 However when accessing from browser, the error comes. <Error> <script/> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>025WQBJQ5K2W5Z5W</RequestId> <HostId>FF3VeIft8zSQ7mRK1a5e4l8jolxHBB40TEh6cPhW0qQtDqT7k3ptgCQt3/nusiehDIXkgvxXkcc=</HostId> </Error> Now I can use s3.ap-northeast-1.amazonaws.com url? or do I need to create access point ? Access permission is public and bloc public access is off Bucket policy is like this { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::678100228133:role/st-dev-base-stack-CustomS3AutoDeleteObjectsCustomR-MLBJDQF3OWFJ" }, "Action": [ "s3:GetBucket*", "s3:List*", "s3:DeleteObject*" ], "Resource": [ "arn:aws:s3:::cdk-st-dev-sample-bk", "arn:aws:s3:::cdk-st-dev-sample-bk/*" ] } ] } Is there any other things I need to check? -
Dynamic Django urls redirects to the wrong function
So what I am trying to do is create urls such that the user can see complaints either by passing a particular parameter or sort by upvotes by default if no parameter is passed. urls.py path('', views.exploreComplaints, name='explore-complaints'), path('?sort_by=<str:sorting_parameter>/', views.exploreComplaints, name='explore-complaints-by-parameter'), views.py def exploreComplaints(request, sorting_parameter="upvotes"): complaints = Complaint.objects.all() if(sorting_parameter=="name"): complaints = sorted(complaints, key = lambda x : x.complaint_name) else: complaints = sorted(complaints, key = lambda x : x.complaint_upvotes, reverse = True) context = {'complaints':complaints} return render(request, 'complaints/complaints.html', context) The sorting parameter does not work when I go to a URL, the value of sorting_parameter is always upvotes, even when I go to a url with ?/sort_by=name in the end. Where am I wrong? -
Rest django checking the duplicate number
if i adding the number 5 i want to check all the numbers before 5( like 1,2,3 and 4 )is must have inside the db ,then only can i add the number 5 ,otherwise show error. And also check is any duplication in the Db using rest django model serilaizer.