Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter JSON field array for multiple indexes lookup with Q model?
Im using Django with Postgres and im having some trouble regarding filtering data into JSON field. --Here is my json object "dimensions": [ { "dimension": "140/200", "price": 163.52 }, { "dimension": "160/230", "price": 214.91 }, { "dimension": "200/290", "price": 338.72 } OR "dimensions": [ { "dimension": "160/230", "price": 214.91 }, { "dimension": "80/150", "price": 70.08 }, { "dimension": "140/200", "price": 163.52 }, { "dimension": "80/200", "price": 93.44 } --Here are my views and what i have tried: if min_price and max_price: queryset = queryset.filter( Q(product_options__options__data__dimensions__price = float(min_price), product_options__options__data__dimensions__contains=[{'price': float(min_price)}]) & Q(product_options__options__data__dimensions__price = float(min_price), product_options__options__data__dimensions__contains=[{'price': float(min_price)}])) -And finally im able to filter them using range filter queryset = queryset.filter(Q(product_options__options__data__dimensions__1__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__2__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__3__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__4__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__5__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)) But here is my question is there any possibility to make this a single query because im hitting db multiple times with all indexes from 0 to n. I have tried with gte and lte but same. I need something like queryset = queryset.filter(Q(product_options__options__data__dimensions__{'Here to filter all indexes'}__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId) -
When testing login functionality I get ValueError
I am writing a test to check if a user can login without entering his username. However, when I run the test I get response: ValueError:The view posts.views.LoginPageView didn't return an HttpResponse object. It returned None instead. How can I fix it? This is my views.py class LoginPageView(View): def get(self, request): if request.user.is_authenticated: return redirect('/') form = LoginForm() return render(request, 'login.html', {'form': form}) def post(self, request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: # if user exists, login() function will keep him logged during session login(request, user) return redirect('/') else: return redirect('/login') This is my LoginPageViewTest(TestCase): def setUp(self): self.login_url=reverse('login') self.register_url=reverse('register') self.user={ 'username':'username', 'password':'password', 're_password':'password', 'first_name':'first_name', 'last_name':'last_name', 'email':'email@gmail.com' } def test_cant_login_with_no_username(self): response = self.client.post(self.login_url,{'username':'','password':'password'},format='text/html') self.assertEqual(response.status_code,401) -
django-dynamic-scraper-unable-to-scrape-the-data
I try this open source example and I found this here Django-dynamic-scraper unable to scrape the data, but there is not the same error. I get all data from github and load all example data, then I want to crawl with 2021-01-13 14:58:15 [scrapy.utils.log] INFO: Scrapy 2.4.1 started (bot: open_news) 2021-01-13 14:58:15 [scrapy.utils.log] INFO: Versions: lxml 4.6.2.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 20.3.0, Python 3.7.7 (tags/v3.7.7:d7c567b08f, Mar 10 2020, 10:41:24) [MSC v.1900 64 bit (AMD64)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1i 8 Dec 2020), cryptography 3.3.1, Platform Windows-10-10.0.17134-SP0 2021-01-13 14:58:15 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor 2021-01-13 14:58:15 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'open_news', 'SPIDER_MODULES': ['scrapy_django_dashboard.spiders', 'open_news.scraper'], 'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'} 2021-01-13 14:58:15 [scrapy.extensions.telnet] INFO: Telnet Password: 00931b453fcba465 2021-01-13 14:58:15 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] 2021-01-13 14:58:15 [asyncio] DEBUG: Using selector: SelectSelector 2021-01-13 14:58:15 [article_spider] INFO: Django settings used: example_project.settings 2021-01-13 14:58:15 [article_spider] INFO: Use ALL images store format (Scrapy behaviour, save both original and thumbnail images) 2021-01-13 14:58:15 [article_spider] INFO: Runtime config: do_action True 2021-01-13 14:58:15 [article_spider] DEBUG: Configuration set: {'DO_ACTION': True, 'RUN_TYPE': 'SHELL', 'SPLASH_ARGS': {'wait': 0.5}, 'IMAGES_STORE_FORMAT': 'ALL', 'CUSTOM_PROCESSORS': [] , 'LOG_ENABLED': True, 'LOG_LEVEL': 'ERROR', … -
How can i upload my Django project on Hostinger VPN?
How can i upload my project files and setup environment to execute python project at server (hostinger VPN server)? Is there any tutorial avaialble? My project is done in Django Framework and has mySQL database connection. Under VPN i have already created on folder and installed Python and Django. Regards, PD -
Custom SetPasswordForm not changing password on submit
I'm making a website and one of the features is that when user forgets his password he can reset it. We all know that templates provided by django aren't beautiful so I created my own. and everything works but the password_reset_confirm Just to be clear if i have my custom templates on every view (reset_password, password_reset_done and password_reset_complete) but I'm using django provided password_reset_confirm page works password is changed but when im using my template and form for this password stays the same Thanks for your help and have a great day btw if some code in views is requied im working with function based views Forms.py from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm class CustomPasswordResetForm(PasswordResetForm): email = forms.EmailField(widget=forms.TextInput(attrs={'class':'registerForm','name':'email'})) class NewPasswordResetForm(SetPasswordForm): error_messages = { 'password_mismatch': ('New Passwords and Confirm Passwords not matching'), } password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'registerForm','name':'new_password1','id':'id_new_password1'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'registerForm','name':'new_password2','id':'id_new_password2'}) Urls.py from .forms import CustomPasswordResetForm, NewPasswordResetForm path('reset_password/', reset.PasswordResetView.as_view(template_name="resetPassword.html",form_class=CustomPasswordResetForm), name="reset_password"), path('new_password_send/', reset.PasswordResetDoneView.as_view(template_name="resetPasswordDone.html",), name="password_reset_done"), path('reset/<uidb64>/<token>/', reset.PasswordResetConfirmView.as_view(template_name="resetPasswordNew.html", form_class=NewPasswordResetForm), name="password_reset_confirm"), path('reset_password_complete/', reset.PasswordResetCompleteView.as_view(template_name="resetPasswordComplete.html"), name="password_reset_complete"), HTML <form method="POST" action=""> {% csrf_token %} <div class="form-group"> {{ form.password1 }} </div> <div class="form-group"> {{ form.password2 }} </div> <button type="submit" class="btnSbtRegister"> <span class="textSbtRegister"> {% trans "Change Pass" %} </span> </button> </form> -
Django error - 'function' object has no attribute [closed]
I have following problem: I would like to call a function vyroci_mesicV from a module vyroci in my view.py. When I simply try print(vyroci.vyroci_mesicV()) in the terminal in VS Code I got the desired output. However, when I run py manage.py runserverand run the local host I got and error message AttributeError: 'function' object has no attribute 'vyroci_mesicV' Here is the code of views.py if needed: def vyroci(request): error_msg = None vysledek = None if request.method == "POST": if (request.POST["operator"] == "Vysehrad"): vysledek = vyroci.vyroci_mesicV() else: error_msg = "something wrong :(" return render(request, "vyroci/vyroci.html", dict(error_msg=error_msg, vysledek=vysledek)) return render(request, "vyroci/vyroci.html", dict(error_msg=error_msg, vysledek=vysledek)) and here the vyroci.html if neede: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>XXX</title> </head> <body> <form method="POST"> {% csrf_token %} <span style="color: red;">{{error_msg}}</span> <br> <select name="operator"> <option value="Vysehrad" {% if request.POST.operator == "Vysehrad" %} selected {% endif %}>Vyšehrad</option> </select> <input type="submit"><br> {{vysledek}} </form> </body> </html> -
In HTML unable to execute django if statement
enter image description here I have created models as shown in the picture. In the index page to display certain content, the member must be active. I am trying to use the if statement. {% if user.active == True %} do this... {% endif %} The above code is not working, also django is not throwing any error. Can anyone please help me on this? -
How can i include a searchbox in a Django FilteredSejectMultiple Widget
I'm a little bit new to django, i've done a couple of practice projects before but this is the first serious one. I'm trying to make a recipe webpage where users can upload, share and search cooking recipes. When writing a new recipe, i want users to be able to attach some already written recipe (lets say they are writing a goulash recipe, i want them to be able to say "here is an old spätzle recipe i really like"). So, in the RecipeModel this is a ManyToMany field and works just fine, but in the RecipeForm i'm really struggling: there would be too many recipes in the database to just list them all up in a dropbox, there should be a searchbox where Users can type the name of the one or multiple recipes they want to link. I know there's this "FilteredSelectMultiple" Widget that should do the work, but I just couldn't find any explanation of how to include a searchbox on it. -
Proper way to backup and restore django project
I have been using Oracle's virtual box to setup an Ubuntu 18.04LTS OS to run my django application. The application is using MySQL as a database. The problem happened a few days ago, all my files suddenly became read-only, which is an indication of hard disk problems as seen in this post. I have since prepared another server to run the application, however I would like to know the proper procedures in migrating data to ensure that I don't loose any of my files. Could someone point me in the correct direction? Thank you. -
How to redirect to the same page location after submitting a form in django?
In a blog post comment, I want to redirect to the comment location after submitting new comment. How am I suppose to do it? Thanks in advance. -
Customise choices for BooleanWidget in django_filters
I'm using django_filters. For boolean fields, it generates this HTML: <select name="bass" id="id_bass"> <option value="">Unknown</option> <option value="true" selected="">Yes</option> <option value="false">No</option> </select> This springs from Django's own specifics of NullFields. How can I change that ugly 'Unknown' to something else? the user is not really searching for 'Unknown'; they're searching for 'all', since my boolean field is required and either true or false. The widget does not accept a choices attribute. Creating manually the HTML myself partially solved the issue; nevertheless, I would achieve this from the view and use only the {{form}} on the template. -
Error after overriding create method in serializer
I'm Overriding create method of serializer in order to manipulate validated_data and create object in a model, Although it works, in the end I get below error, i am not able to figure out why after lot of research. AttributeError: Got AttributeError when attempting to get a value for field `shift_time` on serializer `PunchRawDataAndroidSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `PunchRawData` instance. Original exception text was: 'PunchRawData' object has no attribute 'shift_time'. class PunchRawDataAndroidSerializer(serializers.ModelSerializer): employee_id = serializers.CharField() shift_id = serializers.CharField() work_location_id = serializers.CharField() shift_time = serializers.TimeField() class Meta: model = PunchRawData fields = ['employee_id', 'shift_id','work_location_id', 'punch_type', 'actual_clock_datetime', 'emp_photo', 'created_at', 'updated_at','shift_time'] def create(self, validated_data): validated_data.pop('shift_time') request_data = self.context.get('request') user = request_data.user validated_data['user'] = user data = validated_data return PunchRawData.objects.create(**data) class PunchRawDataAndroidViewSet(viewsets.ModelViewSet): serializer_class = PunchRawDataAndroidSerializer parser_classes = (MultiPartParser, FileUploadParser) -
requests Python lib saves wrong cookie value, invalid JSON str
I am using "requests" latest version in Python. I am sending get/post requests via request.Session(), so the session created is holding the cookies values set by the server. Say my server sets cookie when i GET request some url, the cookie is set in JSON str format. s = requests.Session() s.get("https://www.example.org/api/bla) # Cookie is set print(s.cookies["my_cookie"]) When i check the value of the cookie planted (s.cookies["my_cookie"]) the JSON str format is wrong, it looks like this: '"{key1: value1\\054 key2: value2\\054 key3: value3\\054 key4: value4\\054 key5: value5}"' When i repeat the same request on Chrome browser client, the cookie looks OK. "{\"key1\": \"value1\"\054 \"key2\": \"value2\"\054 \"key3\": \"value3\"\054 \"key4\": \"value4\"\054 \"key5\": \"value5\"}" What can cause this? i don't think it's an issue is on "requests" lib side. I also know that the client sending back the cookie in wrong format, because when the cookie value is valid, the server creates a db object, but via my client (requests lib) the object is not created. Stuff i tried with no help: Changing my custom headers to the same as chrome Updating/Downgrading requests lib Thanks in advance. -
Graphene-Django and CORS issue related to GraphQLerror: "message": "GraphQL only supports GET and POST requests."
I am having serious trouble with this issue. Scouring the internet has yielded me with many StackOverflow and Github threads on the matter but none of them fix the problem at hand. I am creating a GraphQL endpoint for a backend through graphene-django and am encountering CORS pre-flight request issues when connecting to it. I know that the CORS works in all the other contexts, e.g. for using the /admin/ url, however when hitting the /graphql/ url, it fails. I found, through the use of Insomnia (a type of Postman) that it fails because the OPTIONS pre-flight request is rejected by GraphQLView in the following lines of the graphene-django source code: if request.method.lower() not in ("get", "post"): raise HttpError( HttpResponseNotAllowed( ["GET", "POST"], "GraphQL only supports GET and POST requests." ) ) as may be found here https://github.com/graphql-python/graphene-django/blob/main/graphene_django/views.py. I know that the headers are provided correctly back as Insomnia notifies me that they are connected to this 405 Method Not Allowed OPTIONS call. Supposedly, installing django-cors-headers fixes this problem for everyone else but it does not seem so for me: https://github.com/graphql-python/graphene-django/issues/778 https://github.com/graphql-python/graphene-django/issues/288 How to solve error 405 method not allowed, for django graphql server and react axios in front end My … -
Overwrite Django permission
I want to make the permissions in views instead of the default at models I create a main class called CreatorView from django.views.generic import View from django.forms.models import modelform_factory class CreatorView(View): model = None fields = None exclude = None form = None page_title = '' def create_form(self): default =dict() if self.fields == None: if self.exclude == None: default['fields'] = self.fields = self.model._meta.fileds else: default['exclude'] = self.exclude else: if self.exclude: raise Exception('error') default['fields'] = self.fields return modelform_factory(self.model,**default) def get(self,request,*args,**kwargs): return render('','base.html') def post(self,request,*args,**kwargs): ... and so on the main urls is: urlpatterns = [ path('%s/%s' % (cls.model._meta.app_label, cls.__name__.lower()), cls.as_view(), name='%s/%s' % (cls.model._meta.app_label, cls.__name__.lower())) for cls in CreatorView.__subclasses__()] if I make inheritance from CreatorView then my class should create a page for example: class Login(CreatorView): model = Users """ my overwrite methods and actions """ class Configurations(CreatorView): model = Configure """ my overwrite methods and actions """ class Teachers(CreatorView): model = Teachers """ my overwrite methods and actions """ class Students(CreatorView): model = Students """ my overwrite methods and actions """ and so on this code will create to me four pages I want to create table semi to django content_type model to be like: id app_label page 1 myapp login … -
Django-App deployed in network with Gunicorn /NGINX - not accessible on private IP
I deployed a DjangoApp following this documentation: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-debian-10 The aim is to make the app available within a company network. It perfectly works except of the following problems: on localhost the default nginx page is displayed (even though I removed default from sites-available and sites-enabled) It is not accessible on the private IP (192.168....) even though the private IP is defined in settings.py (ALLOWEDHOSTS = …) and in the nginx configuration file: “server { listen 80; servername private_IP; }” The app is available locally on 127.0.0.1 I don’t get any error messages What could be wrong with my configuration? What could I test? -
Django Calculated fields do not appear in get_fields()
I have a calculated field in a model. class SfShifts(models.Model): pr_id = models.PositiveIntegerField(primary_key=True, db_column='pr_id__c') def _get_calculated_field(self): return {'cal': self.pr_id} calculated_field = property(_get_calculated_field) But when I call get_fields() I don't get it. field_list = [field.get_attname_column() for field in self.model._meta.get_fields()] How can I get the calculated field name too? -
Django admin: inherit base class field such that it is used to set the model's field on save
Say I have models A, B, C, each have a foreign key field foo to model Foo. foo is a difficult field to select, hence we rather use a field bar (a foreign key to model Bar), and depending on the entry selected, our code selects the correct Foo. The bar field is not part of A, B, or C, only foo is. Now in django admin models for A, B, and C, I am trying to make a common base model they can inherit from which will handle this functionality. # --- models.py class BaseModel(models.Model): foo = models.ForeignKey(Foo, on_delete=models.PROTECT) class A(BaseModel): name = models.CharField("A name", max_length=200, unique=True) class B(BaseModel): enabled = models.BooleanField("Be enabled", default=True, ) class C(BaseModel): count = SmallFloatField("Count of things", ) # --- admin.py class BaseAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) # This form object does not have .fields attribute form.fields = [x for x in form.fields if x != 'foo'] form.fields += 'bar' return form @admin.register(A) class AAdmin(BaseAdmin): pass @admin.register(B) class BAdmin(BaseAdmin): pass @admin.register(C) class CAdmin(BaseAdmin): pass Unfortunately form.fields does not exist on the form object. How does one replace a field of a base ModelAdmin class such that its derived … -
How to format django-filters with crispy forms?
Is it possible to format a django_filters filter form with django-crispy-forms? I've been trying to do that, but django_filters.FilterSet doesn't seem to accept the crispy forms formats (from DeviceFilter class). It doesn't give an error either.The only thing that seems to be able to give a format is {{ filter.form|crispy }} but I want to be able to do it in python with FormHelper(). filters.py from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column import django_filters class DeviceFilter(django_filters.FilterSet): device_type = django_filters.ModelChoiceFilter(lookup_expr='exact', field_name='device_type__pk', queryset=None) device_group = django_filters.ModelChoiceFilter(lookup_expr='exact, field_name='device_group__pk', queryset=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['device_type'].queryset = DeviceType.objects.filter(owner=self.request.user) self.filters['device_group'].queryset = DeviceGroup.objects.filter(owner=self.request.user) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('device_type', css_class='form-group col-md-6 mb-0'), Column('device_group', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), Submit('submit', 'filter') ) class Meta: model = Device fields = {} template <!-- filter --> {% if filter %} <form method="get"> {{ filter.form|crispy }} </form> {% endif %} -
Django models in admin return TypeError: bad operand type for unary -: 'str'
I'm working on a project using Django(3) and Python(3) in which I have added few models and added those models in admin.py, but when I open the admin panel and try to add an object for those models it returns an error. Here's one of my model which is returning error: From models.py: class CurrencyManagementAssetsModel(models.Model): RequestId = models.IntegerField(blank=False) CbnInstitutionCode = models.CharField(max_length=5, blank=False) SortCode = models.CharField(max_length=10, blank=False) Count = models.IntegerField(blank=False) AssetClassificationId = models.IntegerField(blank=False) AssetTypeId = models.IntegerField(blank=False) ValueOfCurrencyDistributed = models.DecimalField(max_digits='20', decimal_places='10', blank=False) VaultCapacity = models.DecimalField(max_digits='20', decimal_places='10', blank=False) Year = models.IntegerField(blank=False) HalfOftheYear = models.IntegerField(blank=False) class Meta: verbose_name = 'Currency Management Assets' and Here's the error I'm getting when click on that particular model in admin: Request Method: GET Request URL: http://127.0.0.1:8000/admin/reports/currencymanagementassetsmodel/ Django Version: 3.1.3 Exception Type: TypeError Exception Value: bad operand type for unary -: 'str' What can be wrong here? -
Bypassing the unique constraint when defining a foreign key to just one field in Django
I've a model as shown below: class Instance(models.Model): data_version = models.IntegerField(default=1, unique=True) name = models.CharField(max_length=200) The data_version field has to be related to all other models in the application: class Source(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) version = models.ForeignKey(Instance, on_delete=models.CASCADE, to_field='data_version', null=True) The problem here is that Django requires the field data_version to be a unique field for me to be able to define such a relationship but that simply doesn't fit into my use case. I need to have multiple Instance objects in the app, each with version numbers starting from 1. What I'd like is to have a unique constraint on the combination of name and data_version but then Django doesn't allow defining Foreign key relationships as shown above. Is there a way I can bypass this restriction? -
Combining answer and question fields (django)
I have a question answer quiz. I have 2 models Question and Answer. I want to have 2 pages. On the first page there will be a Question model where the user will write the question and the answer to that question. On the second page I will display these questions and accordingly the Answer model where the customer enters the answer and then check if it is equal to the ** answer_question ** of the Question. But I could not do that so call each question Answer and show it in html. this is my code --> models.py --> from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def _unicode__(self): return unicode(self.questin) views.py --> from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, "e":e}) forms.py --> from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm … -
In Django the CustomUserForm is not adding users to the database (i.e. to the `User` model)
I have created a CustomForm by inheriting the UserCreationForm for user registration as follows (code reference): class CustomForm(UserCreationForm): email = forms.EmailField(required=True) firstname = forms.CharField(required=True) lastname = forms.CharField(required=False) class Meta: model = User fields = ("username", "firstname", "lastname", "email") def save(self, commit=True): user = super(CustomForm, self).save(commit=False) user.first_name = self.cleaned_data["firstname"] user.last_name = self.cleaned_data["lastname"] user.email = self.cleaned_data["email"] if User.objects.filter(email = user.email).exists(): raise ValidationError("Email exists") elif commit: user.save() return user I am facing the following issues: Although I have added a condition to make sure unique email is used, I am still able to register a user with the same email address without getting any errors. Though the CustomForm seems to work fine, but when I checked my User model through admin panel, no new users are being added there, and as a result, I am not able to log in. i.e. the CustomForm is not adding users to the database (User model) What can I do to solve the above two issues? -
Is it possible to combine a django app and a javascript app into one app?
I'm looking for ideas on how to implement the following requirement. I have 2 different applications one being a python Django app and the other one being a pure javascript app. I can get both the apps running on different ports but I need to be able to integrate the js app into the Django app. I.e. I want to add the js app into the Django app such that when you navigate to djangoapp.com/admin/js_app you go to the landing page of the js_app application. the 2 apps are https://github.com/CodeForAfrica/gmmp and https://github.com/OpenUpSA/wazimap-ng-ui any ideas will be appreciated -
Django template : sorting by value of __str__
I am using django 3 and I have surcharged the str function for my model : class SubSubCategory(models.Model): subCategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE) name = models.CharField("Nom du sous sous category" , max_length=200, ) description = models.CharField("Description du sous sous category" , max_length=200, null=True, blank=True) def __str__(self): description_locale = self.name + " : " + self.description if self.description else self.name hierarchie = [str(x) for x in [self.subCategory.category, self.subCategory, description_locale]] description_totale = " > ".join(hierarchie) return description_totale How could I ask my template to order my list according to this str representation ? I would like to do something like : {% for SubSubcategory in object_list|dictsort:'str' %} but it obviously doesn't work, as "str" is nothing. How do I call the string representation of an object in a template ? to pass it as an ordering order ?