Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django reload data from model.py
Im working on a Django project and I want to dynamically load images to the page. the images are create each 10 mins. The problem is that when I do f5 or crl f5 to reload the page and check the new image is not there, then I check the list of images and also is not updated, only when I crtl+s the models.py file the page get the new image (no changes are made). This is how i get the list of images in the folder: models.py file: class ItemsFolder(): files_folder=os.listdir('C:/Users/Documents/TestImages/') class Folder(Page): ##other variables## files_folder=ItemsFolder().files_folder and my template.hmtl {% for card in page.files_folder %} <div class="col-md-4 d-flex align-items-stretch"> <div class="card mb-3 text-center"> <a href="{{ card.url }}"> <picture> <img src="{% static card %}" alt="{% static card %}"class="lazy card-img-top"> </picture> </a> </div> </div> {% endfor %} -
Pagination in django. I am unable to seperate Pagination from sidebar
I know where I am getting wrong.. the whole template is turning out in paginated version..but i don't want it to happen over the sidebar. Guide me through please. My sidebar is in base1.html I am new in this. VIEWS.PY class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 HOME.HTML {% extends "blog/base1.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number … -
Images being left untracked
I've added plenty of pictures up to now but I never had an issue loading them until now. It seems no matter what picture I add to my project it just gets left as untracked/doesn't load... I tried the command echo -e "a\n*\nq\n"|git add -i as I seen in a post and the picture went from untracked to "Added" but it still didn't seem to fix my problem . I'm loading the image through background-image: url({% static 'dentist/img/bg-img/tooth.jpg' %}); I cleared my browser data restarted my editor and everything . The image is in the static folder under dentist/img/bg-img so i'm pretty sure my code is correct -
Django Url map with parameter
I am trying to create a web app, that allows you to access one item by a url like items/<str:id> and edit that item via items/<str:id>/edit. Everything worked fine since I tryed to create a form action with that url: <form action="{% url 'items' item_id 'edit' %}" method="POST"> (this form is contained into edit.html, which is the template rendered by my edit function) Of course the solution I came up with did not work at all, but I am wondering if there is a correct way to achieve this kind of form action. How would you do this? my edit function (views.py): def edit(request,id): item = get_item(id) if item is not None: if request.method == "POST": print(request.POST["content"]) return render(request, "webapp/edit.html", { "item_id": id }) Error returned: NoReverseMatch at /webapp/it1/edit/ Reverse for 'webapp' with arguments '('it1', 'edit')' not found. 1 pattern(s) tried: ['webapp\\/(?P<id>[^/]+)$'] I hope I'm making myself clear, I'm new to django. -
Data is being changed to FLOAT or leading zeros being DROPPED from the uploaded file
I am trying to upload file using a Django front end page on the server. When I see the uploaded file on the server or display it on Django front end page, I see that zip codes are either becoming float or leading zeros from the zip codes are being removed. Case 1. Conversion to FLOAT. Input Data:- Jhon,, Jeff, 0011, Berry, 012, Output Data:- Jhon Jeff 11.0 Berry 12.0 Case 2. Leading zeros being removed. (Note in case 2, there are no null zip code rows.) Input Data:- Jeff, 0011, Berry, 012, Output Data:- Jeff 11 Berry 12 Since in the US, zip codes should contain leading zeros and a three digit zip code is invalid. It is crucial for me to keep the zeros. Is there any solution to this problem? On html page. I am simply using following options. <form method="post" enctype="multipart/form-data" action="{% url "my_upload_url" %}"> <input type="file" id="browse" name="myfile"> <button id="upload" type="submit">Upload</button> </form> On back-end I am receiving the uploaded file using below. myfile = request.FILES.get('myfile', None) Any help will be great since I am not able to find workaround to this issue. Thanks. -
How to access to a class method from request django
i am trying to access a class method that is already build from a request which came from angular, but i dont know how to do it: This is my request, which is working fine: @api_view(['POST', 'GET', 'PUT']) @permission_classes([AnonymousRequired]) @renderer_classes([JSONRenderer]) def password_reset(request, format=None): return Response(proceso(request)) def proceso(request): view = PasswordReset.as_view() resp = view(request) resp.post(request) I want to access to POST method to send the request: class PasswordReset(PasswordResetView): def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): if Users.objects.filter(email=self.request.POST['email']): return self.form_valid(form) else: return JsonResponse({'success':False, 'response':['El Email seleccionado no corresponde a ninguna cuenta asociada.']}, safe=False) #self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): sus = {'success':True, 'msj':''} try: super().form_valid(form) except: sus = {'success':False, 'msj':'Ocurrió un error inesperado al enviar el Email'} return JsonResponse(sus, safe=False) Any help with this? Thanks! -
Can't get list of checkboxes (Django) from HTML
HTML : ALB<input type="checkbox" name="iso_code" checked value="ALB"> BEL<input type="checkbox" name="iso_code" value="BEL"> BGR<input type="checkbox" name="iso_code" value="BGR"> <input type="submit" value="Submit"> In views.py: desired_iso = request.POST.getlist('iso_code') It returns a blank list, but I am calling the same name property. It seems that Django doesn't get POST request. I've tried with tag, then tried to replace name value like iso_code[]; Still can't figure out the bug -
Django reverse lookup to get latest
I have a model structure as below, ACTIVE_STATUS = ['waiting', 'loading', 'starting', 'running', 'stopping'] INACTIVE_STATUS = ['stopped', 'finished', 'failed', 'lost'] ALL_STATUS = ACTIVE_STATUS + INACTIVE_STATUS class Task(models.Model): name = models.CharField(max_length=20) class Job(models.Model): task = models.ForeignKey(Task, related_name='jobs') timestamp = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=zip(ALL_STATUS, ALL_STATUS), max_length=20) How can I annotate the "latest timestamp and its status" into Task queryset? I have managed to obtain the latest timestamp by, Task.objects.annotate(latest_ts=models.Max(models.F('job__timestamp'))) So, how can I get the corresponding status? -
Is there a way in which I can pass a template variable to a class in python django
I have a class based view in Django in which I am using a session wizard view.... I am trying to add a variable from a template into this class. How can I do that as it's quite easy to do it in a function based view but I need it for a class -
nginx gives 502 error with uwsgi for running django on ubuntu 18.04 LTS
Note: I am new to django and its deployment and need an urgent help. Deployed django through uwsgi and nginx according to the steps mentioned in this guide - https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html except the emperor-vassal configuration and without any virtual environment. Side note: The site comes up using python3 manage.py 0.0.0.0:8800 But, it seems that nginx is facing permission issues in the socket and giving a 502 bad gateway error in the browser. The nginx error log shows the following error: 2020/07/08 21:05:40 [crit] 3943#3943: *3 connect() to unix:///home/ubuntu/deploymenttst/MySite/MySite.sock failed (13: Permission denied) while connecting to upstream, client: 192.168.12.12, server: 192.168.12.12, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///home/ubuntu/deploymenttst/MySite/MySite.sock:", host: "192.168.12.12:8400" The configuration are as follows: In settings.py file of the project, the configuration are set as (apart from the default wsgi): DEBUG = False ALLOWED_HOSTS = [ "192.168.12.12" ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') The MySite_nginx.conf file inside /etc/nginx/sites-available/MySite_nginx.conf has the following configuration entries: # MySite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///home/ubuntu/deploymenttst/MySite/MySite.sock; # for a file socket #server 127.0.0.1:8008; } # configuration of the server server { # the port your site will be served on listen … -
Django Model ManyToManyField ValueError: Cannot Alter Field
In models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class TweetLike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey('Tweet', on_delete=models.CASCADE) class Tweet(models.Model): content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) likes = models.ManyToManyField(User, related_name='tweet_user', blank=True, through=TweetLike) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.content class Meta: ordering = ['-date_posted'] When I run the python manage.py makemigrations and then python manage.py migrate, it gets this error. ValueError: Cannot alter field tweets.Tweet.likes into tweets.Tweet.likes - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields) I tried a few things, but it still gives the same error. Can someone help me? -
Django : enable CORS
I'm hosting an API on heroku. I try to use my API whith react native. I heard about CORS that I have to enable before using my API. I tried to do that. This is what I made : pip install django-cors-headers settings.py from corsheaders.defaults import default_methods from corsheaders.defaults import default_headers ... INSTALLED_APPS = [ ... 'corsheaders', ... ] 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', 'corsheaders.middleware.CorsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = list(default_methods) + [ 'POKE', ] CORS_ALLOW_HEADERS = list(default_headers) + [ 'my-custom-header', ] I import my changes. After that, impossible to access to my API. I get this error : at=error code=H10 desc="App crashed" I've already try to restart my app but it's not the solution ... Thanks by advance -
i have tried store the logs in file of a website in django, and i want to log the events in the web page
LOGGING ={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file','file2', 'console'], 'level':'DEBUG', 'filters': ['request'] } }, 'handlers':{ 'file':{ 'level':'INFO', 'class': 'logging.FileHandler', 'filters': ['request'], 'filename':'./logs/ourdebug3.log', 'formatter':'simpleRe', }, 'file2':{ 'level':'DEBUG', 'class': 'logging.FileHandler', 'filename':'./logs/ourdebug4.log', 'formatter':'simpleRe', }, 'console':{ 'level' : 'INFO', 'class': 'logging.StreamHandler', 'filters': ['request'], 'formatter':'request_format', }, }, 'formatters':{ 'simpleRe': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'request_format': { 'format': '%(remote_addr)s %(username)s "%(request_method)s ' '%(path_info)s %(server_protocol)s" %(http_user_agent)s ' '%(message)s %(asctime)s', }, }, 'filters': { # Add an unbound RequestFilter. 'request': { '()': 'django_requestlogging.logging_filters.RequestFilter', }, } } thanks in advance -
TypeError: '<' not supported between instances of 'Playlist' and 'Playlist' getting this error
def home(request): context = { '': Playlist.objects.all() } query = "" if request.GET: query = request.GET['q'] context['query'] = str(query) playlists = sorted(get_video_queryset(query)) context['playlists']=playlists return render(request, "video/home.html", context) i am trying to make a search bar all was working fine then I started working on a post creating page, then it just occured as shown -
Pytest and Django, proper method for creating module scoped fixtures
pytest module scoped fixtures that use the django test database are perplexing us. We want a fixture, that creates an entry in the database, once per test module. This works, but it's very clunky: import pytest @pytest.fixture(scope='module') def site(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): address = models.Address.create(..) site = models.Site.create(address=address, ..) yield site with django_db_blocker.unblock(): site.delete() address.delete() We've noticed that django_db_setup is required, because if this fixture is the first one called, the test database won't be set up and the fixture will be created in the non-test database! For complicated objects that have more than one or two related models, the fixture becomes very ugly. Is there a better way to do this? -
Can anyone help me with this django error?
I am a newbie in django when I tried to start my first project this error occurred. Can any anyone help me ??? I just added a URL in urls.py and made a views.py file and added an index function I am running django on android with termux When I start the server I get this fatal error Problem: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/django/urls/resolvers.py", line 581, in urlconf_module … -
django Auto Score in model
In my app i want to create three more class in the model one will be auto setting the base score and the second model class will be the score set by the reviewer while the third class will be where the final score is computed every time a new reviewer score. CHOICES = [('SEED' , 'SEED') , ('Early Stage' , 'Early Stage'),('Established Startup' , 'Established Startup') , ] SCORE = [('SEED' , '10') , ('Early Stage' , '20'),('Established Startup' , '30') , ] Class applicant (models.Model): Q1 = models.CharField ( max_length = 100 , choices = CHOICES , default = 'NA' , blank = False ) Q1 = models.CharField ( max_length = 100 , choices = CHOICES , default = 'NA' , blank = False ) "in this model i want to set the score for the submitted Q1 and Q2 by the Applicant based on SCORE dict and Auto Save to DB" Class Base_Score (models.Model): Q1 = Q1 = "in this model i want to set the defaults score in the Charfield" Class Reviewer_Score (models.Model): Q1 = Q1 = "in this model i want to compute the reviewers scores including the Base_Score as average" Class Commulitive_Score (models.Model): Com_Score … -
extra context in django generic ListView
So I have two models: Person and Family. a Person have only one family. Now I want to use a list view to display all the person along with family for each person, can someone tell me how can I do that? Below is my code models.py class Person(models.Model): name = models.CharField(max_length=100) class Family(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) father_name = models.CharField(max_length = 255) views.py class PersonListView(ListView): model = Person ********Thanks in advance -
Django annotate queryset with counting its members by condition
I have a model: class Event(models.Model): start_date = DateTimeField() end_date = DateTimeField() I want to count all events which are of the same day and include this count as annotation field daily_events to the each member of queryset. I want to solve this on database side for speed. My code so far: from django.db.models import F, Q, DateTimeField, Count from django.db.models.functions import TruncDate events = Event.objects.all() events = events.annotate( daily_events=Count('pk', filter=Q(start_date__date=TruncDate(F('start_date'))))) for event in events: print(event.daily_events) For example I have 4 events, and first 3 at the same day, so desired output should be: 3 3 3 1 but current output is wrong: 1 1 1 1 Any advices? -
Django javascript is properly linked but not working
js file: $(document).ready(function(){ console.log('hrllo') function loadDoc() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var app = new Vue({ el: '#root', delimiters: ['[[', ']]'], data: { "obj": JSON.parse(this.responseText) } }) } } xhr.open('GET', '{%url "fetchData"%}', true); xhr.send(); } window.onload = function () { loadDoc() document.getElementById('PostBtn').disabled = true; } function CreatePostPopUp() { document.querySelector('.postModalContainer').style.display = "block"; } function CreatePostPopUpClose() { document.querySelector('.postModalContainer').style.display = "none"; } function checkNull() { if ( (document.getElementById('id_title').value == "") || (document.getElementById('id_caption').value == "") ) { document.getElementById('PostBtn').disabled = true; } else { document.getElementById('PostBtn').disabled = false; } } $('input').keyup(function () { checkNull() }) }) Base.html: {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{%static 'Content/styles/ContentStyles.css'%}"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <script type="text/javascript" src="{%static 'funtionality/MainScript.js'%}"></script> <title>Document</title> </head> <body> <nav class="navbar navbar-expand-lg"> <div class="container"> <a class="navbar-brand dName">FadCloud</a> <button class="navbar-toggler" data-target="#my-nav" data-toggle="collapse" aria-controls="my-nav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div id="my-nav" class="collapse navbar-collapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <button onclick="CreatePostPopUp()" class="btn btn-primary btn-block" type="button">New Post</button> </li> <li class="nav-item"> <a class="nav-link" href="#" tabindex="-1" aria-disabled="true">Item 2</a> </li> </ul> </div> … -
Why Django code doesn't reflect in website
i made a simple code in django but the Charfield and URlField doesn't show which was given by admin. #index.html {%for des in des %} <a href="{{des.link.url}}">Click here</a> <p>{{des.txt}}</p> {%endfor%} #view.py from django.shortcuts import render from .models import destination def index(request): des = destination.objects.all() return render(request, 'index.html', {'des': des}) #models.py from django.db import models # Create your models here. class destination(models.Model): link = models.CharField(max_length=200) txt = models.CharField(max_length=100, default=False) The image of admin is show.. link and text is provided by admin Image shows the html code which doesn't appear in website. -
dynamic, scheduled push notifications using Celery (Django)
I have a model called Schedule which consists of a list of Task. Below is the json representation { id: 1, tasks: [ { id: 1, date: "2020-09-08", message: "xyz", }, { id: 2, date: "2020-09-10", message: "xyz", }, { id: 3, date: "2020-09-17", message: "xyz", }, ], }; So my question is how do I setup celery to intiate a task which notifies the user(Firebase push notifications) on all the respective dates for the given schedule (The schedules are generated dynamically! throught a GraphQL api) Any alternative technology is also welcomed (it should work with Django though!) -
Django custom 404 page not working as intended
I am trying to implement a custom 404 page into my Django app. I am hosting the site with apache. The HTML page 404.html is: <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>404 Not Found</title> </head> <body> This page does not exist </body> </html> My views.py has this view for the handler: def handle404(request, exception): return render(request, 'mainapp/404.html', status=404) My urls.py has this: from django.conf.urls import handler404 handler404 = views.handle404 All the other things on my site work, so what could be causing this to fail? -
Why My Code Is run after refreshing a form after submit. in django
My code is not worked successfully without refreshing I want To know how its worked successfully without refresh page ............................................................................................................................................................................................................. template.html template.html <form method="POST" action="{% url 'user_homeview:like_dislike_post'%}" class="like-form" id="{{i.id}}" > {% csrf_token %} <input type="hidden" name='post_id' id='post_id' value="{{i.pk}}"> <button id="like" class="like like-btn{{ i.id }}"> {% if request.user in i.liked.all%} <img src='{% static "images\like.png" %}' class="mt-2 settin"></button> {% else %} <img src='{% static "images\unlike.jpg" %}' class=" settin"> {% endif %} </button> <script> $(document).ready(function(){ $('.like-form').submit(function(e){ e.preventDefault(); console.log('Works done') const post_id=$(this).attr('id') console.log(this) console.log(post_id) const likeText=$(`.like-btn${post_id}`).click().image() console.log(likeText) const trim = $.trim(likeText) console.log(trim) const url =$('.like-form').attr('action') console.log(url) $.ajax({ type: 'POST', url:url, data:{ 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), 'post_id':post_id, }, success:function(){ console.log('success') $.ajax({ type:'GET', url:'http://127.0.0.1:8000/user_homeview/serilized/', success:function(response){ console.log(response) $.each(response,function(index,element){ console.log(index) console.log(element.content) if (post_id==element.id){ if(trim=='like'){ $(`.like-btn${post_id}`).html('like') console.log('unlike') }else if(trim=='unlike'){ $(`.like-btn${post_id}`).html('like') console.log('like') }else{ console.log('ooopss!') } } } )} }) }, error:function(error){ console.log('error',error) } }) } ); -
Django, how to set a filter based on a queryset?
I have a queryset given by three different models: class Sottocategoria(models.Model): name = models.CharField('Nome del sottoprodotto', max_length=30) class A(models.Model): codice_commessa=models.ForeignKey() prodotto=models.ForeignKey() sottocategoria=models.ForeignKey(Sottocategoria) class B(models.Model): quantity=models.ForeignKey() price=models.DecimalField() sottocategoria=models.ForeignKey(Sottocategoria) Now I have set the following for loop: for sottocategoria_id, totale in (B.objects.values_list('sottocategoria__id').annotate(totale=(Sum(F('quantity') * F('price')))): .... I have the need to filter sottocategoria__id in the models B, that are present in the model A. Ad example If I have in the model A sottocategoria equal to {'abc','abcd','abcdf'} and model B sottocategoria equal to {'abc','abcd','abcdf', '1234'}, in my for loop I want to filter only {'abc','abcd','abcdf'}.