Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django with Docker on Windows
I have a Django application running on AWS-Beanstalk server (using EC-2 Linux instance) This runs fine and trouble-free, but I am working on a Windows system and would like to work under the same system requirements to prevent problems. Now AWS offers a Linux instance with docker, but I couldn't do much with the documentation and have problems setting up my Windows 10 system with docker for aws. Does anyone know a tutorial or can help me in any other way? Jaron -
query list of attributes and values separately
I need to return attributes and values separately of particular product variant and my model looks like the following models.py class Product(models.Model): name = models.CharField(max_length=128) slug = models.SlugField() class Attribute(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=250, unique=True, allow_unicode=True) has_variants = models.BooleanField(default=False) def __str__(self): return self.name class VariantAttribute(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) name = models.CharField(max_length=100) slug = models.SlugField(max_length=250, unique=True, allow_unicode=True) value = models.CharField(max_length=100) def __str__(self): return self.value class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variants") variant = models.ManyToManyField(VariantAttribute, related_name="productvariants") name = models.CharField(max_length=255, blank=True) I need to return in such way variants: [ {'id': 1, name: 'variant 1', variant: [ { 'attribute': {'id': 1, 'name': 'Size'}, 'values': [ {'id':1, 'name': 'Medium', 'value': 'M'} ] }, { 'attribute': {'id': 1, 'name': 'Size'}, 'values': [ {'id':2, 'name': 'Large', 'value': 'L'} ] } ] } ] if i do product_variant = ProductVariant.objects.filter(product=product) product_variant[0].variant.all() then it lists all the variant attributes but I want to return attributes and values provided to that attribute separately like in above format without using rest framework. -
Override save method in Django not working
My goal with the following code is to create an athlete object and override the save method to automatically set the category for a given athlete based on the born_date. The Category class will be inherited in other models too. The list within the class serves as validation purposes for the save method and the tuples for choice fields (used in other models). Although everything seems right, I ran some test in the shell and the code is saving whatever born_date is inputed. Why is that the case? Can someone shed some light on the problem? Thanks from django.db import models from datetime import datetime class Category: list_categories = [ 'u12', 'u13', 'u14', 'u15', 'u16', 'u17', 'u18', 'u19', 'u20', 'u21', ] CATEGORIES = [ ('U12', 'u12'), ('U13', 'u13'), ('U14', 'u14'), ('U15', 'u15'), ('U17', 'u17'), ('U19', 'u19'), ('U21', 'u21'), ] class Athlete(models.Model, Category): name = models.CharField(max_length=120) born_date = models.DateField() category = models.CharField(max_length=3) def save(self, *args, **kwargs): year_now = datetime.date.today().year year_born_obj = datetime.datetime.strptime(self.data_nascimento, "%Y-%m-%d") self.category = 'u{}'.format(year_now - year_born_obj.year) if self.category in Category.list_categories: try: super(Athlete, self).save(*args, **kwargs) except ValueError: print('Category does not exist. Check born date') def __str__(self): return self.name Here is the shell output: >>> a1 = Athlete.objects.create(nome='Foo', born_date='1990-02-05') >>> a1.category … -
Where to put custom made functions in Django?
In my models.py I have this class. import time class Ticket(models.Model): username = models.CharField(max_length=50) booking_time = time.time() expired = models.BooleanField(default=False) I want the expired bool to turn to true if 1 hour has been passed since the booking_time but I don't have any idea where should I check for the same thing(I was thinking to make the function in views.py but views are only called when we go to a certain URL, in my case I want to check it every hour). -
not able to acess my product information on card
** settings.py** ''' MEDIA_ROOT=os.path.join(BASE_DIR,'/media/ecom/') MEDIA_URL='/media/' ''' from django.shortcuts import render from .models import Product from math import ceil Create your views here. from django.http import HttpResponse def index(request): products = Product.objects.all() print(products) n = len(products) nSlides = n//4 + ceil((n/4)-(n//4)) params = {'no_of_slides':nSlides, 'range': range(1,nSlides),'product': products} return render(request, 'ecom/index.html', params) def about(request): return render(request, 'ecom/about.html') def contact(request): return HttpResponse("We are at contact") def tracker(request): return HttpResponse("We are at tracker") def search(request): return HttpResponse("We are at search") def productView(request): return HttpResponse("We are at product view") def checkout(request): return HttpResponse("We are at checkout") ''' -
Django rest deferred task
I want to write an API method that will do a specific task (e.g task/create) But this task takes a long time. I want the user to run the task (task/create) and then polled the service until it was executed (task/status). As soon as the task is completed, the user can request the result (e.g task/result). What tools can I use to implement such a pattern? Can I put the task on a separate thread? -
How to get category anme from BelongsTomany Relation in Django?
I am trying to creating breadcrumbs in Django but i am unable to display data by category wise, I want to display subchild category data on product view page, please let me know how i can do that. and i have ManyToMany relation of SubChildCategory with Product model. Here is my models.py file... class Category(models.Model): cat_name=models.CharField(max_length=225) cat_slug=models.SlugField(max_length=225, unique=True) class SubCategory(models.Model): subcat_name=models.CharField(max_length=225) subcat_slug=models.SlugField(max_length=225, unique=True) category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True) class SubChildCategory(models.Model): subcategory=models.ForeignKey(SubCategory, related_name='SubChildRelated', on_delete=models.CASCADE, default=None, verbose_name='Sub Category') name=models.CharField(max_length=50, default=None) slug=models.SlugField(unique=True, max_length=50) class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ManyToManyField(SubChildCategory, related_name='pro_subchild', verbose_name='Select Category') here is my views.py file.. def productview(request, slug): product = Product.objects.get(slug=slug) template_name='mainpage/product-view.html' context={'product':product} return render(request, template_name, context) here is my product-view.html file..I am trying to display data here in this format..Home/Category(Name)/SubCategory(Name)/SubchildCategory(Name), and where Name is Category, Subchildcategory, SubChildCategory fields name.. <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'mainpage:homepage' %}">home</a></li> <li class="breadcrumb-item active" aria-current="page">Category Name / Subcategory Name/SubChildCategory Name/Product name</li> </ol> -
Django Ajax div not reloading/disappearing after posting comment
I am trying to resolve the problem for few days. I want to post the comment without refreshing page. The problem is the div in which comments are is not reloading or disappearing after hitting post button. It depends on how i "catch" it: when I use the id like: $('#comments').append('<p>' + data.comment.content + '</p><small>' + data.comment.author + '/' + data.comment.date_of_create + '</small>'); it is not reloading and if i use class it disappears. When i refresh the page, comment is being add properly. This is my code below. views.py class PostDetailView(FormMixin, DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' form_class = CommentForm def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): if request.method == 'POST': new_comment = Comment.objects.create( author = self.request.user, post = self.object, content = form.cleaned_data['content'] ) return JsonResponse({'comment': model_to_dict(new_comment)}, status=200) else: return self.form_invalid(form) def form_valid(self, form): form.instance.author = self.request.user form.instance.post = self.get_object() form.save() return super(PostDetailView, self).form_valid(form) def get_success_url(self): return reverse('post_detail', kwargs={'slug': self.object.slug}) comments.js $(document).ready(function(){ $("#commentBtn").click(function(){ var serializedData = $("#commentForm").serialize(); $.ajax({ url: $("commentForm").data('url'), data: serializedData, type: 'post', dataType: 'json', success: function(data){ console.log(data); $('#comments').append('<p>' + data.comment.content + '</p><small>' + data.comment.author … -
Modify login view to use simple JWT
I am using Django REST framework with SimpleJWT. I am trying to let me user log in form use simpleJWT authentication. Roughly, I think my log in view should: Retrieve the username/password from the form, send a POST request to the TokenObtainPairView.as_view() view, collect the returned token and store it in local storage. How do I do that in my django code? Currently I only have a standard log in form that does not use JWT. Settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',),} My project urls: urlpatterns = [ path('admin/', admin.site.urls), path("", include("my_api.urls")), path('api-auth/', include('rest_framework.urls')), path('api/token', TokenObtainPairView.as_view()), path('api/token/refresh', TokenRefreshView.as_view()), ] This is the user login view. I think I should make a POST request to the 'api/token' with my username and password as my payload, get the returned token, and store it in local storage, but I dont know how to do that in Django. def login_view(request): if request.method == "POST": # Attempt to sign user in email = request.POST["email"] password = request.POST["password"] user = User.objects.get(email=email) if user.check_password(password): username = user.username user = authenticate(username=username, password=password) print("Login successful") login(request, user) return HttpResponseRedirect(reverse("welcome"))``` -
GDPR compliance for a web app (Vue.js, Django, Heroku)
I have build a web application using Django, Vue.js and deployed it on Heroku. It is a web application made for a big charity where you can win prizes by donating to the charity. The following information is collected: Name Username Email Password Which is pretty basic, I guess. The reason no payment information is stored is because, upon clicking 'Donate', the user is redirected to JustGiving (implemented the JustGiving API) where they enter their payment information and such and are then redirected back to our website. A few emails are sent: An email when somebody wins a prize An email if you are the winner of the prize An email when a new prize draw is taking place A receipt of your donation This will be the first time I properly publish a web application so wanted to ask what steps I need to ensure to make sure the web app is legal. I know I have to probably have a 'cookies' alert and a section where users choose to receive emails or not. What other steps must I take to make sure I am not breaking any rules? -
ModuleNotFoundError: No module named 'survey_responses'
After changing a couple of things in my Django app (unfortunately, I forgot what exactly I've changed) I'm seeing this weird error message: (hr-djang) ➜ hr_djang git:(data-isolation) ✗ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/.../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/.../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/..../.virtualenvs/hr-djang/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/.../.virtualenvs/hr-djang/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'survey_responses' survey_responses if one of my installed apps in the Django project. I've commented out all mentioned all references to survey_responses except for the one in installed_apps but the error doesn't change. I'm a bit lost on what could cause this … -
Python Django - Internal Error ProgrammingError relation does not exist
This might probably be a duplicated question, but I can't find a post to answer my questions yet. Any post that is similar to this may help is appreciated. I tried to host my Django app using heroku.com git add . git commit -m "(commit_name)" git push heroku master When I tried to test the website (/questions/1), the website shows an Error 500 (Internal Error). First it shows a ProgrammingError: relation does not exist. After that I did $ heroku run python manage.py migrate try to solve the problem. The original error disappeared, but instead this happened: 2020-08-29T11:05:42.668070+00:00 app[web.1]: Internal Server Error: /questions/1 2020-08-29T11:05:42.668070+00:00 app[web.1]: 2020-08-29T11:05:42.668070+00:00 app[web.1]: DoesNotExist at /questions/1 2020-08-29T11:05:42.668071+00:00 app[web.1]: Question matching query does not exist. Settings.py: import django_heroku from pathlib import Path import os #--------------------(ommited)--------------------# # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] 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 = 'myweb.urls' 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', ], }, }, ] WSGI_APPLICATION = 'myweb.wsgi.application' # … -
Django - changing value from db in place and save it to db
I have table on my page like that: And models.py like that: models.py class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=30) category = models.IntegerField() offset_pages = models.IntegerField() read_pages = models.IntegerField() total_pages = models.IntegerField() book_path = models.CharField(max_length=200, default='') status = models.BooleanField(default=False) def __str__(self): return f'{self.category} | {self.title} | {self.author}' I would like to click on value in "Read pages" column (404 in this case) and then modify it and save to database. The only way I see it for now is to make an html input there with assigned value of 404, then change it within an input and submit it with additional button. I know how to do so, but it seems to me like there has to be way better solution. Does any onemay present me another solution? -
Creating a navigation menu custom tag in Django
Please accept my apology if this is answered somewhere in the Django docs or stackoverflow, but I couldn't track it down myself! I'm creating a portfolio app - mainly as a project to learn Django, but also potentially as a gift to a relative to promote their illustration work and save them some money. I'm creating a custom tag to render a main navigation menu. I've tested django-treebeard and django-mptt, but they feel excessive for a project on this scale, so I'm relying on ForeignKey relationships in my Page model to define parent-child pages. At the moment, I can render a list of all parent pages and all child pages, but of course I want to filter child pages by their parent. Would really appreciate any guidance, whether I do the filter in the templatetags file or in the template itself. My menu_tags.py (in 'Templatetags' dir for the app): from django import template from django.views.generic import ListView from pages.models import Page register = template.Library() @register.inclusion_tag('menus/main_menu.html') def main_menu(): parent = Page.objects.filter(is_parent=True) child = Page.objects.filter(is_parent=False) return { 'parent': parent, 'child': child, } And my template: {% for parent in parent %} <p><strong>{{ parent.title }}</strong></p> {% for children in children %} <p>{{ children.title … -
The page refreshes even when using Ajax
The page refreshes even when using Ajax, I also use csrf_exempt, but the problem was not solved.all java script work fine , all the console.log are displayed but the page was refreshed. i also use a uncompressed jquery file and then after i use jquery cdn link. but problem not solve. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="home"), path('save/', views.save_data, name="save"), ] views.py def save_data(request): # detail = Detail.objects.all() if request.method == "POST": form = DetailForm(request.POST) if form.is_valid(): name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] print(name) print(email) print(password) dt = Detail(name=name, email=email, password=password) dt.save() return JsonResponse({'status':'save'}) else: return JsonResponse({'status':0}) html file --------------------------- ------------------------------- <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" id="submitbutton" value="Save" class="btn btn-success"> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384- JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> AJAX <script> $('#submitbutton').click(function(e){ console.log('btn clicked') let nm = $('#nameinput').val() let em = $('#emailinput').val() let pa = $('#passwordinput').val() let csr = $('input[name=csrfmiddlewaretoken]').val() if (nm == ""){ console.log('enter name') }else if(em == ""){ console.log('enter email') }else if(pa == ""){ console.log('enter password') }else{ mydata = {name:nm, email:em, password:pa, csrfmiddlewaretoken:csr}; $.ajax({ url : "{% url 'save' %}", method : "POST", data : mydata, encode: true, success : function(data){ console.log(data.status); console.log(data); }, }) … -
Redirecting from the login page to signup page back to login page with the same parameters in the url in django
I may not have been descriptive in the title but what I want is that for example When a new user opens a page where login is required --> he is redirected to login page with the login url having a next parameter to the previous page.But as he is a new user he chooses to signup by clicking on a link on the login page which takes him to signup page ,now this is where the problem comes - The signup url gets no parameter and once user signs up he is automatically redirected to login page and after he logs in he is redirected to the index page instead of the page where login was required. This is my login view for my customer user model: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) next_page = request.POST['next'] if next_page != '': return redirect(next_page) else: return redirect('/') else: messages.info(request,"Email Password didn't match") next = request.POST['next'] if next != '': login_url = reverse('login') query_string = urlencode({'next': next}) url = '{}?{}'.format(login_url, query_string) # create the url return redirect(url) else: return redirect('login') else: return render(request,"login.html") And this is my … -
What is name of this block in Django?
i want to create similar block in Django admin panel , but what is this name ? i want to create similar section and group class , AUTHENTICATION AND AUTHORIZATION ,My_site and etc ... -
nested resolvers in Ariadne
When querying for list of products I need to show the product information along with variation. I mean i want products query to return something like this { "data": { "product": { "id": "1", "name": "Polo Shirt", "productType": { "name": "clothing" }, "category": { "name": "Men's" }, "variants": [ { "id": "1", "name": "S", "variant": [ { "attribute": { "name": "Size" }, "values": [ { "name": "S" } ] } ], }, { "id": "2", "name": "XL", "attributes": [ { "attribute": { "name": "Size" }, "values": [ { "name": "XL" } ] } ], }, ] } } } For such result, I have my schema for products as following type Query { products: [Product] } type Product implements Node { id: ID productType: ProductType! name: String! slug: String! description: String! category: Category! attributes: [SelectedAttribute] variants: [ProductVariant] articleNumber: String barcode: String } type SelectedAttribute { attribute: Attribute values: [AttributeValue] } type Attribute implements Node { id: ID name: String } type AttributeValue implements Node { id: ID name: String } type ProductVariant implements Node { id: ID! name: String! sku: String! product: Product! variant: [VariantAttributes] } type VariantAttributes { attribute: Attribute values: VariantAttribute } type VariantAttribute implements Node { id: … -
NOT NULL constraint failed: social_media_app_blogcomment.user_id
I'm making this comment system for my blogs.. I already made the model, the ModelForm and the view to display the comments and the blog. I'm just really confused how to save the comments related to a specific blog. I tried to save the comments with a view but I face an IntegrityError. A little help would be appreciated. Here's my views.py: @login_required #View to show the blogs and comments related to it def readblog(request, blog_pk): Blog = get_object_or_404(blog, pk=blog_pk) return render(request, 'social_media/readblog.html', {'Blog':Blog,'Form':CommentForm()}) @login_required #view to save the comments def commentblog(request,blog_pk): Blog = get_object_or_404(blog,pk=blog_pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): Form = form.save(commit=False) Form.Blog = Blog Form.save() return redirect('usersfeed') Urls.py: path('commentblog/<int:blog_pk>', views.commentblog, name='commentblog'), path('readblog/<int:blog_pk>', views.readblog, name='readblog'), HTML Page to write and save comments (along with the blog): {{ Blog.title }} <br> {{ Blog.text }} <br> {% if Blog.image %} <img src="{{ Blog.image.url }}" alt=""> {% endif %} <br> <form action="{% url 'commentblog' Blog.id %}" method="post"> {% csrf_token %} {{ Form.as_p }} <button type="submit">Comment!</button> </form> {% for i in Blog.BlogComment.all %} {{ i.comment }} <b>user:{{ i.user }}</b> <br> {% endfor %} -
Get client UUID from browser
I want to get client UUID, when user accesses my website. Actually, I am will be encrypting something a user can download and it will open in my application only. In my application I am getting UUID on the run and decrypting using this: os.popen('wmic csproduct get UUID').read() Everything it working fine, now the only limitation is that I couldn't find any way to get UUID of the client from my website, so that I can encrypt along with some other hashes that my application know and can add as salt and decrypt. My website id developed on Django. Note I think I need to write some script that user will download and it will send me the data all the time and then I will allow the user to download, anyone can guide me on this ? I know you can ask what if user changes the system etc. I just want to get UUID for now I have taken care of other things already. For now lets say I want to work on windows only, no Linux or Mac user -
How to solve Incorrect padding in Django?
I just installed 'clean_cachepackage in Django and after refresh my website i gotIncorrect paddingerror, here is the error codehttps://prnt.sc/u7y08g, so please let me know how i can solve this issues. I research a lot about it but i did not found base64.py` file in my file structure. -
I have a domain from GoDaddy and a Django app working on Linode with an IP address. How do I point the domain to the Django app using mod_wsgi?
I have a domain I bought from GoDaddy (example.com) and I have a Django app at an IP address. Without changing the nameservers on GoDaddy, how can I point the domain to the Django app? -
How can we create 'Story Like Feature' using HTML/CSS/JS
Suppose I have an array of Images or Videos like this var arr = ['1.jpg', '2.jpg', '3.mp4', '4.mp4'] I want to make a Story Like Feature like on Facebook or Instagram When a user clicks on Show Story it shows every pic for 10 seconds and if its a video it plays it till it is finished and then jumps to the next one. I want to add controls also.. For example if some clicks on the left side or right side the slideshow jumps to previous slide or next slide respectively... Any Idea how to implment it Using Just HTML/CSS/JS I am using Django Framework for my website -
Django error: "settings.DATABASES is improperly configured. Please supply the ENGINE value."
I am trying to follow the guide here for using multiple databases in Django 2.2, with the default database left blank. In my settings.py file I have # Set database routers DATABASE_ROUTERS = [r'myapp.db_routers.AuthRouter', r'myapp.db_routers.RemoteRouter'] # Database configuration - leave default blank DATABASES = { 'default': {}, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'remote': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'MY HOST NAME', 'NAME': 'MY DB NAME', 'PORT': 'MY PORT NAME', 'USER': get_secret(Secrets.REMOTE_DB_USERNAME), 'PASSWORD': get_secret(Secrets.REMOTE_DB_PASSWORD), 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'host_is_server': True } } } My db_routers.py file then contains the two database routers, as suggested in the documentation (but it should capture all of the django built-in apps): class AuthRouter: route_app_labels = {"admin", "sessions", "messages", "staticfiles", "auth", "contenttypes"} def db_for_read(self, model: Model, **hints) -> Optional[str]: if model._meta.app_label in self.route_app_labels: return "auth_db" else: return None def db_for_write(self, model: Model, **hints) -> Optional[str]: if model._meta.app_label in self.route_app_labels: return "auth_db" else: return None def allow_relation(self, model_1: Model, model_2: Model, **hints) -> Optional[bool]: if (model_1._meta.app_label in self.route_app_labels or model_2._meta.app_label in self.route_app_labels): return True else: return None def allow_migrate(self, db: str, app_label: str, model_name: Optional[str] = None, **hints) -> Optional[bool]: if app_label in self.route_app_labels: return db == "auth_db" else: return … -
Django error with redirect after registration or login
I am using the out the box standard Django authentication. Yet sometimes when I login or register, the page gets stuck on loading when it is supposed to redirect. I have checked my error logs, and there is nothing. Has anyone experienced this before, and how did you solve it?