Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django | Correct way to pass key identfiers to query sting
I was reading this Django doc: https://docs.djangoproject.com/en/3.0/topics/db/sql/#executing-custom-sql-directly It explains how to use params for preventing SQL-Injections and the documenation also just deals with paramaters, which in valid sql can become single quoted. Django simple escapes with single quotes by using: self.baz = "test" cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) becomes: b"UPDATE bar SET foo = 1 WHERE baz = 'test'" This shows that we cannot use the param argument for key identifiers like tablenames: cursor.execute("SELECT %s FROM %s", [column, table]) since single quotes are invalid sql query (back-ticks would be valid): b"SELECT 'id' FROM 'atablename'" This means that we can just pass data with string formatting e.g.: cursor.execute(f"SELECT {} FROM {}".format(column, table)) cursor.execute("SELECT "+column+" FROM "+ table) This way we have to take care ourselfs for sql-injections. Is there anything I am missing? How can I escape key identifiers in Django, so that there are no sql-injection possibilites? -
Django Model Object Automatic Filtering
I am working on a Django project, and I would like do a command like this: Student.objects.all().filter(name__iexact="Some name") in away that's can be more, well, malleable, e.g: someFunction(Student,objects.all(),'name__iexact',"Some name") or: Student.objects.all().some_advanced_filter(key='name__iexact',value='Some name') Thanks! -
Django how to save POST into form?
I'm trying to save the POST into my form. views.py def index(request): if request.method == 'POST': print('!PRINT request.POST') print(request.POST) form = PostForm(request.POST, request.FILES) print('!PRINT form') print(form) if form.is_valid(): form.save() return redirect('/') returned: !PRINT request.POST ~'title': ['Bart', 'Mat'], 'Create Match': ['Submit']}> !PRINT form ~name="title" value="Mat" maxlength="200" required id="id_title" ~name="title1" class="errorlist" This field is required. -
which database can handle about thousands of images effectively/easily?
I am about to start a project (going to develop a website), in which i'll have to deal with thousands of images. I'll upload those images into database and then i'll train,test them (using machine learning algorithms). My website will provide the user it's desired trained images, from the images he uploads. I can work with Django using python. will it work? or should i switch to SQL or MySQL? -
Following Django tutorial, "python manage.py migrate" doesn't create any django tables (MySQL, Pycharm)
In mysite.settings.py I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.path.join(BASE_DIR, 'test'), #'NAME': 'test', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', }} When I run 'python manage.py migrate' in the PyCharm terminal, nothing happens, no error message etc. No new tables are created in the database specified. I tried two things for NAME as you can see. MySQL Server version 8.0.19 MySQL Connector/Python 8.0.19 Python version 3.8 In PyCharm I have package mysqlclient 1.4.6 installed. Any advice on how to find the problem? How to get an error message? Thank you -
Creating a waiting queue in Django Channels?
I am currently working on a "wait queue" application on my Django app using channels. I have a channel layer using Redis to handle the connections within a group. I am also using a model in my database to track the amount of users in the queue. My question is if there is an easier and more scalable way. Will there be any issues down the road with this? class ChatConsumer(AsyncWebsocketConsumer): @database_sync_to_async def get_waiting_room(self): return WaitingRoom.objects.all().count() @database_sync_to_async def add_to_waiting_room(self, name): return WaitingRoom.objects.create(name=name) @database_sync_to_async def remove_from_waiting_room(self, name): return WaitingRoom.objects.filter(name=name).delete() async def connect(self): self.waiting_list = 'waiting_list' await self.channel_layer.group_add( self.waiting_list, self.channel_name) await self.accept() async def receive(self, text_data): self.text_data = json.loads(text_data) await self.add_to_waiting_room(self.text_data['user']) users = await self.get_waiting_room() await self.channel_layer.group_send(self.waiting_list, { 'type': 'user_list', 'users': str(users) }) async def disconnect(self, close_code): await self.remove_from_waiting_room(name=self.text_data['user']) await self.channel_layer.group_discard( self.waiting_list, self.channel_name) users = await self.get_waiting_room() await self.channel_layer.group_send(self.waiting_list, { 'type': 'user_list', 'users': str(users) }) async def user_list(self, event): users = event['users'] await self.send(text_data=users) When a user connects, they are added to a group in the channel_layer (Redis) and accepts the connection, when my user clicks a button, it sends a request to the channel and adds them to the waiting room (My Django model), on disconnect, it removes Model instance and … -
HTTP 403 Even Im Logged In
i am trying to develop django/angular project and using base user model for django user. I tried to implement JWT auth in both side. On django side i am using rest_framework_jwt library. I checked the token flow from client-side to server-side. With a simple login page on angular i use my username and password for logging in. It's accepting my data and redirects me to the main page where i use a service to get "feed" data from server-side. In this step it gives me 403 error. By the way when i use Postman for checking the scenerios im adding jwt as a authorization header like "JWT " and it still give me "Authentication credentials were not provided". Waiting your helps. Thanks. django -> settings.py middleware ; MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] django -> settings py rest_framework ; REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATON_CLASSES':( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'NON_FIELD_ERRORS_KEY': 'global', } i use these settings for jwt #JWT SETTINGS JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': timedelta(days=2) # datetime imported at start } using classic urls.py ( its and included part so it begins with api/auth/ ) urlpatterns = [ path('login/', obtain_jwt_token), … -
how to show or hide field of model after selected django admin choise field
The main logic of my project is to take a list of lessons. Lessons can be presented in the form of only a video format or in the form of a question and answer. My models for the video and the question are completely different. The problem is that I want to set the choice in the admin panel (video or question) and when the admin selects the video, fields for the video_id(foriegn key) should appear, another way must show question_id(from Question model, Foreign Key). Below showed my code(I removed unused fields): LESSON_CHOICES = ( (1, "video"), (0, "question"), ) class Lesson(models.Model): title = models.CharField(max_length=100, blank=True, default='') class VideoLesson(models.Model): video_url = models.TextField(default='') class Question(models.Model): text = models.TextField(default='') class LessonTask(models.Model): lesson_id = models.ForeignKey(Lesson, related_name='lesson_tasks', on_delete=models.CASCADE) order_num = models.IntegerField(unique=True) type = models.BooleanField(choices=LESSON_CHOICES, default=0) question_or_video_id = models.IntegerField(unique=True) I looked at this answer how to hide or show fields of model after clicked on choice field from admin in django but I did not understand anything and it is unlikely that it will help me. thnanks)) -
Unable to apply Django migration in Postgres DB
In Django app, I'm using Postgres DB. I have two tables where one of them has 76 million records and the other 8.2 million. I have created a new migration file where in I'm adding a new column to a table in an app and setting default value to 0. My database is hosted on Ubuntu EC2 instance which has RAM of 8 GB. When I try to apply the migration using python manage.py migrate app_name migration_file_name, it's throwing below error: File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.OperationalError: SSL SYSCALL error: EOF detected I have gone through this solution Postgres SSL SYSCALL error: EOF detected with python and psycopg But not sure if it's memory issue or something else. Python: 2.7.12 Django 1.11.15 Ubuntu: 18.04 Postgres DB: 10.7 What else could be the issue? -
Having troubles Django genieric UpdateView with UUID
I am stuck with this problem for some hours now, I guess, I mad some dumb mistake, but I can't see it. I am trying to use UpdateView, like this way: class ContributorEditView(UpdateView): model = Contributor template_name = "contributor/edit.html" slug_url_kwarg = 'uid' slug_field = 'uid' form_class = ContributorModelForm success_url = 'word/list' def get_queryset(self, *args, **kwargs): qs = super().get_queryset() print('args : ', args, " / ", kwargs) print('qs : ', qs) return qs with this modelform : class ContributorModelForm(ModelForm): class Meta: model = Contributor fields = '__all__' and this basiest html to just check: <form method="post" action="{% url 'contributor-edit' object.uid %}">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> and my url is set as bellow: path('edit/<uuid:uid>', views.ContributorEditView.as_view(), name='contributor-edit'), I am getting this error bellow, and I trying at least to check if I have my uid at the get_queryset as an argument so I can manually perform the database queryset, but I have nothing. NoReverseMatch at /accounts/edit/40acc93b-538c-44aa-9493-56887b5b430d Reverse for 'contributor-edit' with no arguments not found. 1 pattern(s) tried: ['accounts\/edit\/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$'] Request Method: GET Request URL: http://localhost:8000/accounts/edit/40acc93b-538c-44aa-9493-56887b5b430d Thank you in advance -
Cannot upgrade postgis extension. Getting error that postgis has no update path
I have installed postgres database using it in my django app. I started getting this error that django.db.utils.OperationalError: could not access file "$libdir/postgis-2.5": No such file or directory So I decided to update postgis to 2.5 ERROR: extension "postgis" has no update path from version "2.5.2" to version "2.5.0" Is there a wayout. -
Django stuck on processing request. 403 Error
I have an issue with my login form which is custom login form, and the issue us that when I login it gets stuck on processing requests and if I click on login twice I get a 403 error saying csrf_token is missing, however, I do have it. This is my login form: <form method="POST" action="{% url 'main:user_login' %}" class="form-signin"> {% csrf_token %} <div class="form-label-group"> <input type="text" name="username" id="inputText" class="form-control" placeholder="Username" required autofocus> <br/> </div> <div class="form-label-group"> <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="customCheck1"> <label class="custom-control-label" for="customCheck1">Remember password</label> </div> <input type="submit" class="form-control" name="" value="Login"> <hr class="my-4"> <p>Don't have account? <a href="{% url 'main:signup' %}" id="signup">Sign up here</a></p> <a href="{% url 'password_reset' %}" id="signup">Forgot Password</a> {% if form.errors %} <p style="color: red;">Sorry, the username or password you entered is incorrect please try again</p> {% endif %} </form> This is my login view: def user_login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect('home:home') else: form = AuthenticationForm() return render(request, 'main/user_login.html', context={'form': form}) I cannot figure out why this is happening, is it because of my form error or my login view? I am using a … -
Error while using URLconf defined in mysite.urls (Django tutorial)
I know this question has been asked and i have gone through all those answers but i didn't get the solution still. Please help me find out what is wrong . This is the code from django website for version 1.11 of django . mysite/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/' include('polls.urls')), url(r'^admin/', admin.site.urls), ] mysite/polls/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] mysite/polls/views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") I am getting the following error enter image description here -
How do I set a range for a positive integer where the upper bound would be an input from another field?
Suppose I have two variables A and B, both are positive integers. A can't be less than 1, B can't be greater than A. In my models I have something like this: A = models.PositiveIntegerField(validators=[MinValueValidator(1)]) B = models.PositiveIntegerField(validators=[MaxValueValidator(A)]) This gives me the following error: TypeError: '<=' not supported between instances of 'PositiveIntegerField' and 'int' Can someone suggest how to implement this kind of logic? -
Error: return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user
I am trying to create a photo gallery app using Django which takes a hashtag from a user and displays photos related to that hashtag. When I try to migrate the models, I get errors. I am not able to understand why these errors are showing. Please help me out. I am attaching the screenshot of the errors along with the codes. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Album(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE) image_url = models.CharField(max_length = 200) date = models.DateTimeField(default = timezone.now()) retweet_count = models.IntegerField(default = 0) like_count = models.IntegerField(default = 0) hashtag = models.CharField(max_length = 200, default = '#Swachh_Bharat') def __str__(self): return self.user.username views.py from django.shortcuts import render from TwitterAPI import TwitterAPI from Post.models import Album,User import calendar from django.contrib.auth.models import User import requests import http.client,urllib.request,urllib.parse,urllib.error,base64,sys import simplejson as json consumer_key='RNBUUEtazKVJemcMedGHWgMCV' consumer_secret='zILQDS386Dd4WRr8810gD5WAGbfkeVRDT3BYWs7RKChY1U7duM' access_token_key='893345180958564352-UT4mqHeDQyYllebzbsIPItOCyjHs8eP' access_token_secret='Gv2pbj6eeKvKPWjbePfO71la7xOeib2T5lV4SaL86UUdj' api = TwitterAPI(consumer_key,consumer_secret,access_token_key,access_token_secret) me = User.objects.get(username='vedant') def newsfeed(request): hashtag_string = '#Swachh_Bharat' hashtag_string = hashtag_string.lower() if(request.GET.get('mybtn')): hashtag_string = str(request.GET.get('hashtag')) print("HashtagString :: ",hashtag_string) if hashtag_string == '#vedant': url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = {} url_list_in_database = Album.objects.all().filter(user = me).values('image_url') temp = Album.objects.all().filter(user = me).values('image_url','date','retweet_count','like_count') url_list = {} for entry … -
Django 3 confirmation email 'redefinition of group name' error
I was following a Django tutorial to create confirmation emails after a user signs up to my site. (this one: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html) However, I am facing an error: "redefinition of group name 'uidb64' as group 3; was group 1 at position 100". I am VERY new to Django, however, my mentor couldn't help me either. Here is some of my code: views.py def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return redirect('start') else: return render(request, 'journal/activation_invalid.html') urls.py: urlpatterns = [ #... url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), ] account_activation_email.html: <!DOCTYPE html> <html lang="en"> {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} </html> I would appreciate any help! Thank you in advance. -
Django class based signup view with auto login not loging in the new user
I am developing an app in Django in which I am using the default User model and auth system built in Django. To the aforementioned model I have added (via foreign key) a Profile model to store some needed info. My problem comes when I try to create a new user using a class based view extending from generic.CreateView: class SignUpView(generic.CreateView): form_class = forms.RegistrationForm success_url = reverse_lazy('home') template_name = 'registration/signup.html' def form_valid(self, form): user = form.save() birthdate = form.cleaned_data.get('birthdate') services.ProfileService.create(user, birthdate) login(self.request, user, backend=settings.AUTHENTICATION_BACKENDS[1]) return super(SignUpView, self).form_valid(form) The user is created successfully, and as you can see I want to log in that newly created user automatically. But for some reason (I have tried to troubleshoot googling around) the user is not logged in after the successful sign up. Here you can see the custom form in use that inherits from UserCreationForm: class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True, label='EMAIL') birthdate = forms.DateField(required=True, label='FECHA DE NACIMIENTO') friend_token = forms.CharField( required=False, label='CÓDIGO AMIGO', max_length=8) class Meta: model = User fields = ( 'username', 'email', 'birthdate', 'password1', 'password2', 'friend_token' ) def clean(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise ValidationError("El email ya existe") return self.cleaned_data And here (if it is of some use) my settings.py … -
Production site doesnt accept django sessionid cookie
I recently tried to migrate my app to production site. However, I cannot really login. When I put correct credentials, I immeadiately get redirected back to login page. I suppose reason is my browser doesnt accept sessionid cookie, but I don't know why. There are my settings: """ Django settings for project project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False INTERNAL_IPS = ['127.0.0.1'] ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = … -
django ORm auto complete double underscore does not work
There are my models class BNumberGroup(SoftDeleteModel, TimeStampedModel): uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4, editable=False) name = models.CharField(max_length=128, default="") user = models.ForeignKey(User, on_delete=models.CASCADE) operator = models.ForeignKey(Operator, on_delete=models.CASCADE) redirect = models.ForeignKey(Redirects, on_delete=models.CASCADE, null=True, blank=True) TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) timezone = models.CharField(max_length=32, choices=TIMEZONES, default='UTC') def __str__(self): return "-".join([self.name, str(self.operator.name), str(self.user.first_name)]) class BNumber(SoftDeleteModel): uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4, editable=False) number = models.CharField(max_length=123) b_number_groups = models.ForeignKey(BNumberGroup, on_delete=models.SET_NULL, null=True) def __str__(self): return str(self.number) when i write BNumber.objects.filter(b_numbers_groups__) PyCharm does not show other options like : BNumber.objects.filter(b_numbers_groups__) b_numbers_groups__uuid b_numbers_groups__name b_numbers_groups__user b_numbers_groups__operator__id enter image description here queryset = BNumber.objects.filter(b_numbers_groups__uuid=uuid) -
Show last uploaded file details on redirected page - Django
folks. In my application user uploads his/her document on upload_document page, submits the form and he/she should see details (for example, document name, document author and etc.) on redirected result page. Now I don't know where should I get document itself from POST request. Or I'm entirely in wrong way. Here are my codes. views.py: @login_required(login_url='sign_in') def upload_document(request): context = {} form = UploadDocumentForm() if request.method == 'POST': form = UploadDocumentForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('result') context = { 'form':form } return render(request, 'upload_document.html', context) @login_required(login_url='sign_in') def result(request): # Don't know what to do here. return render(request, 'result.html', context) -
ManyToManyField is not saving in DB
I have searched the existing answers on this platform related to this but it isn't helping me. I save the Form but it is not saved in the DB. views.py: def student_list(request, pk) : course = get_object_or_404(Course, pk=pk) teacher = Instructor.objects.get(course_name=course) attendance = Attendance.objects.create(course_name=course, instructor_name=teacher) if request.method == "POST" : form = PostForm(request.POST, instance=attendance) if form.is_valid() : attendance = form.save(commit=False) attendance.published_date = timezone.now() attendance.save() return redirect('post_list') else : form = PostForm(instance=attendance) return render(request, 'blog/student_list.html', {'course' : course, 'form' : form}) forms.py: class PostForm(forms.ModelForm) : class Meta : model = Attendance fields = ('student_name',) def __init__(self, *args, **kwargs) : super().__init__(*args, **kwargs) if self.instance.pk : self.fields['student_name'].queryset = Student.objects.filter(course_name=self.instance.course_name) models.py: class Attendance(models.Model) : course_name = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) student_name = models.ManyToManyField(Student) instructor_name = models.ForeignKey(Instructor, on_delete=models.SET_NULL, null=True) published_date = models.DateTimeField(blank=True, null=True) student_list.html: <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> Also, the fields course_name, instructor_name and published_date are saved in the DB. It is only the student_name that is not saved. -
Django can not set AppConfig atrribute during ready()
i'm currently trying to set a custom attribute for the AppConfig of one of my project's apps. The point of doing so is, that the code producing the value needs to be run after App initialization. That's when i came accross the ready() method of AppConfig. So suppose i got an app called content my apporach is : from importlib import import_module from django.apps import AppConfig from django.conf import settings class ContentConfig(AppConfig): name = "content" sone_val = None def ready(self): value = ... # some code if value: self.some_val = value The ready() method gets called and at that point the value is correct. However when i try to access this attribute later in views.py via from django.apps import apps as django_apps django_apps.get_app_config("content").some_val the result is None instead. What am I overseeing/missunderstanding here? -
TemplateDoesNotExist Exception - Django is not loading template from namespaced template
I am using Django 2.2.10 I have an app called myapp, and this is my folder structure: /path/to/project ... myapp ... templates myapp index.html When I place index.html in /path/to/project/myapp/templates/index.html I am able to view the template, however, when I place index.html in the correct subfolder (as shown above) and recommended in the Django documentation (as a way of "namespacing"the templates per application). I get the eror TemplateNotFound. This is the relevant portion of my settings.py settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates"), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', ], }, }, ] Why is Django not able to find the template, and how do I fix this? -
API with Signed endpoint security in Django REST framework
I'm looking up on how to develop an API with an API key (for the project) and Auth Token (for the users). I'm interested in this kind of authentification for the API key Binance API but I can't find any information on how to do it. Looking at other exchanges APIs looks like is a standard way to do it. Is there any documentation or tutorial on how to accomplish this kind of API key security? So far I found this https://pypi.org/project/djangorestframework-api-key/ but I think it is not what I'm looking for. -
control image size in bootstrap
I am using Django I am trying to make image slider using bootstrap, this is my code so far {% extends "blog/modelsbase.html"%} {% block content%} <body> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src= "/media/models/dd08-43fc-ae2b-c6bc75ade6f6.jpg" alt="First slide"> </div> {% for image in images %} <div class="carousel-item"> <img class="d-block w-100" src= "{{image}}" alt="Second slide"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </body> {% endblock content%} </html> this is my views.py from django.shortcuts import render import os images = os.listdir('/media/models/model1') def test_model_bt(request): return render(request,'blog/model1.html',{'title':'TEST_MODEL','images':images}) The images are showing correctly,I would like to place the images inside some sort of container to give them max size [800x800] (if they are larger than it reduce size else pass), how can I do it ? Note:for now my code is "mobile friendly" I would like to keep that I got my slider from Carousel · Bootstrap