Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a permission via Django Rest API?
I would like to create a custom permission that return true / flase depending on whether the user is the author of a story or not and pass this information via the restAPI. So when the author is requesting a story where he is not author the permission returns "false" and i can access these information IsStoryOwner: "False"via my API. Something like this should be the result: "user": { "id": 35, "username": "HII", "user_permissions": [ IsStoryOwner: "False", ] } However i struggle to implement that. I wrote the following permission: class IsStoryOwner(permissions.BasePermission): """ Check if authenticated user is story author """ def has_object_permission(self,request,obj,**kwargs): if request.user.id == story.author: return True return False Than i integrated the permission in my UserAPI class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, IsStoryOwner ] serializer_class = UserSerializer def get_object(self): return self.request.user However the permission is not appearing in my API and the "user_permissions": [] remains empty. -
Firebase Mutilple Item Upload not working
I need help to upload mutiple images in firebase for files in local_image: cloud_img = "images/example" + str(random.randint(1, 18596)) storage.child(cloud_img).put(files, user['idToken']) imgurl = storage.child(cloud_img).get_url(user['idToken']) def Convert(string): li = list(string.split(",")) return li urllist = imgurl # print(Convert(urllist)) x = Convert(urllist) data = { "name": name, "email": email, "phone": phone, "password": password, "image": x } print(x) results = db.child("users").push(data, user['idToken']) I am using python to push data but images url is saving only single url in databse please help me to figure it out -
ElasticSearch Autocomplete cleaning suggestions Django
I'm trying to make an autocomplete search for an application. I use django-elasticsearch-dsl with elasticsearch 7.x Instead of searching through documents title, I prefer to use a bunch of searched term saved like Google (I presume) models.py class SearchedTerm(models.Model): text = models.CharField(max_length=120, unique=True) def save(self, *args, **kwargs): """ Force lowercase for text """ if self.text: self.text = self.text.lower() models.Model.save(self, *args, **kwargs) document.py # Analyzer for searched term indexing my_completion_analyzer = analyzer('my_analyzer', tokenizer=tokenizer('trigram', 'edge_ngram', min_gram=3, max_gram=20, token_chars=['letter', 'digit']), char_filter=['html_strip'], # remove html entities filter=["lowercase", "snowball"] ) @registry.register_document class SearchedTermDocument(Document): completion = fields.CompletionField( attr='text', analyzer=my_completion_analyzer, fields={'raw': fields.KeywordField()} ) class Index: # Name of the Elasticsearch index name = 'searched_term' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = SearchedTerm # The model associated with this Document # fields to index # fields = ['text'] # None as using completion with special analyzer Get some Autocomplete suggestions: from apps.search.documents SearchedTermDocument es = SearchedTermDocument.search().suggest( 'autoc', 'sail boa', completion={ 'field': 'completion', 'skip_duplicates': True }}).execute().to_dict() [suggest['text'] for suggest in es['suggest']['autoc'][0]['options']] I get: [u' sail boat ', u'18 sail boat', u'ie sail boat', u'sail boat', u'sail boat'] Excpected result: [u'sail boat', u'18 sail boat', u'ie sail … -
Django - can't loop through custom templatetag
I've created custom categories_tag templatetag as follows: from django import template register = template.Library() from ..models import Category @register.simple_tag(takes_context=True) def categories_tag(context): categories = Category.objects.all() return categories And now want to loop through this tag like: <h3>CATEGORIES</h3> {% for i in categories_tag %} <a href="">i</a> {% endfor %} But in browser doesn't seem anything. What can be wrong with my code ? -
Wagtail: Getting 404 when using django-allauth and Wagtail?
I'm trying to setup login, logout functionality following this tutorial. In there the instructor shows where to put the url(r'', include('allauth.urls')) however he puts it above this line,url(r'', include('wagtail_urls')) that I don't see in my urls file for my project app. Notice that his url path is empty '', but then he goes to localhost/login and get a loginpage, that acording to him is provided by Wagtail. I don't get that, but a redirct to a 404 error page. What should I do? My Wagtail site works perfect, I can create pages, snippets, etc. /mysite/urls.py: from django.conf import settings from django.conf.urls import include, url from django.urls import path from django.contrib import admin from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = urlpatterns + [ # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This … -
How do I get the text and img of the "div contenteditable" and save it on the server?
How do I get the text and img of the "div contenteditable" and save it on the server, and then paste its information from the server to another div with i use django? HTML: div class="text_area_input" contenteditable id="text_area"> </div> JS is put img to "div contenteditable" JS: -
How to push data from several HTML input fields to Django database
I have an application that uses around 20 input fields (type text and number, some select) to make some calculations on the client-site. I would then like to push this entire data on click of a submit button to my Django database into a single table/model. How to accomplish this? Do I have to transpose each input field into a html form and then grab all of the html input fields data within a single view? Additionally do I need Django forms at all if I don't need to render the forms from the backend instead just having them in my html template pre-defined? Is it smart to fire an AJAX call to trigger the view or is it more convenient to directly post the data to the backend? (So I would need to create a custom submit button?) My html looks like the following right now: <div class="formsBox" id="formsBoxConsideredRisk"> <div class="formLabel"> <p class="formLabel">Risk & Underlying</p> </div> <div class="formMain"> <div class="riskContainer"> <input type="number" class="formInputRisk" id="formInputriskInPercent"> <p id="riskPercentText" class="riskText">Risk in %</p> </div> <div class="riskContainer"> <input type="number" class="formInputRisk" id="formInputriskInFiat"> <p id="riskFiatText" class="riskText">Risk in $</p> </div> <div class="riskContainer"> <select name="Underlyings" id="underlyings"> <option value="Shares">Shares</option> <option value="Gold">Gold</option> <option value="Silver">Silver</option> <option value="Oil">Oil</option> <option value="Indices">Indices</option> <option value="Other">Other</option> … -
Young developer facing the multitude of frameworks. What to do?
Hello everyone in the community, I am a young developer in the last year of level 3 engineering and for more than 3 months I have seen several job offers in development just as varied as each other. I use the Django, React, Ionic frameworks and I have some knowledge in java, android, Bootstrap, PHP development. I would like to know what is the attitude to adopt when I find myself facing more and more variable demand requiring other knowledge such as angular, laravel, Hibernate, Spring boot, jQuery, symfony, mongo db, MSSQL, PostgreSQL and sometimes all this is found on the same job offer. Thank you -
Django REST framework catches redirects before URLs names
I have a strange issue: Django REST framework appears to steal my URLs on redirect, even when the URL names are in my urls.py file and are before the REST routers. This is my code: views.py: def project_delete_view(request, id): obj_project = get_object_or_404(Project, id=id) if request.method == "POST": obj_project.delete() return redirect('my-projects') context = { 'project': obj_project.id, } return redirect('my-projects') urls.py: from rest_framework import routers from django.urls import re_path router = routers.DefaultRouter() router.register(r'projects', ProjectViewSet) urlpatterns = [ path('private/my-projects/', my_projects_list_view, name='my-projects'), ] If I comment router.register(r'projects', ProjectViewSet) the redirect works fine. Hardcoding the URL (return redirect('/private/my-projects')) doesn't help. When I click 'delete' in my template and the view is called, I get redirected to /api/projects/36/delete/ , no matter what. The view gets called correctly and the project gets deleted, the issue is only the URL to which the view redirects after the .delete() function. -
How to i go live from localhost with python files??? it is not working just like other normal html php files
I tried uploading my website created with python in localhost with django framework, but it is not working but showing the directories. Usually when a website is developed in PHP, when we upload with the index files the hosting auto fetches which is not happening here. the site made with python has also the index.html file but i have it inside sub folders. So the summarized question is how to move my python website from local server to live? -
`Return` gives wrong json data in output
I am trying to send JSON data from a django rest framework API but the output is modified by the return Response The API: class TransportDirectoryAPIView(APIView): def get(self, request, format=None): state = request.GET["state"] city = request.GET["city"] data = pd.read_csv(r"Suppliers.csv", error_bad_lines=False) data = data.fillna("-") data = data[(data["State"]==str(state)) & (data["City"]==str(city))].reset_index().to_json(orient='records') print("data ", data) return Response(data) now the print gives the following output: data [{"index":296,"Id":297,"Company Name":"ABC","Contact Person Name":"ABC", "Primary Contact Number":"999", "Contact Number 1":9999, "Contact Number 2":"-", "Contact Number 3":"-", "Contact Number 4":"-", "Primary Email":"-", "Secondary Email":"-", "Address":"ABCDE","City":"ABC","Pin Code":"-","State":"ABC","Services":"SXYZYZYZ"},....] But when I check in Postman it seems like this: "[{\"index\":296,\"Id\":297,\"Company Name\":\"abc\",\"Contact Person Name\":\"abc\", \"Primary Contact Number\":\"9999\", \"Contact Number 1\":9999, \"Contact Number 2\":\"-\", \"Contact Number 3\":\"-\", \"Contact Number 4\":\"-\", \"Primary Email\":\"-\",\"Secondary Email\":\"-\",\"Address\":\"ABC\",\"City\":\"ABC\",\"Pin Code\":\"-\",\"State\":\"ABC\",\"Services\":\"XYZYXY\"},.. Why the backslashes are added to the output and how can I correct it ? -
How do i send the data of a form (retrieved from a function of an HTML page) to a function of another HTML page in Django/Python?
The sequence is: - The user fills the 'a' form in the 'A' HTML page.(URL: AppName/A) - The user is directed to 'B' HTML page with other forms to fill.(URL: AppName/A/B) In the python code, How do i send the data of the 'a' form (retrieved from the function corresponding to the 'A' HTML page) to the function corresponding to the 'B' HTML page in views.py ? Notes: I do not want to retrieve the data from the 'A' HTML page in the 'B'HTML page but in the function corresponding to the 'B' HTML page as the user goes from 'A' to 'B' HTML page. Thank you. -
How to make min() and F() work together in Django?
Python 3.7.7, Django 3.0.6 I have this method, that works: def Proliferate (): models.Token.objects.filter(amount__gte=2).update(amount=F('amount') + 2) I also have this method, that technically works: @staticmethod def Cull (): tokens = models.Token.objects.all() for token in tokens: token.amount = min(token.amount, token.county.max_population) token.save() However I assume that the second one is actually making one query for every line, making it extremely unoptimised. I'd like to convert the Cull method to be like Proliferate (which I assume that runs a single query, otherwise what's the point of update?). I've tried this: models.Token.objects.all().update(amount=min(F('amount'),F('county.max_population'))) But it complained that: '<' not supported between instances of 'F' and 'F' So I've browsed for documentation and sites, but I wasn't able to find a simple obvious way to do this. Note: please notice that the min() has to be run between token.amount itself, and token.county.max_population, i.e. from a different table. Here's the model: class Token (models.Model): county = models.ForeignKey(County, on_delete=models.CASCADE) amount = models.PositiveSmallIntegerField() -
what is the best way to add an upvoting function to django
I would appreciate if any one could help me out as i'm new to learning python django. this is my code, i would like someone to give me help, with implementing the best way to add an upvoting function to my code. I would like the user to vote on the post and show the count for each post on index page and detail page one vote per user. this is my code views def index(request): links = Link.objects.order_by('-posted')[:10] context = {'links': links} return render(request, 'links/index.html', context) def detail(request, link_id): link = get_object_or_404(Link, pk=link_id) return render(request, 'links/detail.html', {'link': link}) models from django.db import models from django.contrib.auth.models import User class Link(models.Model): submitter = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) url = models.URLField(blank=True) text = models.TextField(blank=True) votes = models.IntegerField(default=1) posted = models.DateTimeField(auto_now_add=True) edited = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Vote(models.Model): link = models.ForeignKey(Link, related_name='link_votes', on_delete=models.CASCADE) voter = models.ForeignKey(User, related_name='link_voter', on_delete=models.CASCADE) def __str__(self): return self.link.title urls from django.urls import path from . import views app_name = 'links' urlpatterns = [ # ex: /links/ path('', views.index, name='index'), # ex: /links/5/ path('<int:link_id>/', views.detail, name='detail'), # ex: /links/5/vote/ # path('<int:link_id>/vote/', views.vote, name='vote'), ] index page {% if links %} <ol> {% for link in links %} … -
Choices in inherited field
class WagonOptimal(models.Model): ... CAPACITY_CHOICES = [ (5, 5), (6, 6), (7, 7), (8, 8) ] capacity = models.IntegerField(null=True, blank=False, choices=CAPACITY_CHOICES) class WagonBelMix(WagonOptimal): BELMIX_CAPACITY_CHOICES = WagonOptimal.CAPACITY_CHOICES + [ (9, 9), (10, 10), (11, 11), (12, 12), (13, 13) ] Lets say i have something like above. Is it possible to change choices in inherited capacity field? (for BELMIX_CAPACITY_CHOICES). -
How to display the names instead of pk in the list viewset in Django Rest Framework?
I've designed an API to add songs and create a playlist. models.py: class Song(models.Model): title = models.CharField(null=False, blank=False, max_length=400) artist = models.CharField(null=False, blank=False, max_length=400) def __str__(self): return f"{self.title} by {self.artist}" class Playlist(models.Model): name = models.CharField(null=False, blank=False, max_length=100) songs = models.ManyToManyField('Song', blank=True, related_name='playlists') serializers.py: class SongSerializer(serializers.ModelSerializer): class Meta: model = Song fields = ['title', 'artist'] extra_kwargs = {'playlists': {'required':False}} class PlaylistSerializer(serializers.ModelSerializer): class Meta: model = Playlist fields = ['name', 'songs'] extra_kwargs = {'songs':{'required':False}} views.py: class SongViewSet(viewsets.ModelViewSet): queryset = Song.objects.all() serializer_class = SongSerializer class PlaylistViewSet(viewsets.ModelViewSet): queryset = Playlist.objects.all() serializer_class = PlaylistSerializer But when I do a get request on the Playlist, I get the results as the following: { "name": "Classic Hits", "songs": [ 1, 3, 4 ] } I want the songs' names to be displayed instead of their PKs in the playlist.How do I do that? -
AttributeError: type object 'Like' has no attribute 'like'
** how i solve this error i dont know In views.py", line 120, in likePost Like.like(post,user) AttributeError: type object 'Like' has no attribute 'like' ............................................................................................................................................................................... ** views.py #############Like def likePost(request): post_id=request.GET.get("likeId",'') print(post_id) post=Post.objects.get(pk=post_id) user= request.user like=Like.objects.filter(post= post,user= user) liked=False if like: Like.dislike(post,user) else: liked=True Like.like(post,user) resp={ 'liked':liked } response=json.dumps(resp) return HttpResponse(response,content_type="application/json") template.html <button type="button" class="btn-xs btn-info like btn-sm "id="{{i.id}}"> {% if i in liked_post %} <a href="{%url 'like_dislike_post'%}" style="color: white;" id="like_text">Liked</a> </button> {% else %} <a href="{%url 'like_dislike_post'%}" style="color: white;" id="like_text">Like</a> </button> {% endif %} $(".like").click(function(e){ var id=this.id;//$(this).attr(.id); var href=$('.like').find('a').attr('href'); console.log(href,id) e.preventDefault(); $.ajax({ url:href, data:{'likeId':id}, success:function(response) { if (response.liked) { $('#like_text').html("Liked") } else { $('#like_text').html("Like") } } }) }); models.py class Like(models.Model): user = models.ManyToManyField(User,related_name="linkingUser") post = models.OneToOneField(Post,on_delete=models.CASCADE) @classmethod def liked(cls,post,liking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.add(liking_user) @classmethod def liked(cls,post,disliking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.remove(disliking_user) # @classmethod # def def __str__(self): return str(self.post) -
from_db_value() missing 1 required positional argument: 'context'
Trying to create google login for django using googleapiclient and oauth2client. I am able to open home page, and getting redirected to google login successfully. Once after sign-in, it is redirecting to home page where I'm receiving this error. Reference link/tutorial views.py import httplib2 from googleapiclient.discovery import build from django.http import HttpResponseBadRequest from django.http import HttpResponseRedirect from .models import CredentialsModel from gfglogin import settings from oauth2client.contrib import xsrfutil from oauth2client.client import flow_from_clientsecrets from oauth2client.contrib.django_util.storage import DjangoORMStorage from django.shortcuts import render from httplib2 import Http def home(request): print("*****home*****") status = True if not request.user.is_authenticated: return HttpResponseRedirect('admin') storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() print(f"credential: {credential}") print(f"storage: {storage}") try: access_token = credential.access_token resp, cont = Http().request("https://www.googleapis.com/auth/gmail.readonly", headers={'Host': 'www.googleapis.com', 'Authorization': access_token}) except: status = False print('Not Found') return render(request, 'index.html', {'status': status}) ################################ # GMAIL API IMPLEMENTATION # ################################ # CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console> FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope='https://www.googleapis.com/auth/gmail.readonly', redirect_uri='http://127.0.0.1:8080/oauth2callback', prompt='consent') def gmail_authenticate(request): print("*****gmail_authenticate*****") storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() print(f"credential: {credential}") if credential is None or credential.invalid: … -
Configuring loggers in Django + django_extensions is overrides by django_extensions
I've built a server using Django, and I configured the logging of the server to have different logs for ERROR, WARNING, and INFO, and a log in the console (in INFO level). Until I added django_extensions to the modules of the project, everything worked fine, but now the INFO log configuration is not what I configured. I think that the configuration is overridden by django_extensions, but I can't find a place to change it back. The configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[{asctime}] [{levelname}]: {message}', 'style': '{', }, 'vv': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'info.log', 'formatter': 'verbose', }, 'error_file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': 'error.log', 'formatter': 'verbose', }, 'warning_file': { 'level': 'WARNING', 'class': 'logging.FileHandler', 'filename': 'warning.log', 'formatter': 'verbose', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file', 'error_file', 'warning_file'], 'level': 'DEBUG', 'propagate': True, }, }, } INSTALLED_APPS: INSTALLED_APPS = [ 'abc.apps.ABCConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django_user_agents', ] I'm using python 3.7.6, Django 2.2.9, django-extensions 2.2.9. -
Django query Many to Many fields and get queryset based on each filter
I have the following problem to filter my group table with its realizations so that I only get the data set that matches the filter settings. My models look like this: Group: class Group(models.Model): name = models.CharField(max_length=35) products = models.ManyToManyField('Product') subgroups = models.ManyToManyField('Subgroup') user = models.ForeignKey(User, on_delete=models.CASCADE) is_hidden = models.BooleanField(default=False) Subgroup: class Subgroup(models.Model): name = models.CharField(max_length=35) products = models.ManyToManyField('Product') order = models.IntegerField(null=True) is_hidden = models.BooleanField(default=False) Product: class Product(models.Model): name = models.CharField(max_length=35) is_hidden = models.BooleanField(default=False) Currently, my query returns all groups that match at least one of the filters, but I want to apply the filter per model. non_hidden_groups = Group.objects.filter(user=user, is_hidden=False).filter(subgroups__is_hidden=False).filter(products__is_hidden=False) The problem is that I get a queryset back that exclude groups that are not hidden, but for example contains subgroups that are hidden. I only want to exclude: all groups that are marked as is_hidden all subgroups in the group that are marked as is_hidden all products in the group that are marked as is_hidden all products in a subgroup in a group that are marked as is_hidden Has anyone an idea how to do this without converting the queries into a list? -
Running selenium chromedriver on heroku w/ django management command
I have already tried a few different things to figure out this issue. I try to run a custom django management command which is supposed to run a selenium task using chromedriver. However, when I run the command on heroku, I get the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/app/.heroku/python/lib/python3.6/subprocess.py", line 729, in __init__ restore_signals, start_new_session) File "/app/.heroku/python/lib/python3.6/subprocess.py", line 1364, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/app/../chromedriver': '/app/../chromedriver' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/games/management/commands/new_data.py", line 6, in handle updater = UpdateData() File "/app/games/management/commands/update_data.py", line 27, in __init__ self.browser = webdriver.Chrome(executable_path=self.path, options=self.options) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__ self.service.start() File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home Which leads me to believe that I must have … -
AJAX pagination in my Django project pointing to 'page not found'
My django app has a favorite section with a favorite list for the user to save favorite products in it. For now the user can navigate through the favorite list using regular Django pagination set on 5 items per page. But I want a smoother user experience and I want to use AJAX to display the content. views.py: def pagination(request): model = SavedProduct.objects.all() number_of_item = 5 paginatorr = Paginator(model,number_of_item) first_page = paginatorr.page(1).object_list page_range = paginatorr.page_range context = { 'paginatorr':paginatorr, 'first_page':first_page, 'page_range':page_range } if request.method == 'POST': page_n = request.POST.get('page_n', None) serializer = pagination_ser(paginatorr.page(page_n).object_list, many=True) return JsonResponse(serializer.data, safe=False) return render(request, 'register/ajax.html',context) urls.py: app_name = 'register' urlpatterns = [ path('pagination/', views.pagination, name='pagination'), ] ajax.html: <body> <div id="register_list"> {% for i in first_page %} <h2>{{i.sub_product.real_name}}</h2> {% endfor %} </div> {% for i in page_range %} <a id='fav_nav' href="{{i}}">{{i}}</a> {% endfor %} <script> $('#fav_nav').on('click',function(event) { event.preventDefault(); console.log('ok') var page_n = $(this).attr('href'); $.ajax({ type: "POST", url: "{% url 'register:pagination' %}", data : { page_n : page_n, csrfmiddlewaretoken: '{{ csrf_token }}', }, success: function (resp) { $('#register_list').html('') $.each(resp, function(i, val) { $('#register_list').append('<h2>' + val.name + '</h2>') }); }, error: function () {} }); }); </script> </body> But event.preventDefault() is not working, whenever I click on a … -
Popup Django with url
I want to create specific popup that also can be opened by URL. Let us say, there "example.com/gallery". On this page there are some small-sized pictures. As for now, I use JavaScript to open popup by clicking on picture, and redraw image in it. But I cannot open it by URL. So how to use URL to get to gallery page and and open exact popup. "example.com/gallery/picture-1" or "example.com/gallery?picture=1" -
OSError: [Error 24] Too many open files: || Slow Application
My app got too many requests to celery and each request basically opens a headless chrome using pyppeteer and does some operations. Now when i saw celery logs, following is the error i got. So, there were too many socket connections created which made the entire application slow (**VERY VERY SLOW).** Can someone please suggest a workaround to close all these open socket connections because i cannot afford to restart the machine as its in production. -
DRF what's the difference between serializers(many=True) vs ListField(serializer())
When should I use each of the following? * MySerializer(many=True) * serializers.ListField(child=MySerializer())