Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create Client Assertion JWT token when connecting to Azure AD?
My issue is that I'm not sure what to use to sign the JWT token to make Client assertion when sending back authorized code to the Azure AD to get access token. The supported auth method is "private_key_jwt". -
Django Group objects by foreign Key field value
class Publisher(models.Model): name = CICharField("Name", max_length=200, unique=True) description = models.TextField("Description", blank=True) class Category(models.Model): name = CICharField("Name", max_length=200, unique=True) description = models.TextField("Description", blank=True) class Book(models.Model): name = CICharField("Name", max_length=200, unique=True) description = models.TextField("Description", blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="books", blank=True, null=True) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, related_name="books", blank=True, null=True) I want to get all Books objects filter by publisher and group by Category. For eg. books = Books.objects.all().filter(publisher=1).group_by('category') Output be like, [ { category 1: [book1, book2, ...] }, { category 2: [book3, book4,... ] }, ] Can anyone tell me, How can I achieve that? Thank you. -
Django settings: auto detect ROOT_URLCONF value
I'm working on splitting my settings.py into generic and project-specific configurations, and I was wondering if there was a "Django" way to get the root url configuration for the "app", that is to say, can Django auto-detect the app name such that I can do something such as the following: from django.apps import apps ROOT_APP = apps.get_root_app() ROOT_URLCONF = f'{ROOT_APP}.urls' Or should I just settle for an environment variable approach: ROOT_APP = os.environ.get('DJANGO_ROOT_APP') ROOT_URLCONF = f'{ROOT_APP}.urls' -
Django's Custom Authentication Middleware & Authentication Backend
I'm writing a custom Authentication middleware that check the incoming requests for the "Authorization" key in the header, which contains a token. I'm using this token to check with a third-party (Microsoft Graph) for the validity of the user. MS Graph will respond with an object like below # the response object { '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity', 'businessPhones': ['xxx'], 'displayName': 'xxx', 'givenName': 'xxx', 'id': 'xxx', 'jobTitle': None, 'mail': 'xxx', 'mobilePhone': None, 'officeLocation': None, 'preferredLanguage': 'xxx', 'surname': 'xxx', 'userPrincipalName': 'xxx' } I then append this object to the request: request.custom_user = response.json() Now I want to design this to work just like Django's default authentication backend with proper group and permission. How can I work on a LazyObject to be able to check for user's group membership and permission? -
I'm trying to load map in div using same class in each row but unable to do that
We are rendering the data from django in html page. Then using the GET text function to get MAP Address and placed to the address option for marker(For reference Pls check the below Jquery). If i have 10 records in single page. In 1st record able to add the marker after that i coudn't do that. Can anyone help me out kindly find the attachements for reference. $(document).on('click','.google-map', function(){ var get_text = $(this).closest('.col').find('.map-address').text(); var split_text = $.trim(get_text); $(".map").googleMap({}); $(".map").addMarker({ address: split_text, // Postale Address title: split_text, }); }); {% for result in current_page %} {% ifchanged result.provider_npi and result.tax_id %} <div class="panel panel-default" id="panel{{result.id}}"> <div class="panel-heading" > <div class="panel-title"> <div class="col"> <div class="provider-addr-column border-right"> <div class="wow fadeInUp contact-info" data-wow-delay="0.4s"> <div class="section-title"> <p class="map-address"><i class="fa fa-map-marker"></i> {{result.address|title}} <span class="break"> {{result.city|title}}, {{result.state|upper}}, {{result.zip_code}}</span></p> <p class="morelocations"> <a data-toggle="modal" data-target="#map-details" data-url = "{% url 'prsearch:more_location' result.id %}" id= "mul_loc" class=" center-block more-locations">More Locations</a></p> </div> </div> </div> <div class="view-details"> <a href="#collapse{{result.id}}" data-toggle="collapse" href="#collapse{{result.id}}" aria-expanded="true" aria-controls="collapse{{result.id}}"> <button type="button" class="btn btn-outline-secondary rounded-0 mb-1 google-map slide-toggle">View Details</button> </a> </div> </div> </div> </div> <div id="collapse{{result.id}}" class="panel-collapse collapse " data-parent="#accordion"> <div class="panel-body"> <div class="view-content-details"> <div class="details-right"> <div class="col-maps" > <div class="map"></div> </div> </div> </div> </div> </div> </div> {% endifchanged %} … -
Django Rest, SessionAuthentication - CSRF token can be modfied?
I have a Vue SPA connecting to a Django Rest application, using Session Authentication (and I want to keep it that way). I use Axios, and set the instance like this: var instance = axios.create({ baseURL: API_URL, withCredentials: true, xsrfCookieName: "csrftoken", xsrfHeaderName: "X-CSRFTOKEN", }); It is all working and when I remove the csrf cookie in Developer Console, I am not allowed to do unsafe requests - perfect. It also does not work if I remove or add a character to the cookie. But, if I change the token manually to any string that has the correct length, like: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - it still works? I guess I have misunderstood something, what? -
How to show the price at the index (page home) in the form of 1.0 lac i.e 100000 as 1 lac
here is my models.py file class ProductPage(models.Model): item=models.CharField(max_length=100) price=models.IntegerField(null=True, blank=True) @property def price_tag(self): if price>=100000 or price<=9999999: price=price//100000 return self.str(price)+ 'lac' my view.py file. def product(request): object1=ProductPage.objects.all() return render(request,'item.html',{'object1':object1}) and index.html file... {% for i in object1 %} <tr> <td>{{i.id}}</td> <td>{{i.item}}</td> <td>{{i.price_tag}}</td> {% endfor%} In my admin panel price is in form of integer field i.e 100000 . I want to convert it into a form as '1 lac' at the display page . Please help me how to do? -
Cannot change the Django field from mandatory to optional input
Cannot change the Django field from mandatory to optional input I have a sign up form that requires the users to fill in their phone num. Then , now ,I want to change it from mandatory to optional .But it fails and makes it disable to submit the form .How to fix? The web is written in Django .I just want to change the field from mandatory to optional input HTML <div style="margin-bottom: 25px" class="input-group"> <span class="input-group-addon"><i class="fa fa-phone"></i></span> <input id="phone_no" type="text" class="form-control" name="phone_no" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" maxlength="8" placeholder="phoneno*"> </div> .... var form = $("#form_data")[0]; var data_item = new FormData(form); data_item.append("profile_img",document.getElementById("imgInp").files[0]) data_item.append("username",username) data_item.append("password",password) data_item.append("cnf_password",cnf_password) data_item.append("email",email) data_item.append("phone_no",phone_no) $.ajax({ method : "POST", url : "/signup/", enctype : "mutipart/form_data", processData : false, contentType : false, cache : false, data : data_item, success : function(response){ console.log(response) $("#loading").hide() if (response == "success") swal("Registration Saved Successfully", { icon: "success", button: "Ok", closeOnClickOutside: false, }).then(function() { location.href = "/signin/"; }); model.py class Signup(models.Model): phoneno=models.CharField(max_length=15,null=True,blank=True) view.py @csrf_exempt def signup(request): username=request.POST.get('username') email=request.POST.get('email') password=request.POST.get('password') phone_no=request.POST.get('phone_no') dob=request.POST.get('dob') gender=request.POST.get('gender') profile_img=request.FILES.get('profile_img') email_all=request.POST.get('email_all') phone_all=request.POST.get('phone_all') bio=request.POST.get('bio') if email_all=="false": email_all=False else: email_all=True if phone_all=="false": phone_all=False else: phone_all=True if Signup.objects.filter(username=username,).exists(): return HttpResponse("user_name_exists") elif Signup.objects.filter(email=email).exists(): return HttpResponse("email exists") else: if dob: user_obj=Signup(username=username,email=email,password=password,phoneno=phone_no,dob=dob,gender=gender,profile_image=profile_img,email_status=email_all,pwd_status=phone_all,bio=bio) user_obj.save() else: user_obj=Signup(username=username,email=email,password=password,phoneno=phone_no,gender=gender,profile_image=profile_img,email_status=email_all,pwd_status=phone_all,bio=bio) user_obj.save() … -
Django and React : Error Message " You need to enable JavaScript to run this app. " instead of Json
I'm new to React and I try to make Django Rest and react work together. I have a simple view : class StudentView(generics.ListCreateAPIView): queryset = Student.objects.all() serializer_class = StudentSerializer I try to fetch it from react with : useEffect(() =>{ fetch("http://127.0.0.1:8000/secretariat/get_student/", { method: 'GET', headers: { 'Content-Type': 'application/json', } }) .then( resp => resp.json()) .then( resp => setStudents(resp)) .catch(error => console.log(error)) }, []) When i check in browser network the response this is what i have : I dont think that i have a CORS Header problem but here my CORS settings. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'common_app', 'rest_framework', 'rest_framework.authtoken', 'allauth.account', 'rest_auth.registration', 'ldap', 'rest_auth', 'simple_history', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1' ) CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) I assume i'm doing something wrong but i have no clue. Thanks -
Running an App (Mayan EDMS) on Linux (Ubuntu) OS
I have an app installed on my pc. It is Django based. Its called: Mayan EDMS The link to install it on Linux is: https://docs.mayan-edms.com/chapters/deploying.html I was able to successfully install it by following their guide. But I cannot run the app. Please help. -
Showing the result of "python manage.py test" inside template
I am writing views.py function which it should return "python manage.py test" and render it to the template views.py @login_required def Test_Case(request): output = os.popen("python manage.py test").read() return render(request, 'Test-Case.html',{'output':output} ) above code return nothing but when i do @login_required def Test_Case(request): output = os.popen("dir").read() return render(request, 'Test-Case.html',{'output':output} ) it work fine , is there any idea how can i do that thanks for your help -
How to unittest uploading a file
I have a User model and a usercreation form. I wrote a unittest to test if the form validates. I also would like to validate if a profilepicture has been uploaded to the form. This is the model: class User(AbstractUser): profilepicture = ImageField(verbose_name="profielfoto", upload_to='profielpictures') This is the test: from django.contrib.auth.forms import AuthenticationForm import pytest from aegir.users.forms import UserCreationForm from aegir.users.tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestUserCreationForm: def test_clean_username(self): # A user with proto_user params does not exist yet. proto_user = UserFactory.build() form = UserCreationForm( { "email": proto_user.email, "first_name": proto_user.first_name, "last_name": proto_user.last_name, "password1": proto_user._password, "password2": proto_user._password, } ) assert form.is_valid() # Creating a user. form.save() Any ideas how the test the uploading of the profilepic? Thanks in advance. -
varchar column type in cassandra cqlengine
How to define a varchar field in my django cassandra model. I have the model as follows from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class ChatEvent(DjangoCassandraModel): interview_id = columns.UUID(partition_key=True) fire_time = columns.DateTime(primary_key=True, clustering_order="DESC") id = columns.UUID(primary_key=True) type = //to be varchar type data = columns.Text(required=True) created_by = columns.UUID(required=True) this documentation lists all possible data types but it does not have a varchar type https://docs.datastax.com/en/drivers/python/2.5/api/cassandra/cqlengine/columns.html#:~:text=Columns%20in%20your%20models%20map,one%20non%2Dprimary%20key%20column. -
How to scale Heroku Django Celery app with Docker
I'm trying to deploy my Django app to Heroku and i have several doubts about dynos, workers and deploy configuration. In my heroku.yml file I have 2 types of processes, one for the web and the other for celery, I would like them to both have only 1 dyno but with several workers and to be scalable if necessary. heroky.yml: build: docker: web: Dockerfile-django celery: Dockerfile-django run: web: gunicorn project.wsgi --log-file - celery: celery -A project worker -B --loglevel=INFO Dockerfile-django: FROM python:3.7-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update && apk add --no-cache bash postgresql postgresql-dev gcc python3-dev musl-dev jpeg-dev zlib-dev libjpeg RUN mkdir /dilains COPY ./project /dilains/ COPY ./requirements.txt /dilains/ WORKDIR /dilains RUN pip install -r requirements.txt EXPOSE 8000 I tried scale with this commands to scale each process type with 4 workers: $ heroku ps -a app_name === celery (Standard-1X): /bin/sh -c celery\ -A\ project\ worker\ -B\ --loglevel\=INFO (1) celery.1: up 2020/10/23 08:05:31 +0200 (~ 41m ago) === web (Standard-1X): /bin/sh -c gunicorn\ project.wsgi\ --log-file\ - (1) web.1: up 2020/10/23 08:05:40 +0200 (~ 41m ago) $ heroku ps:scale web=1 worker=4 -a app_name $ heroku ps:scale celery=1 worker=4 -a app_name I'm paying Stardar-1X and tells: number of … -
Django messages not rendering properly
I am making a project in Django and want to render a styled message if a user fails to input their username/password correctly. The message does render, but it doesn't render using the CSS provided for it: ul.messages li.error{ border: 1px solid; margin: 10px auto; padding: 15px 10px 15px 50px; background-repeat: no-repeat; background-position: 10px center; max-width: 460px; color: #D8000C; background-color: #FFBABA; } I'm pretty sure doing ul.messages is overkill, but it's just something I tried. I've also tried .messages .error, .error, etc... The relevant template code: {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} Again, the message renders, just not with the relevant CSS. The message call looks like this: messages.error(request, "Login failed due to incorrect username/password") -
CSS static files are not working in Django, I am a beginner in Django and main.css properties are not being applied to my store.html
This is added in settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] urls.py from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', views.store, name="store"), ] urlpatterns += staticfiles_urlpatterns() views.py from django.shortcuts import render from django.template.context import RequestContext def store(request): context ={} return render(request, 'store/store.html',context) store.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <h3>store</h3> <img src="{% static 'images/cart.png' %}"> main.css body{ background-color: blue; } folder tree store->store->store.html static->css->main.css static->images->cart.png -
want to implement owl carousel but but but
I am trying to create a website using django and bootstrap. I am extending base.html into index.html. I have implemented navbar(from bootstrap) in base.html and want to implement owl carousel in index.html. Both base.html and index.html are in templates folder of my project. I tried placing css and js files like owl.carousel etc in <!-- THIS IS base.html--> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link rel="stylesheet" href="/static/css/owl.carousel.css"> <link rel="stylesheet" href="/static/css/owl.theme.green.min.css"> <script src="/static/js/jquery.min.js"></script> <script src="/static/js/owl.carousel.min.js"></script> <title>BURGERZONE-{% block title %} {% endblock title %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/"> <h1>BURGERZONE</h1> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/menu">Menu<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="/contact">Contact Us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Today's special </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="/about">About Us</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> … -
Django DRF access parent serializer instance in many=True
Tl;dr: I need to access instance of parent serializer in child one while serializing in many=True mode. In my Blog model, I have field tabs = JSONField (stores list of tabs, showed in blog) I have ModelSerializer like this: class BlogShortListSerializer(serializers.ModelSerializer): tabs = TabsSerializer(read_only=True) class Meta: model = Blog fields = ['id', 'name', 'type', 'tabs'] and TabsSerializer: class TabsSerializer(serializers.ListField): def to_representation(self, data): # Taking list (generated by base class ListField) res = super().to_representation(data) # Taking Blog from parent serializer blog = self.parent.instance # Taking user from request user = self.context["request"].user # If it's not alowed to user to see "peoples" tab, remove it before showing. if not is_user_able_to_see_peoples(blog, user): if "people" in res: res.remove("people") return res When I use BlogShortListSerializer on a single instance, everything working fine: return Response(BlogShortListSerializer(blog).data) But if I use it on many objects, it doens't work. return Response(BlogShortListSerializer(blogs, many=True).data) Because in second case blog = self.parent.instance doesnt put Blog object into blog variable it put a whole list of blogs that was supplied to BlogShortListSerializer constructor. I've debugged DRF code, and found that, when in many=True mode, serializer walks through list of supplied items, and call child.to_representation just attribute value, and instance not being stored anywhere … -
How to add custom view in django adminlte?
I created an environment using pycharm & installed adminlte by git clone from https://github.com/app-generator/django-dashboard-adminlte.git. And installed adminlte3 , django3.1 & all requirements. Then run python manage.py runserver and registered a new user & was able to login ,view all pages, added new link to a html page. But I am unable to add view with jsonresponse to a button click on new page, geting Error 500 - Server Error. My new html page is {% extends "layouts/base.html" %} {% block title %} Layout Boxed {% endblock %} <!-- Element injected in the BODY element --> {% block body_class %} sidebar-mini layout-boxed {% endblock body_class %} <!-- Specific Page CSS goes HERE --> {% block stylesheets %} <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> <!-- Font Awesome --> <link rel="stylesheet" href="/static/assets/plugins/fontawesome-free/css/all.min.css"> <!-- Theme style --> <link rel="stylesheet" href="/static/assets/css/adminlte.min.css"> <link rel="stylesheet" href="/static/assets/css/mapstyle.css"> <link rel="stylesheet" href="/static/assets/js/pages/gis/dist/map.css"> <style> .map { margin: 0; padding: 0; width: 900px; height: 500px; background:white !important; border:1px solid #ccc; } </style> {% endblock stylesheets %} {% block content %} <div class="content-wrapper"> <div id="lyrDiv"></div> <div id="map" class="map"></div> <button id="search">Search</button> </div> {% endblock content %} <!-- Specific Page JS goes HERE --> {% block javascripts %} <!-- jQuery --> … -
Why won't Django load my CSS files when I already used static?
I'm trying to create a website but idk why some of my CSS is not working on the page. I followed the format my teacher gave and his worked so idk why mine won't. in urls.py of the project: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('system/', include ('system.urls')), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in HTML file: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> in CSS file: .body{ background-color: yellow; } .title { color: #000; font-family: Arial Black; position: absolute; top: 0; left: 4%; } .list { color: #000; font-family: Arial; position: absolute; top: 10%; left: 10%; } When I python manage.py runserver, the page background is still white and the text is also white so I have to block them to see it. I tried to do the collectstatic but it gave a warning that it will overwrite existing files so I canceled it. My teacher also haven't taught us the collectstatic command. What am I doing wrong here? -
Why do my changes not save in static css files in django?
They used to save before, but all of a sudden they do not. I even have DEBUG = True and I have django.contrib.staticfiles in my installed apps. I'm not really what code I should provide, so if anyone needs any, please ask, and I'll send you the code. Thank You! -
How to send image from SketchCanvas to server
Application Image I use RNSkecthCanvas in React-Native then I want to send a drawing image to my server that use Django when I click save button in the bottom what keyword I have to search.I search then I see only how to upload image by select file in phone -
Trying to add a "add to wishlist button" in my Django web application
I'm trying to add an "add to wishlist" button to my page that lists books. When a user presses the button, it will add the isbn (pk of the books) along with the user id into the wishlist table. For some reason, it's not adding them into my database when I press the button. There are no errors shown so i don't know what's the problem. Here's my code #views.py class wishlistView(TemplateView): template_name = 'TextSearch/wishlist.html' def post(self, request, pk): isbn = self.request.POST.get('isbn') current_user = request.user book = wishlist(userid_id = current_user.id, ISBN_id = isbn) book.save() return my HTML code {% if user.is_authenticated %} <form method="post"> {% csrf_token %} <input type="hidden" value="{{book.pk}}" name="isbn"> <a href="{% url 'TextSearch:wishlist' book.pk %}" >Add To WishList</a> </form> {% else %} <a href="{% url 'User:RegisterView' %}" >Add To WishList</a> {% endif %} Thank You in advance, I'm new to Django. -
How to order by a field in an another model in Django
I have two tables here, one is called SystemPushLog and another called UserPermission, they are both have a user_id field with IntegerField. class SystemPushLog(models.Model): ... user_id = models.IntegerField(null=True) class UserPermission(models.Model): user_id = models.IntegerField(primary_key=True) expire_datetime = models.DateTimeField(null=True) # 会员过期时间 ... The reason why they are chosen IntegerField rather than an Foreignkey is bacause the User model is in another system. And we have to retrieve user info by gRPC remote function calls. So, we just save the user_id as an IntegerField. Now, I am stucking in how to order by expire_datetime field on another model UserPermission in queryset of SystemPushLog. The two table does not have relations except sharing the same user_id field. I have tried to implement using raw SQL like this: qualified_ids = [item.id for item in queryset] queryset = SystemPushLog.objects.raw("""RAW SQL IGNORED""") ordered_log_ids = [item.id for item in queryset] clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(ordered_log_ids)]) ordering = 'CASE %s END' % clauses queryset = SystemPushLog.objects.filter(id__in=ordered_log_ids).extra( select={'ordering': ordering}, order_by=('ordering',) ) # Now the queryset is ordered... But, it runs really slowly. Maybe it is because of clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in … -
Trouble using python dictionary in a Django template
So I have a python dictionary storing the size and the amount each size has, titled final_list. Then I'm passing that to the template using "sizes": final_list. In the html template, I'm trying to create a drop-down selection with all the sizes, and only display sizes that are available, or have an amount not equal to 0. The problem is, it seems as if it isn't accepting the dict or something, since the dropdown shows up empty. Below is the code I have, any help would be much appreciated. Views.py I'm getting the sizing info from a model called 'Size' then checking if there are 0 objects of that size. Then I'm creating the dictionary to only have sizes that are actually available. from django.template.defaulttags import register @register.filter def get_item(dictionary, key): return dictionary.get(key) def product(request, code): sizes = Size.objects.get(code=code) all_size = ['small', 'medium', 'large', 'XL'] final_list = {} for size in all_size: if getattr(sizes, size) == 0: pass else: final_list[size] = getattr(sizes, size) return render(request, "website/listing.html", { "sizes": final_list }) HTML (website/listing.html) <form method="POST"> <select name="sizes" style="width: 90px; height: 20px;"> {% csrf_token %} {% for size in sizes %} {% if final_list|get_item:size != 0 %} <option>{{size}}</option> {% endif %} {% …