Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django postgres full text search for keyword inside document
I am new with django. Can please any one help me how can i perform a certain text search inside some a any document that is saved using filefield in a django model. I am clueless at this point i can search in doc url for title and all but how do i do it for inside a doc file..I know someone awesome will help me. Thank you in advance. Appriciated. -
Django CMS get url of child pages
I am looking for a way to get the URLs of all the subpages of the current page. For example if I have the following page structure MainPage -- Subpage 1 -- Subpage 2 In the template file of the MainPage I would like to access the URLs to the subpages. -
Angular 2 HTTP GET returning URL null, not a CORS issue
I have an Angular2 App running that is attempting to make a call to my Django server. I have a function called getOffreById That makes the external API call and should return a list of objects. However, i've tried fiddling with a few of the HTTP headers, as well as playing around with some settings on my server, but I cannot figure out what is wrong. Any help in the matter would be much appreciated, I can provide any additional debug information. EXCEPTION: Response with status: 0 for URL: null error_handler.js:54 ErrorHandler.prototype.handleError error_handler.js:54 next application_ref.js:348:63 EventEmitter.prototype.subscribe/schedulerFn< async.js:93:34 SafeSubscriber.prototype.__tryOrUnsub Subscriber.js:234 SafeSubscriber.prototype.next Subscriber.js:183 Subscriber.prototype._next Subscriber.js:125 Subscriber.prototype.next Subscriber.js:89 Subject.prototype.next Subject.js:55 EventEmitter.prototype.emit async.js:79:52 NgZone.prototype.triggerError ng_zone.js:333:54 onHandleError ng_zone.js:294 ZoneDelegate.prototype.handleError zone.js:233 Zone.prototype.runTask zone.js:154 ZoneTask/this.invoke component.ts: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router/src/router_state'; import { Subscription } from 'rxjs/Subscription'; import { MyServiceService } from '../my-service.service' import { Router } from '@angular/router/src/router'; @Component({ selector: 'app-offres-entreprise', templateUrl: './offres-entreprise.component.html' }) export class OffresEntrepriseComponent implements OnInit { private subscription: Subscription; private offreIndex: number; items : any[] = []; check: boolean =false ; constructor(private route: ActivatedRoute, private myService: MyServiceService, private router: Router) { } offreProfile(id: number){ this.router.navigate(['/components/OffreDetail/', id]); } ngOnInit() { this.subscription = this.route.params.subscribe((params: any) => … -
Django, 2.0.4 path is not work, how to fix?
Today for the first time installed the 2nd version of django and in shock from this shit, took and removed the normal routing using url I know that there is a re_path but this is not it! In general, everything was done according to the instructions as django, but it does not work does not see any coincidences! error Using the URLconf defined in src.urls, Django tried these URL patterns, in this order: admin/ / ^media\/(?P<path>.*)$ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. main urs.py 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('admin/', admin.site.urls), path('/', include("someapi.urls")), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urls from my app from django.contrib import admin from django.urls import path from .views import handle_verification, send_message from django.conf.urls import include, url urlpatterns = [ path('', handle_verification, name='handle_verification'), path('send/<str:recipient>/<str:txt>/', send_message, name='send_message'), ] my views import random from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render, get_object_or_404, redirect from django.http import JsonResponse, Http404, HttpResponse import requests import json … -
Getting Error NoReverseMatch at detail_view
Error - NoReverseMatch at / Reverse for 'Detail_function' with arguments '('',)' not found. 1 pattern(s) tried: ['function\/(?P[0-9]+)\/$'] MY CODE urls.py urlpatterns = [ path('',views.HomeFunction, name= 'home_function'), path('function/<int:pk>/',views.DetailFunction, name='Detail_function'), ] models.py class Profile(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=100) def __str__(self): return self.name views.py def HomeFunction(request): form = Profile.objects.all() context ={'form':form} return render (request,'home_function.html',context) def DetailFunction(request,pk): form=get_object_or_404(Profile, pk=pk) return render(request,'detail_function.html',{'form':form}) templates home_function.html {% for i in form %} <ul> <li><a href="">{{i.name}},{{i.gender}}</a> </li> </ul> {% endfor %} detail_function.html <ul><li>{{form.name}} | {{form.gender}}</li></ul> BUt when im adding {% url 'Detail_Function' object.pk %} in home_function.html like below {% for i in form %} <ul> <li><a href="{% url 'Detail_function' object.pk %}">{{i.name}}, {{i.gender}}</a> </li> </ul> {% endfor %} its throwing NoReverseMatch at / Reverse for 'Detail_function' with arguments '('',)' not found. 1 pattern(s) tried: ['function\/(?P[0-9]+)\/$'] showing error at Please be guiding me,Thanks in advance -
Feed javascript parameter with django model value
I am working on a website with Django, and I want to include a 3D viewer (three.js) which read an object file selected by the user. So, I get all 3D objects files via a call from my Django model in the template: HTML body {% for 3dobj in 3dobj _list %} <li>{{ 3dobj.path}}</li> {% endfor %} And then, I would like that by selecting one object of my list, it will feed my javascript function with the path "/media/3D_object_1.obj" JS var onLoadMtl = function ( materials ) { objLoader.setModelName( modelName ); objLoader.setMaterials( materials ); objLoader.getLogger().setDebug( true ); objLoader.load( '/media/3D_object_1.obj', callbackOnLoad, null, null, null, false ); }; How could I do that ? Many thanks for your help :) -
How to install python3 and Django using userdata in AWS EC2 with aws cli boto3
I need to install python3 and django via user data on EC2 instances. I know I can do it with Cloudformation or directly on EC2 but I need to install and deploy it via user data. I am creating the VPC and autoscaler but I need to automate the install and deployment of python3 and django automatically. Here is what I have but it doesn't seem to work. UserData="""#!/bin/bash yum install httpd php php-mysql -y echo y | sudo yum install python36 python36-virtualenv python36-pip sudo pip install --upgrade pip python3 -m venv venv source ./venv/bin/activate pip install django pip install --upgrade pip yum update -y service httpd start chkconfig httpd on adduser Eteram I have tried enclosing them in the double quotes but still doesn't work. I am basically trying to install python3 and django and deploy a test application to be able to go to the django admin url. -
Django 2.0 URLs: Configuring urls.py file
I am a beginner and I have problems with urls, I have a project, in the project i've created an application called "contacts", in the application, I created a folder "views", in this folder i have a file "index.py" the contents of my urls.py file is as follows: from django.urls import * from django.contrib import * urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^index$', include('contacts.urls')), re_path(r'^$', contacts.views.index.page), ] when I run ./manage.py runserver 0.0.0.0:8080 I get this error : File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ImportError: No module named 'contacts.views.index.page'; 'contacts.views.index' is not a package Thanks !! -
Django Rest Framework list and detail view overlap
My API is going to list a bunch of episodes of a podcast. The list itself should be stripped down and not have a lot of data to be small enough to pull the whole list at once. Here's my DRF serializer class class EpisodeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Episode fields = ('url', 'id', 'title', 'subtitle', 'show_id', 'published_at', 'updated_at') This works just fine using this view class EpisodeViewSet(viewsets.ModelViewSet): queryset = Episode.objects.all().order_by('-published_at') serializer_class = EpisodeSerializer The `HyperlinkedModelSerializer' also links the episodes to their own detail views but obviously uses the same view by default. Now what I want is to be more detailled on the detail view so what I did was: router.register(r'episodes', views.EpisodeViewSet) router.register(r'episode', views.EpisodeDetailViewSet) added this route and made a new view class EpisodeDetailViewSet(viewsets.ModelViewSet): queryset = Episode.objects.all().order_by('-published_at') serializer_class = EpisodeDetailSerializer and the serializer using additional models for more details class EpisodeDetailSerializer(serializers.ModelSerializer): chapters = ChapterMarkSerializer(source='chaptermark_set', many=True) media = MediaClipSerializer(source='mediaclip_set', many=True) show = ShowSerializer() class Meta: model = Episode fields = ('url', 'id', 'title', 'subtitle', 'show', 'published_at', 'updated_at','description', 'show_notes', 'cover_image', 'updated_at', 'chapters', 'media') depth = 1 Now this basically works for each Episode now using the /episode/123 format but it also renders all episodes with full details under the /episode URL … -
how to use ArrayField with ImageField in rest framework
i have a list of images for a every object, but can not use it. models: from django.contrib.postgres.fields import ArrayField class MyModel(models.Model): national_card = ArrayField( models.ImageField(upload_to=directory_path), blank=True, null=True, ) serializer: class MyModelSerializer(serializer.ModelSerializer): class Meta: model = MyModel fields = '__all__' database (column of national_card): { orders/2d4ba9ff-44af-44e9-9203-a0aad5a3c7ec/380cbbf0-1b73-4e36-996d-015c81dbaa71.jpg, orders/2d4ba9ff-44af-44e9-9203-a0aad5a3c7ec/380cbbf0-1b73-4e36-996d-015c81dbaa71.jpg } result of serializer: { "national_card": [ null, null ] } -
Django QuerySet FIlter based on previous QuerySet
This may be a simple answer but after days of searching I cannot seem to figure out the correct way to achieve this. I have a template where I want to show all the questions that are related to an assessment that has been assigned to a user. I thought that I could use the results from: ResponseDetails = AssessmentResponse.objects.prefetch_related('assessment').filter(id=response_id) by looking into the object and grabbing the assessment_id which I could then pass into the next query-set as a filter but I couldn't get that to work. Problem: Because the view doesn't filter based on the assessment_id found in the AssessmentResponse model, it gives me every question in the AssessmentQuestion model. An answer would allow me to actually have a good nights sleep trying to figure it out. Views def UpdateAssessmentResponse(request, response_id): ResponseDetails = AssessmentResponse.objects.prefetch_related('assessment').filter(id=response_id) QuestionList = AssessmentQuestion.objects.all() ChoiceList = AssessmentQuestionChoice.objects.all() context = { "ResponseDetails":ResponseDetails, "QuestionList":QuestionList, "ChoiceList": ChoiceList, #"ID" : ID, } return render(request, "assessment/assessment_response_update.html", context) Template {% if QuestionList and ResponseDetails%} {% csrf_token %} {% for question in QuestionList %} <p> {{ question.question_text }} </p> {% for choice in ChoiceList %} {% if choice.question_id == question.pk %} <fieldset id="group1"> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" name="choice" id="choice{{ … -
django timezone is taken as UTC even though I have set it to 'Asia/Kolkata'
here is my timezone settings in settings.py TIME_ZONE = 'Asia/Kolkata' # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = 'en-us' # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id SITE_ID = 1 # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n USE_I18N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n USE_L10N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz USE_TZ = False now when I use timezone.now(), I am getting UTC time always. Did I miss something -
Cant find admin:......_......_changelist django
I am just learning django at the moment and am doing a tutorial on how to create a calendar app (https://alexpnt.github.io/2017/07/15/django-calendar/) and am having trouble when trying to find the admin:bookings_Bookings_changelist path on line 37 and 38 of my admin.py file (screenshot linked below) admin.py The current syntax i found online through documentation is "app_label"_"model_name"_changelist, which i am following, however, i still get the error telling me: Reverse for 'bookings_Bookings_changelist' not found, and that it is not a valid view function or pattern name. Any help would be appriciated Thanks -
Iterating a dict->list->dict->list->dict data structure
I have a complex data structure which represent a n-dimensional dictionary of lists of dictionary of lists categories. And For every child I have to make an of the name of the category. Books: Comedy: sth: sth else: n times: Potatoes: recursively n time s <ol>Books:</ol> <ol>Comedy:</ol> <ol>sth:</ol> <ol>sth else:</ul> n times: <ol>Potatoes:</ol> recursively n time s {'data': OrderedDict([('name', 'DEFAULT'), ('description', 'DEFAULT')]), 'id': 1, 'children': [{'data': OrderedDict([('name', 'BOOKS'), ('description', 'books')]), 'id': 2, 'children': [{'data': OrderedDict([('name', 'scifi'), ('description', 'scifi')]), 'id': 3, 'children': [{'data': OrderedDict([('name', 'Hegel'), ('description', 'asaddsaasd')]), 'id': 5}, {'data': OrderedDict([('name', 'marks'), ('description', 'marks')]), 'id': 4}]}]}, {'data': OrderedDict([('name', 'Kartofi'), ('description', 'asdasd')]), 'id': 6, 'children': [{'data': OrderedDict([('name', 'julti'), ('description', 'asasdsad')]), 'id': 7}, {'data': OrderedDict([('name', 'miti'), ('description', 'adsasdasd')]), 'id': 8}]}]} The {% for key in dictionary recursive %} doesn't work, because because depth goes like this dict->list->dict->list How Can I iterate this in Django? Is it possible to iterate it with Jinja2, or I have to pull of a good interpretation in the view? -
Making a CBV(CreateView) from django FBV with 2 models (Gangster/GangMember)
Hi Djangonauts I am new to Django please forgive any silly mistakes. Lets say I am trying to make this web-app that allows users to write about Gangsters (more like the post model)from around the world and from different time periods and I am trying to convert the below FBV to a CBV (CreateView) so I can have a easy to make (UpdateView) & (DeleteView). I am using 2 models in this post_create. Gangster and GangMember . Below is how the model looks models for Gangster class Gangster(models.Model): user = models.ForeignKey(User, related_name='posts') gangster_name = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) history = models.TextField() gangster_image = models.ImageField() # there are more attributes like "Post-like but ignoring them as they are not relevant here" def save(self, *args, **kwargs): self.slug = slugify(self.title) #for SEO on google searches super().save(*args, **kwargs) Now there is a model called GangMember which is a Foreign-Key of Gangsters. A user can add from 0 to 7 GangMember to their Gangster post(you'd be surprised some gangmembers were more popular than the main boss, super-hot blondes, superbad hitmen). model for Gangmember class Gangmember(models.Model): gangster = models.ForeignKey(Gangster, on_delete=models.CASCADE, related_name="ganglord") gangmember_image= models.ImageField(upload_to='images/', blank=True, null=True, default='') gangmember_name = models.CharField(max_length=100, default='') brief_description = models.CharField(max_length=1000, default='') … -
django-rest-framework hint:"type error:expect a primary key, but get a ‘dict’"
The questions has bothered me for several days.I have setup a program with django rest framwork. The front end program in 'vue.js'.When 'patch' the data in front end, the server shows '400'. And chrome 'console.log' function shows 'type error:expect a primary key, but get a ‘dict’. Followings are details: views.py class MenuConfigViewSet(viewsets.ModelViewSet): print("submitmenu has in") permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) lookup_field = "user_id" def get_queryset(self): return MenuInfo.objects.filter(user=self.request.user) def get_serializer_class(self): if self.action == 'list': return MenuInfoSerializer else: print("hello") return MenuSerializer models.py class MenuInfo(models.Model): user = models.ForeignKey(User, verbose_name="用户") app_id = models.CharField(default="", max_length=30, verbose_name="app_id", help_text="app_id") note = models.TextField(default="", verbose_name="备注", help_text="备注") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "菜单信息" verbose_name_plural = verbose_name def __str__(self): return self.user.username class Button(models.Model): name = models.CharField(default="", max_length=20, null=True, blank=True, verbose_name="菜单名称", help_text="菜单名称") menuinfo = models.ForeignKey(MenuInfo, related_name='button', blank=True, verbose_name="menuinfo") type = models.CharField(default="view", max_length=100, null=True, blank=True, verbose_name="菜单类型", help_text="菜单类型") data = models.CharField(default="", max_length=100, null=True, blank=True, verbose_name="数据", help_text="数据") note = models.TextField(default="", verbose_name="备注", help_text="备注") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "菜单详情" verbose_name_plural = verbose_name def __str__(self): return self.name class Thumb(models.Model): content = models.CharField(default="NULL", max_length=20, null=True, blank=True, verbose_name="图文详情", help_text="图文详情") menuinfo = models.ForeignKey(MenuInfo, related_name='thumb', blank=True, verbose_name="menuinfo") url = models.URLField(default="view", max_length=100, null=True, blank=True, verbose_name="链接", help_text="链接") note = models.TextField(default="", max_length=100, null=True, blank=True, verbose_name="备注", … -
Django Rest Framework relation Attribute error
I'm fighting to find my way into DRF and can't get related data into my endpoint. models.py class ChapterMark(models.Model): title = models.CharField(max_length=100, null=True) episode = models.ForeignKey(Episode, on_delete=models.CASCADE) start_time = models.CharField(max_length=20) class Episode(models.Model): title = models.CharField(max_length=100, blank=False) show = models.ForeignKey(Show, on_delete=models.PROTECT) serializers.py class ChapterMarkSerializer(serializers.ModelSerializer): class Meta: model = ChapterMark exclude = ('') class EpisodeSerializer(serializers.ModelSerializer): chapters = ChapterMarkSerializer(source='id') class Meta: model = Episode depth = 1 The error I'm getting is Got AttributeError when attempting to get a value for field start_time on serializer ChapterMarkSerializer. The serializer field might be named incorrectly and not match any attribute or key on the int instance. Original exception text was: 'int' object has no attribute 'start_time'. My guess is that the relation via source='id' just doesn't work but everything I found so far is pointing back to doing it that way. There's a many to one relationship between chapters and episodes (so each episode has many chapters). I'm sure I'm just missing an important part. -
0.0.4 has requirement requests==2.0.0, but you'll have requests 2.18.4 which is incompatible
I download django via pip3 and I believe I installed it successfully but got this error saying indeed 0.0.4 has requirement requests==2.0.0, but you'll have requests 2.18.4 which is incompatible. Could you point out what is wrong and how to fix it? Below is for your reference. XXXX-MacBook-Pro:~ xxxx$ pip3 install django Collecting django Downloading ttps://files.pythonhosted.org/packages/89/f9/94c20658f0cdecc2b6607811e2c0bb042408a51f589e5ad0cb0eac3236a1/Django-2.0.4-py3-none-any.whl (7.1MB) 100% |████████████████████████████████| 7.1MB 2.2MB/s Requirement already satisfied: pytz in /usr/local/lib/python3.6/site-packages (from django) (2017.2) indeed 0.0.4 has requirement requests==2.0.0, but you'll have requests 2.18.4 which is incompatible. Installing collected packages: django Successfully installed django-2.0.4 -
Django - allow manually setting auto_now attribute for Sub-class
I'm using Django 1.10 In our base model (that few model inherit from) we set class BaseModel(models.Model): created_at = models.DateTimeField(db_index=True, auto_now_add=True) now, in specific sub-class model I need to override it's save and update the 'created_at': class Item(BaseModel): title = models.CharField(max_length=200) identifier = models.CharField(max_length=15) def save(self, *args, **kwargs): existing_item = Item.objects.active_and_deleted().get( identifier=self.identifier) existing_item.created_at = now() super(Item, existing_item).save(args, kwargs) That updated instance created_at is 'None'. I've tried 'editable=True' but seems like Django 1.10 doesn't support that. Any idea? -
Django: testing with login_required
I am trying to test a post request on a view which has login_required. if i run this in the shell django: Client().post('/recipes/', {'name' : 'Matar Cauliflower ', 'mass_unit' : '', 'mass_quantity' : '', 'volume_unit' : '1', 'volume_quantity' : '50', 'pieces_unit' : '', 'pieces_quantity' : ''},follow=True).status_code I get: <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/login/?next=/recipes/"> How to pass the login credentials are tell that a user is logged in. -
Django Deferred Attribute operand error
I am getting the following error: unsupported operand type(s) for *: 'DeferredAttribute' and 'DeferredAttribute' in Django, when I am trying to use two variables as such: def MakeCalcs(a,b): varc = a*b return varC I think that this originates from the fact that when the model fields are being populated in sequence (i.e., a and b are being populated after the model already exits). My question is how do I use those model fields? is there some way to turn a deferred attribute into one that you can apply operations to? -
Django: Is there a way to address informally with "du"?
In contrast to English there are two different "versions" of how you can speak with others in German. You can use the formal, more impersonal "Sie" or the informal, more personal "du". So, while you just say "Can you help me?" in English, you could say Können Sie mir helfen? (formal, when you don't really know the person) Kannst du mir helfen? (informal, when you know the person already) in German. My problem now is that for my Django application I would like to use the second version ("du") because it just suits much better for my web application. Thing is that Django (what I know?) just supports the formal version and now I have inconsistencies in the web application. Sometimes, there you can read "du" and sometimes "Sie" (from the default Django translations). Of course, I could remove my manually added sentences with "du", but I do not like it because the web page will be for people who know each other. My two questions: Is there a way to let Django use the informal translation that I perhaps have missed? In case Django does not provide this feature, is there a way to let Django support it (I … -
Django ajax redirect opening in same div
I'm using Django 2.0 I am making Ajax request to FormView to render template inside <div> and want to redirect in certain case. <script> function loadNextQuestion() { $('#question-box').load("{% url 'learn:question' course_learn.pk %}?session="+$('#session-id').val(), function(){ // other stuffs }); } </script> and the view is like class LearnQuestion(FormView): form_class = SessionForm template_name = 'learn/learn_question.html' def get_context_data(self, **kwargs): context = super(LearnQuestion, self).get_context_data(**kwargs) course_learn = CourseLearn.objects.get(pk=self.kwargs['course_learn_id']) session = self.request.GET['session'] question, question_type, options, complete = CourseLearn.objects.get_next_question(course_learn, session) if complete: context['complete'] = complete context['course_learn'] = course_learn context['session'] = session return context context['question'] = question context['question_type'] = question_type context['options'] = options context['course_learn'] = course_learn context['session'] = session context['complete'] = complete return context def render_to_response(self, context, **response_kwargs): if context['complete']: return redirect(reverse('learn:success', kwargs={ 'course_learn_id': context['course_learn'].pk, 'session': context['session'] })) return super(LearnQuestion, self).render_to_response(context, **response_kwargs) which renders learn/learn_question.html template inside question-box <div> but redirects when context['complete'] is True This works good but on redirect, the template of redirected URL is rendering in same <div id="question=box"> How can I redirect to a complete new page instead of rendering in same <div>? -
How to pass django model field to function and have variables returned to context for use in template
I have some values that I collected from users in a form, which are saved to the DB. I want to take these values, perform an operation on them in function, and then return them so that I can use them in them alongside the other context. Here is my model: #models.py file class MyModel(models.Model): varA = models.PositiveIntegerField() varB = models.PositiveIntegerField() varC = models.PositiveIntegerField() And here is the outside function that I am using: #makecalc.py def MakeCalc(varA, varB, varC): #simplified from what I am actually doing varD = varA*varB**varC varE = varA+varB+varC return varD, varE And here is the views.py file: #views.py file from .makecalcs import MakeCalc class MySummary(DetailView): model = MyModel def get_vars(self): varD, varE = MakeCalcs(varA, varB, varC) #Am I passing this correctly? return varD, varE #How do I send these to context? And finally the html: <p> you input: {{MyModel.varA}}</p> <p> you input:{{MyModel.varB}}</p> <p> you input:{{MyModel.varC}}</p> <p> I output:{{varD}}</p> #how do I call this? <p> you input:{{varE}}</p> #how do I call this? So, my question is in the view, how do I add varD, varE to context so that I can use it alongside varA, varB, and varC from the model? -
Jinja2 Django Python groupby('attribute') custom sort of grouper
So I have a Jinja2 template that I am using with Django. I have set up a for loop that does a groupby('attribute'). Is there any way that I can do a custom sort of the grouper sets. Below is the template code. {% for group in data('attribute')|groupby('property') %} {{ group.grouper }} {% for item in group.list %} {{ item }} {% endfor %} {% endfor %} I would like to do something like: for group in data('attribute')|groupby('property')|CUSTOM ORDERING SCHEME GOES HERE I know that it is possible to do: for group in data('attribute')|groupby('property')|reverse So what I am thinking is maybe it is possible.