Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django settings.py import error in mange.py Configuration error
Thanks in Advance for My Query. I have created a django project which has manage.py file inside src folder it works fine when running terminal from SRC folder. FOr Heroku deployement manage.py should be placed in root directory so i updated manage.py file with "os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.tweetme.settings")" Changed "os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tweetme.settings")" to "os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.tweetme.settings")" import issue is faced on running locally. Need solution how to import setting.py inside two folder deep. #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.tweetme.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) I am facing following Error: attached Error_Message.png Hiras-Mac-mini-2:tweethere apple$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 23, in execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 307, in execute settings.INSTALLED_APPS File "/Library/Python/2.7/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/Library/Python/2.7/site-packages/django/conf/init.py", line … -
Internal Server Error and Type Error, get error on post request?Nginx Django
On local machine everything works great, but on production, creation of qr images not work, and creating qr images give me this error P.S on local host everything works great! because the working directory is determined where the file manage.py is located so that it does not clutter the main directory, I create it on the other for a temporary picture, save it in the correct place, then delete it! my creating qr image view def qr_code_generator(hex_code, username, __show__id, q, price): check_curent_dir = os.getcwd() if os.path.basename(check_curent_dir) == 'src': os.chdir('..') os.chdir('media/fake_qr_code_img/') qr_code_generate_himslef = pyqrcode.create(hex_code) generate_name = ''.join(username + '_' + str(__show__id) + '_' + str(q) + '_' + str(price) + '.png').replace(" ", "_") qr_code_generate_himslef.png(generate_name, scale=6) get_user_profile = get_object_or_404(UserProfile, user__username=username) get_upcoming_show = get_object_or_404(SectionUpcomingShow, id=__show__id) with open(generate_name, 'rb') as new_qr_img: new_qr_code, created = QRCode.objects.get_or_create(user=get_user_profile, qr_code=hex_code, is_active=True, defaults={"user":get_user_profile, "qr_code":hex_code, "qr_code_img":File(new_qr_img), "upcoming_show":get_upcoming_show}) if not created: pass try: os.remove(generate_name) except: print("Cannot be removed!") return 'Done' when i try to buy tickets i got this error on my email Internal Server Error: /purchase_tickets/ TypeError at /purchase_tickets/ super(type, obj): obj must be an instance or subtype of type Request Method: POST Request URL: http://therockband.tk/purchase_tickets/ Django Version: 1.11.6 Python Executable: /webapps/theband/bin/python3 Python Version: 3.5.2 Python Path: ['/webapps/theband/src', '/webapps/theband/bin', '/webapps/theband/src', … -
Django did not display DEBUG error page despite being run on localhost and ``DEBUG=True``
In my django project I did set DEBUG setting to true, and I'm accessing the server from localhost. Despite that instead of error page I get: "A server error occurred. Please contact the administrator.". -
Django2, the forms in template do not work
(only in Django 2 & 2.0.1) if I use {{form}} it works but if I use {{form.field}} it disappears all <form method="POST" class="post-form" method="post"> {% csrf_token %} {{ form }} <input type="submit" id="salva" class="btn btn-primary" /> </form> -
Django Sum Aggregation from Int to Float
So i save my fees in cents, but want to display them in Euro. The conversion problem is that it first divides the integer by 100 and then converts to a float. It should be the other way around. How can i do that? The following code should illustrate my Problem: >>> from django.db.models import F, FloatField, Sum >>> from payment.models import Payment >>> >>> paymentlist = Payment.objects.all() >>> result = paymentlist.annotate( ... fees_in_cents=Sum(F('fees'), output_field=FloatField())).annotate( ... fees_in_euro=Sum(F('fees')/100, output_field=FloatField())) >>> >>> print(result[0].fees_in_cents, result[0].fees_in_euro) 120.0 1.0 fees_in_euro should obviously be 1.20 -
I have set the related_name in OneToOne Field, but still get the RelatedObjectDoesNotExist error
When I use the to_representation I get error: django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: SwitchesPort has no physical_server. The traceback is bellow: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework/serializers.py", line 656, in <listcomp> self.child.to_representation(item) for item in iterable File "/Users/asd/Desktop/xxx/api/serializers.py", line 256, in to_representation if instance.physical_server == None: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 407, in __get__ self.related.get_accessor_name() django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: SwitchesPort has no physical_server. My Models: class SwitchesPort(models.Model): """ 交换机接口 """ ... switches = models.ForeignKey(to=Switches, on_delete=models.CASCADE,related_name="switchesports", help_text="所属交换机") vlanedipv4networkgroup = models.ForeignKey( to=VlanedIPv4NetworkGroup, # 初始化之后的 null=True, blank=True, on_delete=models.SET_NULL, related_name="switchesports", help_text="所关联的vlaned组") network_speed = models.IntegerField(default=10, help_text="交换机控制网络流量速度") class Meta: ordering = ['name'] def __str__(self): return self.name def __unicode__(self): return self.name class PhysicalServer(models.Model): """ physical_server """ ... switchesport = models.OneToOneField(to=SwitchesPort, related_name="physical_server", on_delete=models.DO_NOTHING, help_text="所属交换机接口", null=True) def __str__(self): return self.name def __unicode__(self): return self.name My Serializer is bellow: class SwitchesPortSerializer(ModelSerializer): """ switches port """ class Meta: model = SwitchesPort fields = "__all__" extra_kwargs = { "vlaned_network":{"read_only":True} } def to_representation(self, instance): serialized_data = super(SwitchesPortSerializer, self).to_representation(instance) if instance.physical_server == None: # there syas the error serialized_data['is_connected'] = True return serialized_data You see, the OneToOne Field have the related_name, why I still get the issue? -
jsonfield violates not-null constraints and filetype is not unsupported
I Have a model field field_name = JSONField(editable=False) from django admin I can't save it. If I give any json format data it shows this error 'InterfaceError: Error binding parameter 10 - probably unsupported type' -
Django last page pagination redirect
My problem is similar to this problem. The only difference is I use GCBV for my pagination. My view file is as follows: class ChatListView(ListView): model = Chat form_class = NewMessageForm template_name = 'chat.html' paginate_by = 5 queryset = form_class.objects.all() def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect('chat') <--- here return render(request, self.template_name, {'form': form}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = NewMessageForm() return context What I want the post method to redirect to the last page of the pagination. In the link, it was achieved by return HttpResponseRedirect('/forum/topic/%s/?page=%s' % (topic.slug, posts.num_pages)). But for my GCBV, I don't know how to get the .numpages via an object. Any thoughts? -
How to POST values with specific ID from page that displays a list?
I'm working on my first django project which is a sport betting app. My models are: class Game(models.Model): home_team = models.CharField(max_length=100) away_team = models.CharField(max_length=100) class GameBet(models.Model): gameid = models.ForeignKey(Game) bet = models.IntegerField(default=None) #values: 1(home win), 0 (draw), 2 (away win) userid = models.ForeignKey(User) I am able to save user bets using a single game view, when I pass gameid in url, but that is not very effective. I created a simple page with list of games with 1 form per game for a start (at the end I would prefer to send all bets with one button): {% for game in games %} {{ game.id }} | {{ game.home_team }} | {{ game.away_team }} | <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="bet" /> </form> <br> {% endfor %} and my form is: if request.method == 'POST': #if request.POST["bet"] == 'bet': form = NewBetForm(request.POST) if form.is_valid(): bet = form.save(commit=False) bet.gameid = [r.id for r in owing_games] #it gives me a list and ValueError Cannot assign "[10, 11, 12]": "GameBet.gameid" must be a "Game" instance. bet.userid_id = current_user.id bet.bet = form.value() bet.save() How can I pass a single game.id in that case? -
Django rest ModelViewSet filtering objects
I have two models: Library and a Book. A Library will have Many Books. class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) city = models.CharField(max_length=30) address = models.CharField(max_length=80) phone = models.CharField(max_length=30, blank=True, null=True) website = models.CharField(max_length=60, blank=True, null=True) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) reader = models.ManyToManyField('Reader', related_name='wishlist') my serializers: class LibrarySerializer(serializers.ModelSerializer): class Meta: model = Library fields = '__all__' class BookSerializer(serializers.ModelSerializer): wishlist = ReaderSerializer(many=True, read_only=True) class Meta: model = Book fields = '__all__' And my view: class LibraryViewSet(viewsets.ModelViewSet): queryset = Library.objects.all() serializer_class = LibrarySerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.filter(which_library=library_id) serializer_class = BookSerializer My Urls: router = routers.DefaultRouter() router.register(r'libraries', LibraryViewSet) router.register(r'books/(?P<library_id>[0-9]+)', BookViewSet) urlpatterns = router.urls my Library routes work correct. However for Books, I need to return the books only belonging to specific library. The default URL and all() returns all the books in database and can retrieve single by hitting books/1. How can I achieve this? I could do it previously with : @api_view(['GET', 'POST']) def books(request, library_id): but now I want to do it with ModelViewSet. -
Django: How to add a foreignkey to a dependent form, to a multi-form submit?
Forgive the logic of the table structure below example. It only meant as a simple example of the situation that I am. So the situation is that I want to make an employee form page, where the department and line manager might or might not exist already. So I replace the drop-down box with the form field for the foreign key, so they can be created if need all in one step for the user. However, with this kind of dependency, I am not doing the right thing in view to make it work. If you need more detail please do ask. If you can make the Title more precise please do. Thank you for your time. Model class Employee(models.Model): name = models.CharField() age = models.CharField() line_manager = models.ForeignKey(LineManager) department = models.ForeignKey(Department) class LineManager(models.Model): manager_name = models.CharField() department = models.ForeignKey(Department) class Department(models.Model): department_name = models.CharField() Form class EmployeeForm(ModelForm): class Meta: model = Employee fields = ['name', 'age' #'line_manager' Not needed #'department' Not needed] exclude = ('line_manager', 'department') class LineManagerForm(ModelForm): class Meta: model = LineManager fields = ['manager_name'] exclude = ('department') # There is a basic form for Department, as well. View class AddEmployeeView(View): forms = {'department': DepartmentForm(self.request.POST or None), 'line_manager': … -
"Closure Table" in django models?
Can someone help me to create Django models with next tables which us "Closure Table" hierarchical tree architecture. I am confused of relationship in models. "document" TABLE: "document_tree" TABLE: | document_id | document_name | | ancestor | descendent | level | | -------------|---------------| | ---------|------------|-------| -
Try to post a dictionary to my view
In my template, I have a form and a <select> with many <option>. I have to pass 2 values in each <option>, so I had the idea to make a dictionary : <option value="{'Game':{{game.on_game.id}},'Platforme':{{game.on_plateform.id}}}"> It returns something like this : <option value="{'Game':3,'Platforme':3}"> In my view I want to save a new entry : post = request.POST entry = InboxRecruiting() entry.on_game = Games.objects.get(id=post['game']['Game']) entry.on_platforme = Plateform.objects.get(id=post['game']['Platforme']) entry.save I have an error : string indices must be integers Thanks for your help. -
Integrate c++ Compiler to a website using DJANGO
I would like to integrate an online code editor with a C++ compiler integrated into my website. Are there any soft service which allows to compile and execute codes from user. and is there any possibility to compile the code into the website server and run it in the user machine ? thanks -
get_absolute_url not making any effect
I only used this in my template. I am following a tutorial. In tutorial video is working but I couldn't make it work. Here is my template code: <i> {% for object in object_list %} <div class="media"> <div class="media-left"> <a href="#"> {% if object.img %} <img class="media-object" src="..." alt="..."> {% endif %} </a> </div> <div class="media-body"> {{ object.content }}<br/> via {{ object.user }} | {{ object.timestamp|timesince }} ago | <a href='{{ object.get_absolute_url }}'>View</a> </div> </div> <hr/> </i> -
Celery Beat not Working
Celery beat is not scheduling task properly and freezes. Celery Configuration 4.1.0 CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_ACCEPT_CONTENT += ['pickle'] CELERYBEAT_SCHEDULE = { 'testing_msg': { 'task': 'modules.sms.tasks.testing_message', 'schedule': crontab(minute=1), }, } tasks.py @task() def testing_message(*args, **kwargs): SmsAPI().send_sms("Hello Shubham Message Time is {}".format(datetime.now().time()), "958xxxxxx") SmsAPI().send_sms("Hello Nishant Message Time is {}".format(datetime.now().time()), "971xxxxxx") Celery Beat Logs (Nishant) shubham@shuboy2014:/media/shubham/BC161A021619BDF8/Nishant Project/Project1$ celery -A config beat -l debug raven settings celery beat v4.1.0 (latentcall) is starting. __ - ... __ - _ LocalTime -> 2018-01-04 14:57:53 Configuration -> . broker -> redis://127.0.0.1:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%DEBUG . maxinterval -> 5.00 minutes (300s) [2018-01-04 14:57:53,139: DEBUG/MainProcess] Setting default socket timeout to 30 [2018-01-04 14:57:53,139: INFO/MainProcess] beat: Starting... [2018-01-04 14:57:53,334: DEBUG/MainProcess] Current schedule: <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)> [2018-01-04 14:57:53,334: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes [2018-01-04 14:57:53,336: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. Any helpful comments and answers will be appreciated. -
How to construct a response in Django as specified in finger print reader sdk
The following is part of a documentation of SDK for a finger print device. SDK documentation Device sends: GET /iclock/cdata?SN=xxxxxx&options=all Thereinto, xxxxxx is the device’s serial number. server returns (example): GET OPTION FROM: xxxxxx Stamp=82983982 OpStamp=9238883 ErrorDelay=60 Delay=30 TransTimes=00:00;14:05 TransInterval=1 TransFlag=1111000000 Realtime=1 Encrypt=0 How can i construct such a response in Django? -
Django 2: project root url namespace not working
I have the following url patters in the project root's urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('main/', include('main.urls', namespace='main')), ] But django complains with the following message: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. According Django's documentation, the pattern of 'main' should be correct. What's the problem? -
How to do logging in flask?
The python logging module will have problem in multiprocessing. Because there is no lock between processes while they writinig to the same log file. But the flask or django programes will always run in multiprocessing enviroment when they are hosted by uwsgi. Uwsgi run multiple workers. One worker is one process that hosted the flask/django program. So this is a situation that write log into one file from multiple process How flask or django to solve this? -
Django User Profile Model Sign Up Form
I'm developing django project. Now I'm making sign up form with profile model. But I got a problem. models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) usernickname = models.CharField(db_column='userNickName', max_length=50, blank=True, null=True) userbirth = models.DateField(db_column='userBirth', blank=True, null=True) class Meta: managed = False db_table = 'profile' @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py : from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): userBirth = forms.DateField() class Meta: model = User fields = ('username', 'password', 'userBirth') widgets = { 'username': forms.TextInput(), 'password': forms.PasswordInput(), 'userBirth': forms.DateField(), } views.py : def join(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.userbirth = form.cleaned_data.get('userbirth') user.save() user = User.objects.create_user(username=user.username, password=user.password) user.save() return redirect('index') else: form = UserForm() return render(request, 'registration/join.html', {'form':form}) and when sign up, InternalError at /join/ (1054, "Unknown column 'profile.user_id' in 'field list'") this error returns. when log in to /admin, same error returns. I don't have any idea.. I refernced this blog: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html#sign-up-with-profile-model -
Use input type text of html as {% csrf_token %}
I am trying to run a client server application using django using ajax post. All the tutorials that i went across uses a form as the {% csrf_token %} but i want the input type text to be used as the {% csrf_token %} . Also, I want the method post to be used. Right now, I am doing it as follows - <form class="forms" method="POST"> {% csrf_token %} <input type="text" name="chat" id="chatb" placeholder="Hi there! Type here to talk to me." onfocus="placeHolder()"> </form> So, here I am making a form. But, I want an alternative of not using forms. Also, i want to save the previously entered data. -
Wagtail - getting routablepageurl of page category in other page
I have filter of category on mydomain.com/gallery/album/2017 class Gallery(RoutablePageMixin,Page): short_description = models.CharField(max_length=300,blank=True) content_panels = Page.content_panels + [ FieldPanel('short_description'), InlinePanel('image_gallery', label="image gallery"), ] def get_posts(self): return AlbumImageGallery.objects.all() @route(r'^albums/(?P<album>[-\w]+)/$') def post_by_category(self, request, album, *args, **kwargs): self.get_posts = self.get_posts().filter(album__slug=album) return Page.serve(self, request, *args, **kwargs) def get_context(self, request, *args, **kwargs): context = super(Gallery, self).get_context(request, *args, **kwargs) context['albums'] = Album.objects.all() context['album_image'] = AlbumImageGallery.objects.all() context['get_posts'] = self.get_posts context['gallery'] = self return context In my Html ` <a href="{% routablepageurl gallery "post_by_category" each.slug %}"> {{each.album_name}}</a>` Now i want to get mydomain.com/gallery/album/2017 from my other page class MymodelPage(Page): ... get_context(): context['gallery_images'] = Image.objects.all() context['gallery'] = Gallery.objects.get() MymodelPage.html error NoReverseMatch at /media-corner/ Reverse for 'post_by_category' with arguments '('',)' not found. 1 pattern(s) tried: [u'albums/(?P<album>[-\\w]+)/$'] I want to get gallery url/slug on my Modal RoutablePageMixin i tried to pass url page its gives me error -
Django translation makemessage error
I'm creating django multilingual website. Settings.py USE_I18N = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ], }, }, ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('de', _('German')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) template: <h5>{% trans "Hello, this is testing page" %}</h5> urls: from django.conf.urls.i18n import i18n_patterns from django.conf.urls import include, url urlpatterns = [ url(r'^rev/', rev, name="rev"), url(r'^userprofile/', userprofile, name="profile"), ] views: @login_required def rev(request): return render_to_response('rev.html', {'client': request.user.client, 'user': request.user}) @login_required @require_http_methods(["GET"]) def userprofile(request): return render(request, 'userprofile.html', { 'user': request.user, 'form': UserProfileForm(instance=request.user) }) So, using python makemessage -l de command I got next error: CommandError: errors happened while running msguniq msguniq: \u041d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u0442\u044c \u0438\u0437 \xabASCII\xbb \u0432 \xabUTF-8\xbb. msguniq \u043f\u043e\u043b\u0430\u0433\u0430\u0435\u0442\u0441\u044f \u043d\u0430 iconv(). \u042d\u0442\u0430 \u0432\u0435\u0440\u0441\u0438\u044f \u0431\u044b\u043b\u0430 \u0441\u043e\u0431\u0440\u0430\u043d\u0430 \u0431\u0435\u0437 iconv(). I think, that I set urls incorrect. All answers about it are at least 3-4 years old, on newest django version , setting urlpatterns = i18n_patterns[....] causes error: TypeError: 'function' object is not subscriptable GNU gettext installed. Why Am I really getting this error, and I know, that … -
Dynamic Django Sidebar
I'm trying to create a dynamic sidebar in Django, which gets loaded using the following models. class MenuItem(models.Model): display_name = models.CharField(max_length=100) active = models.BooleanField(default=True) def __unicode__(self): return self.display_name class Meta: default_permissions = () class MenuParent(MenuItem): pass class MenuTitle(MenuParent): pass class PageGroup(MenuParent): parent = models.ForeignKey(MenuTitle) icon = models.ForeignKey(Icon) class Page(MenuItem): parent = models.ForeignKey(MenuParent) icon = models.ForeignKey(Icon) page_name = models.CharField(max_length=100, blank = True, null = True) user_access = models.ManyToManyField(User, verbose_name="Gebruikers", blank=True) group_access = models.ManyToManyField(Group, verbose_name="Groepen", blank=True) objects = PaginaManager() class Meta: verbose_name_plural = "Pagina's" The different subclasses are made such that a page can be directly under a title, or under a group. A group can only be under a title. I created a manager to get all the pages that a user has access to, either through user_access or through group_access. I however cannot get this to work decently. Could anyone help me create this manager? And a second question. If I want to add an order in which the menu item's are displayed, how would you go at this? -
Using distinct on annotations
I am trying to get a distinct list of items. The db has a created field which is datetime and I need it as a date for my query. So I added an annotation. The problem is that distinct won't work on the annotation... distinct_failed_recharges = recharges.filter( status=FAILED ).annotate( created_date=TruncDate('created') ).distinct( 'created_date', 'sim', 'product_type', 'failure_reason' ).values_list('id', flat=True) This is the error that I get: django.core.exceptions.FieldError: Cannot resolve keyword 'created_date' into field