Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Poor Django application degradation
I'm assigned to support an old Django application. This application used to run on gunicorn synchronous workers. However, it was getting slower. Recently, a engineer made a change to use gunicorn asynchronous workers with gevent. This week the system suffered a severe degradation when the number of HTTP requests increased. We received lots of error: can't start new thread on gevent.threadpool._add_thread. The Django view with most hits performs about 400 SQL queries before completing and renders a complex template. Could the elevated number of queries and CPU time to render the template be playing badly with this new async worker? And if so, how can I explain it to others? The connection pool is configured to not exceed the limit of postgres connections. -
How to refer to variables inside the hmtl template?
I have a beginners question. I followed a very quick tutorial on how to enter a data from a frame into database (http://www.learningaboutelectronics.com/Articles/How-to-insert-data-into-a-database-from-an-HTML-form-in-Django.php) <html> <head> <title>Create a Post </title> </head> <body> <h1>Create a Post </h1> <form action="" method="POST"> {% csrf_token %} Title: <input type="text" name="title"/><br/> Content: <br/> <textarea cols="35" rows="8" name="content"> </textarea><br/> <input type="submit" value="Post"/> </form> </body> </html> In the HTML above - I used name="title" and name="content" inside the views.py def createpost(request): if request.method == 'POST': if request.POST.get('title') and request.POST.get('content'): post=Post() post.title= request.POST.get('title') post.content= request.POST.get('content') post.save() return render(request, 'posts/create.html') else: return render(request,'posts/create.html') and that works perfectly, the data is entered into the database. Now I want to work with a free template I found on the internet. I have already edited the other parts of the HTML file, the remaining part is to work with the contact-form here below. The difference is they are using 'this.value' to pass the content of a field. Before I could distinguish between title and content, but now it's just one variable. How can I refer to that variable in my views.py ? The copy of the code of my interest is below. <div class="services_dark sj" id="signup"> <div class="container"> <h3 class="m_3"><center>Interested to join us?</center></h3> … -
FileSystemStorage doesn't work and when 2 images uploaded, SuspiciousFileOperation error is returned
I'm having a terrible issue. I want to upload 2 images and get a result after running them through a lot of code. However, when I choose the path (on the server) as to where to upload these files, I always get a "SuspiciousFileOperation" error. Thank you for your help! PS1: I'm using django as a back-end for my front-end so I need web services. PS2: This code was running fine before reinstalling Django and Python due to some tensorflow issues, but reinstalled all needed packages. Django version: 2.2.2 Python version: 3.6.7 (64-bits) #HERE IS THE VIEW import json import os from rest_framework import generics from rest_framework.response import Response from rest_framework import permissions from .ProcessData.FaceRecognition import FaceRecognition from .ProcessData.OCR import OCR from .ProcessData.Wanted import Wanted from identity.models import IdentityCheck from .serializers import IdentityCheckSerializer from rest_framework.generics import CreateAPIView from django.core.files.storage import FileSystemStorage from django.conf import settings class IdentityCheckView(CreateAPIView, generics.ListAPIView): serializer_class = IdentityCheckSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): request = self.request qs = IdentityCheck.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter(name__icontains=query) return qs def save_fss(self, filename, file): mediaRoot = os.path.join(settings.MEDIA_ROOT, 'media/tmp/') filename = filename + ".jpg" fs = FileSystemStorage(location=mediaRoot) if fs.exists(filename): os.remove(mediaRoot + filename) newFile = fs.save(filename, file) … -
Accessing many to many data in class-based detail view with models in different apps Django
I have two models related via ManyToMany relationship, but they are located in separate apps. I am trying to load details of one model then adding the manytomany field in the template but the conventional way is not working. Here is my code so far: models.py (listings app) from listing_admin_data.models import PropertyFeatures class Property(models.Model): .... property_features = models.ManyToManyField(PropertyFeatures) .... models.py (listing_admin_data app) class PropertyFeatures(models.Model): .... feature_name = models.CharField(max_length=50) .... views.py class PropertyDetailView(DetailView): model = Property context_object_name = 'property' Then in the template, I am trying to do this, but getting empty list, yet I have data. <h3>Property Features</h3> <ul class="amenities-list"> {% for feature in property.property_features.all %} <li>{{ feature.feature_name }}</li> {% empty %} <li>Property has no features!</li> {% endfor %} </ul> I tried this intentionally: <p>{{ property.property_features }}</p> And upon loading I get: listing_admin_data.PropertyFeatures.None on the browser. The other fields directly related to the object loaded are working fine, like {{ property.price }}, while those from ForeignKey are also working fine, i.e. {{ property.listing.listing_title }}. Is inter-apps model relationship handled the same way in Django or it has a special treatment? -
How to Unittest autocomplete.Select2QuerySetView (Django autocomplete light)
I'm Using the Django package Django Auto Complete light and here is how I use it: in the urls.py I use : path('buy-invoice-items-autocomplete/', views.ItemAutoComplete.as_view(), name='buy_invoice_items_autocomplete', ), then in the views.py : class ItemAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Item.objects.filter().order_by('id') if self.q: qs = qs.filter(Q(id__iexact=self.q) | Q(name__icontains=self.q)) return qs And finally i use it in my forms.py to let the user filter using it. Now when I try to include it in my unit tests file I do it this way : class TestItemAutoComplete(TestCase): def test_visit(self): self.client.get('/buy-invoice-items-autocomplete/') Using Coverage package it shows that my test is not covering the lines: if self.q: qs = qs.filter(Q(id__iexact=self.q) | Q(name__icontains=self.q)) How to reach this part in the class and test it ? -
Django Field is showing up in one view but not the other
I'm just starting out with Django and I have a problem where, when I added a field to my model (JobPost which inherits from models.Model) and it migrated successfully I can see and interact with the new field when I create a job post, but not when I view the JobPost (which is displayed using crispy forms using the {{ form|crispy }} tag. I have added the field name to my fields = [''] in my views.py models.py class JobPost(models.Model): #constants CLEARANCE_LEVELS=[(...),] author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() clearance_required = models.CharField(max_length=50, choices=CLEARANCE_LEVELS, default='None') date_posted = models.DateTimeField(default=timezone.now) views.py class JobDetailView(DetailView): model = JobPost class JobCreateView(LoginRequiredMixin, CreateView): model = JobPost fields = ['title', 'content', 'clearance_required'] # form_valid checks if the user is logged in def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) jobpost_form.html {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <!--Used to prevent some XSS Attacks (Cross-site request forgery) --> <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Job Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} So when I view it in my browser, I see the "clearance_required" field when I create … -
Execute alternative search in Django Rest Framework if object not found (404 error)
I'm prototyping something to learn more about fullstack development. On my website I have a search bar where users can search for podcasts. They first look into my database but if no item is found, I want to retrieve results from the iTunes API and display those (while at the same time saving those results in my database so that they are there for further searches). The frontend uses React while the backend uses Django Rest Framework. If the podcast is not in my database, a 404 is thrown. How can I catch the 404 exception before it's thrown and perform the search on iTunes? -
Job for gunicorn.socket not found
I am trying to setup gunicorn for my django website on the digitalocean but sudo systemctl start gunicorn.socket responds as "Job for gunicorn.socket failed". I have double checked for any spelling mistakes or directory path issues. I have been following this tutorial - https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 filepath = /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/home/myuser/profile_website ExecStart=/home/myuser/profile_website/myenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project2.wsgi:application [Install] WantedBy=multi-user.target filepath = /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target I have already tried restarting gunicorn.socket but it did not work. -
Query django postgres nested jsonfield
from django.contrib.postgres.fields import JSONField class Entity(Model): lang = CharField() data = JSONField() How can I query this model to find all objects that contain a given value. JSON can be nested. For example, if data is [ { 'name': 'Alfred', 'children': [{'name': 'Bob', 'children':['name': 'Melanie']}] }, { 'name': 'Harry', 'children': [{'name': 'Helen'}] } ] Then I want to return it if I search for Melanie. There can be any level of nesting. From the documentation Entity.objects.filter(data__values__contains=['Melanie']) doesn't work. -
How to share one Apscheduler Jobstore over 2 Django instances
I am running a Django App that creates 2 instances. I am using BackgroundScheduler to schedule a job and later remove it based on some conditions. Since there are 2 Django instances, the job still gets executed by the other instance. Is there a way to share a Jobstore over different instances so that I can still run 2 instances? -
Should UUIDFields be made unique and indexed in Django?
I have a model which has a UUIDField, that is not the primary key. The primary key is simply left as the default, a big integer field. import uuid class MyModel(models.Model): uuid = models.UUIDField(_('uuid'), default=uuid.uuid4, editable=False) Now my question is, should I explicitly declare the field to be unique? I realize the chance of collisions is very very small, which is probably why the Django documentation does not explicitly make the field unique. Also, should I also index the field in the database? Like so: import uuid class MyModel(models.Model): uuid = models.UUIDField(_('uuid'), default=uuid.uuid4, editable=False, unique=True, db_index=True) The field will mostly be used as an external identifier, where the id is generally not preferred. -
array don't Access in the tamplate
I want to known the number of views in each separately Playlist where I can store the view number for each one in the array and later display it in the tamplate but show me the array in the following in the tamplate: [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, … -
Auto save user in Django inline formsets with Class-based views and crispy forms
I am using Django inline formsets with Class-based views and crispy forms. Currently, I have a requirement in my project where a User can submit a request for a new Study Concept and any user in the Application can provide comments and share their opinion for a Study Concept. When a user enters her or his comments and submit the form, I want to auto save the currently logged in user to the user field. For example, User A created a new Study Concept and provided a comment (Please approve my request) while creating the new request. Then for the above comment user A should be saved. Later User B comes and edit this request and comments " Request looks good to me" and updates the form. Now user B should be auto saved for this comment. This is a new requirement for the project. I have tried various solutions available on stack-overflow, but I haven't succeeded yet. You can check in my code what currently I am trying to achieve. Please find my code below: models.py: class StudyRequestConcept(models.Model): CHOICES = ( ('Yes', 'Yes'), ('No', 'No'), ) REQUEST_STATUS = ( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Denied', 'Denied'), ) APPROVER_CHOICES = ( … -
2 level of users in django
I am into development of a web based business application using django which will be used by 3 different companies. The business process is exactly same. I have stucked at user creation. I need 2 level of users. First the comany detail (higher level) and second 'n' number of users from that company itself which will be using the application. I have extended the default user model using ABSTRACTUSER to fulfill my fields requirement but I am not able to configure my requirement. I am asking for what could be the best way to achieve my goal and I would give a try to it. -
web socket with Django channels
I am writing a small prototype of e-vote where each person will vote, but the vote will be encrypted with Shamir's secret-sharing, so the result of the vote will be displayed only if all voters meet. i do not know if it's feasible but for that i would like to integrate django-channel to my existing project to create real-time communication between users and wait for all voters to log in and enter one of their passwords (to decrypt key numbers) in the database) and valid to display the results at temp reel (I never use Django-channel). so my question is: is it possible? and can i run WSS (websocket secure) in my localhost, if yes how? thanks , and sorry for my bad English . -
*** TypeError: get_value_by_attribute() missing 1 required positional argument: 'attribute'
I am using Django oscar and trying to get product attributes key and values using product.attr.get_value_by_attribute(). And I am getting above errors and I have tried to pass attribute and it still giving me an error. My testing debugger code is as follows: (Pdb) child_product <Product: Good Day 100 gm> (Pdb) child_product.__dict__ {'_state': <django.db.models.base.ModelState object at 0x7fa088e1c438>, 'id': 13, 'structure': 'child', 'upc': '', 'parent_id': 12, 'title': 'Good Day 100 gm', 'slug': 'good-day-100-gm', 'description': '', 'product_class_id': None, 'rating': None, 'date_created': datetime.datetime(2019, 6, 22, 15, 30, 24, 273252, tzinfo=<UTC>), 'date_updated': datetime.datetime(2019, 6, 22, 15, 30, 24, 273270, tzinfo=<UTC>), 'is_discountable': True, 'attr': <oscar.apps.catalogue.product_attributes.ProductAttributesContainer object at 0x7fa088e1c470>} (Pdb) child_product.attr <oscar.apps.catalogue.product_attributes.ProductAttributesContainer object at 0x7fa088e1c470> (Pdb) child_product.attr.__dict__ {'product': <Product: Good Day 100 gm>, 'initialised': False} (Pdb) child_product.attr.__dict__ {'product': <Product: Good Day 100 gm>, 'initialised': False} (Pdb) child_product.attr.get_values() <QuerySet [<ProductAttributeValue: Brand: Britania>, <ProductAttributeValue: Variant Name: 100 gm x 12>]> (Pdb) child_product.attr.get_all_attributes() <QuerySet [<ProductAttribute: Brand>, <ProductAttribute: GST Rate>, <ProductAttribute: HSN Code>, <ProductAttribute: Liquid Content>, <ProductAttribute: Parent Company>, <ProductAttribute: Promo SKU>, <ProductAttribute: Selling Lot Size>, <ProductAttribute: Sub Brand>, <ProductAttribute: Tags>, <ProductAttribute: Variant Name>, <ProductAttribute: Weight>, <ProductAttribute: Weight Unit>]> (Pdb) child_product.attr.get_value_by_attribute() *** TypeError: get_value_by_attribute() missing 1 required positional argument: 'attribute' (Pdb) child_product.attr.get_value_by_attribute(attribute="Brand") *** ValueError: invalid literal for int() with base … -
When and how does DRF calculate the queryset?
I have a ModelViewSet that looks like: class UserRegistrationView(viewsets.ModelViewSet): """ UserRegistrationView A view to handle the User registration process """ permission_classes = ( permissions.AllowAny, ) serializer_class = accounts_serializers.UserRegistrationSerializer And, I have a serializer that looks like: class UserRegistrationSerializer(core_serializers.BaseModelSerializer): mobile_number = serializers.CharField(required=True, min_length=10, max_length=10) password = serializers.CharField(required=True, min_length=6, max_length=20) class Meta: model = accounts_models.User fields = ( 'mobile_number', 'password', ) I was studying the Django REST Framework code base to ascertain how the queryset used by the serializer is calculated by the view. I realized that happens within the get_queryset method within the view. But, I'm unable to understand how that happens. Basically, get_queryset looks like: queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset Now, what I find difficult to understand is that when is self.queryset set and where in the drf code base does that happen? Also, how does the view come to know of the model I'm trying to use before calculating the queryset? Am I missing something here? Thanks for the help in advance! -
How to automatically use my custom PasswordResetSerializer? (Django - DRF)
I want to use my custom PasswordResetSerializer to send the email automatically after the user reaches the limits of login attempts This serializer works fine in my frontend via API call Here is my code: authentication.py class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('email', None) # get the username request header password = request.data.get('password', None) """ After all validations and login attempts """ if user.fails_authentication(): #Use here my custom PasswordResetSerializer serializers.py class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() password_reset_form_class = PasswordResetForm def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(_('Error')) ###### FILTER YOUR USER MODEL ###### if not User.objects.filter(email=value).exists(): raise serializers.ValidationError(_('Invalid e-mail address')) return value def save(self): request = self.context.get('request') user = User.objects.get(email=request.data.get('email')) token = Token.objects.get(user=user.id) uid = urlsafe_base64_encode(force_bytes(user.id)).decode() template = 'example_message.html' context = {'usertoken': token, 'reactdomain': 'localhost:3000', 'userid': uid} opts = { 'use_https': request.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), ###### USE YOUR TEXT FILE ###### 'email_template_name': template, 'extra_email_context': context, 'html_email_template_name': template, 'request': request, } self.reset_form.save(**opts) -
Inlineformset Factory to pass the foreign Key and set it automatically from another model
i am trying to link the Team with the startup name as my model below using inlineformse factory: i want the assigning of foreign key to be autoset to startup name each time a new application is initiated. my codes are below for both models.py and views.py appreciate help. '''''' Models.py: from django.db import models class Startup (models.Model): startup_name=models.CharField('Startup Name', max_length = 100) def __str__(self): return self.startup_name class Team (models.Model): startup=models.ForeignKey(Startup, on_delete = models.CASCADE ) name=models.CharField('Name', max_length = 100) position=models.CharField('Position', max_length = 100) def __str__(self): return self.startup Views.py: def StartupName (request): form = modelform_factory ( Startup , fields = ('startup_name',) ) if request.method == 'POST': formset = form (request.POST) if formset.is_valid ( ) : formset.save ( ) return redirect ( 'str_team' ) else : formset = form() return render ( request , 'application/str_name.html' , { 'formset' : formset } ) def Teams (request, startup_id) : startup = Startup.objects.get(pk=startup_id) team = inlineformset_factory(Startup, Team , fields = ('name' , 'position') ) if request.method == "POST" : formset = team (request.POST, instance = startup ) if formset.is_valid ( ) : formset.save () return redirect ( 'str_dashboard' ) else : formset = team (instance = startup) return render ( request , 'application/str_team.html' , { … -
how to define a pk for models in django-tables 2 ? isn't it an automated?
I've used django-table2 to render a patients list entered by users however I'm getting a value error for unknown reason to me: Failed lookup for key [Patient] in , when resolving the accessor Patient.pk here's my tables.py class PatientTable(tables.Table): FirstName = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) LastName = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) Telephone_no = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) class Meta: model = Patient # attrs = {'class': 'table table-striped table-hover'} exclude = ("user", "Notes", "Address") template_name = 'django_tables2/bootstrap4.html' and here's my view function in the views.py def Patients_list(request): table = PatientTable(Patient.objects.filter(user=request.user)) return render(request, 'accounts/patients_list.html',{ 'table' : table }) -
How i can serealized data to json with drf serealizer
I have data model like: from django.db import models class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() def __str__(self): return self.first_name + ' ' + self.last_name class Course(models.Model): name = models.CharField(max_length=255) description = models.TextField() start_date = models.DateField(null=True) end_date = models.DateField(null=True) def __str__(self): return self.name class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='courses', on_delete=None) student = models.ForeignKey(Student, related_name='students', on_delete=None) completed = models.BooleanField(null=True, default=False) def __str__(self): return self.course I have some serealizer: class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('name', 'end_date', 'start_date') I need make some method which will be return date in json like: { "courses": [ { "name": "Math", "end_date": "2019-06-26", "start_date": "2019-06-26", "participant_students_count: 10 } ] } How I can get "participant_students_count" and return it data in json with other fields. Thanks for help! -
Make JWT (Jason Web Token) Last Longer or Other Alternatives For Flutter App
I have a django backend that user the Django Rest Framework. I have Django Rest APIs set up, that are specific for every user. I then also use Jason Web Tokens to be able to authenticate Users via my mobile Flutter Frontend. I then use the token I get on login in every request which works great! My problem is when the token runs out the user has to login again for this all to work. Is there any way I could make the Jason Web Tokens to last longer then the standard time of like 5 minutes??? Token Code in Django: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES' : ('rest_framework_simplejwt.authentication.JWTAuthentication',), } Different URLS (also the get-token url): urlpatterns = [ path('admin/', admin.site.urls), path('project/', include('project.urls')), path('studyplan/', include('studyplan.urls')), path('get-token/', TokenObtainPairView.as_view()), path('refresh-token/', TokenRefreshView.as_view()) ] -
I don't work comments and forms are not displayed
I'm trying to make comments on the site, but when I start the server, I do not see the forms. I create a simple blog in which a person can post likes and comment, but the problem is that when i add a comment form, they simply do not appear. P.S And excuse me for my English I am from another country and I don’t know English very well post.html main template {% extends "ShapeHtml/wrapper.html" %} {% block content %} <div class="panel panel-default"> <div class="panel-heading"> <h1 class=" text-info">{{object.title}}</h1> </div> <div class="panel-body"> <p> {{object.post|safe|linebreaks}} </p> <h3 align="right" class=" text-info"> Опубликованно: {{articles.date|date:"d-m-Y в H:i"}}</h3> </div> <h4>Comments</h4> <form action="{% url '' %}" method="post"> {% csrf_token %} {% if CommentModel %} {% for CommentModel in comments %} {{ CommentModel.WhoAreYou }} <br> {% endfor %} {% endif %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} views.py from .forms import CommentForm class ArticlesList(ListView): model = Articles template_name = 'news/posts.html' class ArticleDetail(DetailView): model = Articles template_name = 'news/post.html' def GetComments(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: form = CommentForm() comments = CommentModel.objects.all() return render(request, 'news/post.html', {'form': form, 'comments': comments}) urls.py urlpatterns=[ path('', ArticlesList.as_view(), name='articles_list'), path('<int:pk>/', ArticleDetail.as_view(), name='article_detail'), … -
how to set/get language for 2 different templates ( if lang a > templ2te1 elif lang b > template2
in my views i have the following, i have 2 different templates for each lang maybe i just have some kind of thinking problem when hiting site with lang en in browser i get de not defined since it is an if statement i seem not to be able where the problem is and the other way around with browser lang de LANGUAGES = translation.get_language() . . . if LANGUAGES == de: return render(....) elif LANGUAGES == en: return render(....) else: return HttpResponseNotFound NameError: name 'de' is not defined -
Django Template - Foreign Key Order by
In a Django template, how can I specify the order when I loop over all the objects founds in a reverse lookup such as in: {% for item in object.other_set.all %} <p>item.text</p> {% endfor %} Let's say I'd like this to be ordered by item.creation_date then by item.text?