Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auto end video call session from a page Django
I'm developing a custom video call app in Django. I want to end the video call session after 1 hour. Is there any way other than using JS or AJAX to auto exit from the page? -
Cannot open raw files from cloudinary in django admin
I do config the raw file's storage to couldinary and I can't open it in django admin(it shown 404 error). Did I miss something? I have set the storage location in setting.py as below: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' DEFAULT_FILE_STORAGE1 = 'cloudinary_storage.storage.RawMediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'XXXXX', 'API_KEY': 'XXXXXX', 'API_SECRET': 'XXXX-XXXXX', } CKEDITOR_UPLOAD_PATH = DEFAULT_FILE_STORAGE CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } Added to urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('team_profile.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.DEFAULT_FILE_STORAGE) Set the raw file's upload path in models.py: from django.db import models from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField from cloudinary_storage.storage import RawMediaCloudinaryStorage class apply_position(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=8) mail = models.EmailField(blank=False) file = models.FileField(upload_to='add/file_save/', null=False, storage=RawMediaCloudinaryStorage()) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.name The forms.py is fine and I've put it to the views.py def recruit(request): form = addForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): form.save() return redirect('/') else: form = addForm() The Error I got when I try to open the files in admin site: https://res.cloudinary.com/xxxxx/raw/upload/v1/media/add/file_save/xxxx.pdf HTTP ERROR 404 -
Django website wow.js and animate.css is not working
I got animate.css to work fine , but when i imported wow.js into my static folder, it did not function on the scroll or just in general. The animation part only works without the "wow" class. As my website is built with django, im not sure if that has anything to do with it. Here is the code that includes the animate and wow files. <link rel="stylesheet" href="{% static 'css/animate.css' %}"> this is the only one that works: <div class="container"> <h1 class="animate__animated animate__bounce" style="color:black;">An animated element</h1> all of these do not work and i don't know what i am doing wrong: </div> <div class="container"> <h1 class="wow animate__bounce" style="color:black;">An animated element</h1> </div> <div class="container"> <h1 class="wow bounce" style="color:black;">An animated element</h1> </div> <div class="wow bounce"> <h1 class="wow bounce" style="color:black;">An animated element</h1> </div> I have these loaded in as well: <script language="javascript" type="text/javascript" src="{% static 'js/wow.min.js' %}"></script> <script>new WOW().init();</script> Attached image of my folder hierarchy The wow.js does not work wherever i put the containers on the page. All of this code is in my base.html folder (please refer to the image attached) On my website, they are further down with other information (i did not include as it would be too messy … -
How to use async_to_sync() & sync_to_async() in Django?
I need to use the asynchronous methods in the Django Views. How can I accomplish that. The documentation is available here, but the example is not provided. The below code is not working and I am getting the error coroutine. async def Dashboard(requests): txt = await api.com/mymessage return render(requests, 'Index.html', {'message': txt}) What is the proper way to wrap the method in the async_to_sync()? -
How can you sort the order of cards displayed in HTML
I'm using Python and Django to build a website. I'm making a rough version of the homepage with Bootstrap and HTML. I have a group of Cards that have a time written on them (i.e "12:00AM" or "2:30PM"). How can I sort these cards in order of earliest to latest? Here's a link to a rough version of my code. I put random data in there because I'm getting real data from Django : Codeply Link -
Django: Page not found (404) when posting form data
I am trying to create a form to submit a blog post on an author detail page, so that the blog post will automatically use the current author as its "blog_author" foreign key. The Django docs recommended using 1 parent view and 2 subviews to handle get and post respectively (https://docs.djangoproject.com/en/3.0/topics/class-based-views/mixins/). The page renders fine with the get, but the post gives me an error reading "Page not found (404) - no blog post found matching the query." The exception is raised by my parent view (blog.views.AuthorDetail), but there is no traceback. Here are my views: class BlogAuthorDetailView(generic.DetailView): model = BlogAuthor def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = BlogSubmitForm() return context class BlogSubmit(SingleObjectMixin, FormView): template_name = 'blogauthor_detail.html' form_class = BlogSubmitForm model = BlogPost def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() #Should I be overriding form_valid() to use the line above? Not sure if I'm doing my data #handling in the right place return super().post(request, *args, **kwargs) def form_valid(self, form): blogpost = form.save(commit=False) blogpost.blog_author = self.object blogpost.save() return redirect('blog_author-detail', pk=self.object.id) class AuthorDetail(View): def get(self, request, *args, **kwargs): view = BlogAuthorDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = BlogSubmit.as_view() return view(request, … -
Django: Official recommendations for using try - except (aka try catch exception handling)
In Django specifically, what are the recommendations for using try/except, for example, in a view or similar area of the code? I could not find an official document on best practices & performance considerations for Django specifically. For context, if an exception is raised in a view without a try-except, the error and some trace is reported in the log and the Django server keeps running. Now, there are some times when a try-except is necessary for logic. There are other times when it's not- the best course of action is to raise it anyhow and leave the function. Technically, almost every line of code could be a try-except. In practise, that code gets very long, and rather than having 1 central way to deal with raised exceptions, it creates lots of copying and pasting across the dev team which can result in consistency issues/cat herding. What are the official recommendations, and failing that, what rules of thumb are there? FYI, using Python3. -
Web Socket through connection handshake error, status: 200 on production while on local its working fine, Django + Angular
I'm trying to set up a web-socket for real-time notification. My Frontend is Angular & Backend is Django using docker for both backend and frontend. On the local machine, it's working perfectly fine. Connection successfully establish & signal can transmit/broadcast. But when I deployed it on the server it through error 200 Here is the backend connection code: main -> routers.py application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( sog.notification.routing.websocket_urlpatterns ) ), }) app -> routers.py websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer ) ] consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] #usename self.room_group_name = self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) Here is the Frontend code: While I'm on local machine In Frontend I wrote WEB-SOCKET URL: wss://localhost:8000/ws/chat/notification_'+ authService.getUsername() For Server I used: wss://domain.com/ws/chat/notification_'+ authService.getUsername() websocket.service.ts import { Injectable } from "@angular/core"; import * as Rx from "rxjs/Rx"; @Injectable() export class WebsocketService { constructor() {} private subject: Rx.Subject<MessageEvent>; public connect(url): Rx.Subject<MessageEvent> { if (!this.subject) { this.subject = this.create(url); console.log("Successfully connected: " … -
How to multiply 2 fields and save the result to another field in django
i want to multiply 2 fields of django database and save the result to another field. like i want to multiply the selling price and total quantity of a product to find total price of all those products. -
Return serialized JSON from DRF Serializer
I have a custom serializer that is returning a string representation of JSON. This serializer uses django.contrib.gis.serializers.geojson.Serializer which is much faster than the DRF serializer. The downside of this serializer is that it returns everything already serialized into a string, rather than as a JSON serializiable object. Is there a way to shortcut the DRF obj>json string process and just pass the string as the json response? Currently I am doing the following, but the obj>string>dict>string process is not ideal: from django.contrib.gis.serializers.geojson import Serializer from json import loads class GeoJSONFastSerializer(Serializer): def __init__(self, *args, **kwargs): self.instances = args[0] super().__init__() @property def data(self): # The use of json.loads here to deserialize the string, # only for it to be reserialized by DRF is inefficient. return loads(self.serialize(self.instances)) Which is implemented (simplified version) in the view: from rest_framework.mixins import ListModelMixin from rest_framework.viewsets import GenericViewSet class GeoJSONPlaceViewSet(ListModelMixin, GenericViewSet): serializer_class = GeoJSONFastSerializer queryset = Places.objects.all() -
how to get the context of an object in object_list?
I have a query set in the PostListView, and I would like to access the .likes attribute of a single object in a post.objects.all() query_set. But in the templates' context, I can only access the context dict of: context {'is_paginated': True, 'object_list': <QuerySet [<Post: aasd>, <Post: asd>, <Post: ads>, <Post: asd>, <Post: asd>]>, 'page_obj': <Page 1 of 3>, 'paginator': <django.core.paginator.Paginator object at 0x10e5901c0>, 'posts': <QuerySet [<Post: aasd>, <Post: asd>, <Post: ads>, <Post: asd>, <Post: asd>]>, 'view': <blog.views.PostListView object at 0x10e5904f0>} How can I get the context of the single Post object from the QuerySet and therefore accessing that Post.likes attributes? Thanks Edited: Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'post': post, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context) def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect('http://127.0.0.1:8000/') class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['posts'] #attribute error, no attr likes in posts queryset if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return … -
Django select oneotone from queryset in view
view @login_required def users(request): """List all users page""" t_users = User.objects.all() users = t_users.usersettings.filter(search_hidden=False).select_related('user') context = {'users': users} return render(request, 'users/users.html', context) model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserSettings(models.Model): """Stores the user's settings.""" user = models.OneToOneField(User, related_name='usersettings', on_delete=models.CASCADE) public_profile = models.BooleanField(default=True) search_hidden = models.BooleanField(default=False) class Meta: verbose_name_plural = 'usersettings' def __str__(self): return f"{self.user}'s settings" @receiver(post_save, sender=User) def create_user_usersettings(sender, instance, created, **kwargs): if created: UserSettings.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_usersettings(sender, instance, **kwargs): instance.usersettings.save() I want to select all users that have search_hidden disabled, however what I've tried doesn't work.The error 'QuerySet' object has no attribute 'usersettings' is displayed whenever the page is requested. I probably need to select each user and retrieve the settings, but I don't know how to do that in an efficient manner. -
Find the specific work via beautifulsoup in django
i started to learn beautifulsoup. I tried to make web application with django that have a html form and get the keyword from this form. When it get keyword, need to find related words inside the website.It can successfully retrieve the form from post request but for some reason, the function is not returning the rendered html as expected. its also not printing output.text. When i change the code for find tags(div,p,a etc...) it's working without any problem. This code giving output until i make any request. i didn't understand where is the problem, render or patterns? How can i fix this problem? if request.method == "POST": keyword = request.POST['keyword'] if '£#$½{[]}' in keyword: print("Please enter invalid words") else: url = 'https://www.emu.edu.tr/en' contents = requests.get(url) page_html = contents.text pagesoup = bs4(page_html, 'html.parser') mykeyword = pagesoup.find_all(keyword) for output in mykeyword: if output.select('p')[0].text == '1': print(output.text) return render(request, 'BeatifulSoup.html', {} -
Do Django models tests need database usage?
Here an minimal example (full code), a foobar application with a Class Fruit whom I want to test the __str__() method. foobar.models : from django.db import models class Fruit(models.Model): """An MVC for testing models without using Django DB""" name = models.CharField(max_length=42) def __str__(self): return self.name.upper() foobar.tests from pytest import mark from foobar.models import Fruit fruit_name = "cherry" def test_fruit__str__py(): """testing Fruit.__str__() whitout using Django DB""" test_fruit = Fruit(name=fruit_name) assert test_fruit.__str__() == fruit_name.upper() @mark.django_db def test_fruit__str__dj(): """testing Fruit.__str__() using Django DB""" Fruit.objects.create(name=fruit_name) test_fruit = Fruit.objects.last() assert test_fruit.__str__() == fruit_name.upper() Question : Since the method you would test do not involve database or pre-loaded dataset and if I want to unit-test, is the first one (test_fruit__str__py()) enough relevant? -
Django collectstatic does not collect media files from react npm build folder
I have a frontend react app, after using npm run build it creates build folder with: build favicon.ico index.html service-woker.js static After using django's python manage.py collectstatic I noticed what django has done was that it pulls out only the static folder, favicon.ico is not pulled out. So, my website icon doesn't work. In my index.html, <link rel="apple-touch-icon" href="%PUBLIC_URL%/favicon.ico" /> In my settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../frontend/build/static') ] STATIC_ROOT = '/var/www/web/home/static/' STATIC_URL = 'home/static/' In chrome inspect in the headers element: <link rel="icon" href="./home/favicon.ico"> How do I get it to display my web icon. Thankyou! -
How to serve Static Folder files in script tag - Django
I am creating a project where i create a files dynamically and store those file in staticfiles folder But when i am accessing this file it is showing file in browser http://localhost:8000/static/rest_framework/css/bootstrap.min.css But when i trying to access file which i have created and stored in staticfiles/bot_js http://localhost:8000/static/bot_js/cfe96a9a-dc84-4127-9b00-0411b7b3288e.js It is showing Page not Found I want this file to hosted on my website serve as script file for different website, like this <script src="http://localhost:8000/static/bot_js/cfe96a9a-dc84-4127-9b00-0411b7b3288e.js"></script> But it is giving me Page not found (404). How can i serve this file for different website. settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' # Add these new lines STATICFILES_DIRS = ( os.path.join(BASE_DIR, '../frontend/build/static/'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') -
How to request a user response in the middle of a django view?
I have an html page, where a user sees information about an employee, on that page I have a query button, when I click on that button I open a modal with the information needed for the query such as Name, record, date of birth. In this modal I have a continue button, when the user clicks on that button I make an ajax request for a django view, in this view I create a Query type object, my query is performed on a page external to my code, and it follows the following steps: Consult.add_page () (basically inserts the user's data in a section). Consult.capcha () (at this point I make a post request on the page with the section data to obtain a captcha), here is my problem, I need to render the captcha on the screen, I need the user to answer it, and after that I need to continue the view flow to make a Consulta.consulta_page (). Following the commented code for better understanding obs: Consult is a class Obs2: I validate codes using Tkinter to render image for user and get response, but i cant use Tkinter in server Production, and i cant return HttpResponse … -
AllAuth allowing login from users.email and account_emailaddress tables
Allauth is allowing me to log in from email addresses in account_emailaddress.email and from user.email. How can I keep these both consistant so it only allows login from one table or another? Considering updating account_emailaddress.email in views but not sure if thats the best way to go about it. models.py class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) secondary_email = models.EmailField(max_length=254, unique=False, null=True, blank=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) settings.py ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_AUTHENTICATION_METHOD = 'email' LOGIN_REDIRECT_URL = 'dashboard' ACCOUNT_LOGOUT_REDIRECT_URL = 'home' LOGIN_URL = 'signin' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None -
Reverse for 'editar_arvore' with arguments '('',)' not found. 1 pattern(s) tried: ['arvore/editar_arvore/(?P<id>[0-9]+)/$']
I am having this error when I try to click to edit a form already submitted, it is as if I was not passing the arvore.id in the template ver_arvore. When I change arvore.id to a number(eg. 1) I can see all my records in the database, otherwise I have the NoReverse Match error. It is as if the view ver_arvore is not saving my dictionary, as shown in the traceback My models: class Arvore(models.Model): tag = models.CharField(max_length=255) nome = models.CharField(max_length=255) nivel = models.CharField( default='Planta', max_length=50, choices=( ('Planta', 'Planta'), ('Sistema', 'Sistema'), ('Equipamento', 'Equipamento'), ('Peça', 'Peça'), ) ) criticidade = models.TextField() requisitos = models.TextField(blank=True, null=True) descricao = models.TextField(blank=True, null=True) fabricante = models.CharField(max_length=255, blank=True, null=True) modelo = models.CharField(max_length=255, blank=True, null=True) pai = models.CharField(max_length=255, blank=True, null=True) localizacao = models.CharField(max_length=250,blank=True, null=True) link_historico = models.CharField(max_length=255, blank=True, null=True) link_pm = models.CharField(max_length=255, blank=True, null=True) link_foto = models.ImageField(blank=True, null=True) def __str__(self): return self.nome class Meta: managed = True db_table = 'arvore' class FormArvore(forms.ModelForm): class Meta: model = Arvore my url: app_name = 'arvore' urlpatterns = [ path('', views.ver_arvore, name='ver_arvore'), path('cadastro_arvore/', views.cadastro_arvore, name='cadastro_arvore'), path('editar_arvore/<int:id>/', views.editar_arvore, name='editar_arvore'), path('deletar_arvore/<int:id>/', views.deletar_arvore, name='deletar_arvore'), ] My views: def cadastro_arvore(request): if request.method != 'POST': form = FormArvore return render(request, 'arvore/cadastro_arvore.html', {'form': form}) form = FormArvore(request.POST, … -
Input redirect me on the wrong view
Hello i'm a beginner at django and i got this problem. (i don't know if the code i put is enough) When i decide to create a new comment, if i click on "create" instead of redirect me to "usercomments" and send the data to the database, it log me out and send me where log out is supposed to send me. i can't find a similar problem, i don't even know what kind of error it is, help Thanks :) Templates of "create comment" : <div class="create-comment"> <h2>Write a comment</h2> <form class="site-form" action="{% url 'usercomments:create' %}" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> </div> Urls.py : from django.conf.urls import url from . import views app_name = 'usercomments' urlpatterns = [ url(r'^$',views.comments_list, name="list"), url(r'^create/$', views.comments_create, name="create"), url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"), ] Views of create comment : @login_required(login_url="/userprofile/login/") def comments_create(request): if request.method == 'POST': form = forms.CreateComment(request.POST) if form.is_valid(): # save article to db instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('usercomments:list') else: form = forms.CreateComment() return render(request, 'usercomments/comments_create.html', { 'form': form }) Views of log out : def logout_view(request): if request.method == 'POST': logout(request) return redirect('/') <--- Where i get redirected when i press "create" else: pass Urls of … -
Django server is not running after added a new path function
I have created an app name 'calc' in Django and in the app, I have edited two files codes. urls.py from django.urls import path from . import views urlpattern = [ path('', views.home, name='home') ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Hello Django!") and finally, I have changed my directory folder's file urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ] now I am running the command on terminal: python manage.py runserver and it's giving me these below errors and not connecting to the server. terminal errors: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\shuvra\appdata\local\programs\python\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\shuvra\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File … -
Elastic Beanstalk - django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17)
Elastic Beanstalk with Python 3.6 and Amazon Linux 1. Django 3.0.7. Trying to create environment using eb create django-env, I get: Command failed on instance. Return code: 1 Output: (TRUNCATED)...backends/sqlite3/base.py", line 63, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). container_command 01_migrate in .ebextensions/02_setup.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. Have read that downgrading django would solve the issue, but I need a recent django version so that it works with django channels. Any straightforward way to upgrade SQLite? -
How to give permission to some user which allow only view one instance by one time?
I always want allow to check for all users view one instance by one time. But another function like get(list)\post\patch\update\delete only for user which have got general perm for this actions. class IsCardAccess(BasePermission): def has_permission(self, request, view): has_perm = False if request.user and request.user.is_authenticated: if request.user.has_perm_extended(PERM_CARD_ACCESS): has_perm = True elif request.user.has_perm_extended(PERM_CARD_SUPER_ACCESS): has_perm = True return has_perm In this way user without PERM_CARD_ACCESS and PERM_CARD_SUPER_ACCESS can't do anything, but when PERM_CARD_ACCESS user can do all of this actions (get\post\patch\update\delete). I don't understand what I need to do. Anyone have any ideas? -
How to store Advance Python Scheduler Job on my database
I am trying to create various scheduling tasks to manage objects and store these jobs as a Django model on postgres and manage them through admin panel. Could anybody please help me. Thanks in advance. -
Django pagination not showing links to other page links
I am following a django book to learn django.I tried implementing pagination on a differnt website,it worked.But it's not working in my fyp.Each page has 3 objects as specified by me but the links to change pages are not appearing. My views.py:- from django.shortcuts import render from .models import song_thumb from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from django.views.generic import ListView # Create your views here. class SongListView(ListView): model=song_thumb context_object_name='artists' paginate_by=3 template_name='home.html' my template: {% block content %} <form class="" action="mediaplayer.html" method="get"> <div class="data-content"> {% for artist in artists %} <div class="container"> <div id="img-1" class="tabcontent"> <div class="blog-content"> <div class="row"> <div class="col-sm"> <div class="card" style="width: 18rem;"> <div class="img"> <img class="img-thumbnail" src="{{ artist.img.url }}" alt=""> </div> <div class="card-body"> <div class="title"> <p>{% trans 'Artist:' %} {{artist.artist}} </p><br> <p>{% trans 'Title:' %} {{artist.song_title}}</p><br> <p>{% trans 'Album:' %} {{artist.album}}</p><br> <p>{% trans 'Duration' %} {{artist.song_duration}}</p><br> </div> <audio controls> <source src='{{ artist.song.url }}' type="audio/mpeg"> Your browser does not support the audio element. </audio> </div> </div> </div> </div> </div> </div> </div> {% endfor %} </div> </form> {% include "pagination.html" with page=page_obj %} {% endblock %} my pagination.html: <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page.number }} of {{ page.paginator.num_pages …