Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Localhost not showing views
I am making a django app for storing files and I'm not seeing any errors on the runserver console but when I decide to go to localhost I get this error.Screenshot of localhost Which is odd because my urls.py is structured like this. urlpatterns = [ url('admin/', admin.site.urls), url(r'^$', index, name='index'), url(r'^(?P<slug>[\w\-]+)/$', document, name='document') ] And my models.py class Document(models.Model): title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, max_length=255) case_number = models.IntegerField() description = models.TextField(max_length=500) lawyer_name = models.CharField(max_length=250) case = models.FileField(upload_to='uploads/%Y/%m/%d/') def __str__(self): return self.title I'm using Django 1.11 and Python 3.6.2 -
Django filter foreign key with list
class Word(Model): word = CharField() categories = ManyToManyField('Category') class Category(Model): name = CharField() What is the query to get all words that have at least two categories: General and Garden? -
in Django passing form variable to model for auto create?
i'm newbie in django recently i have problem with my code and would like to ask how to pass referral_id from extended userform to MemberProfile model so that i can create automaticly when user model created. here is my code: models.py class MemberProfile(models.Model): member = models.OneToOneField(User, on_delete=models.CASCADE) referral_id = models.CharField(max_length=10) def create_profile(sender, **kwargs): if kwargs['created']: member_profile = MemberProfile.objects.create(member=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'referral_id'] def save(self, commit=True): user = super(UserForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.username = self.cleaned_data['username'] if commit: user.save() return user please give advice how to solve my problem thanks -
Django tests not finding my tests
When I run tests, django runs 0 tests. This is my project structure: manage.py - app/ - main_app/ - test/ - tests_v1 - tests_v2 I use this command: python manage.py test --pattern="tests_v*.py" Django runs 0 tests in 0 seconds. What am I missing? -
Combining Django F, Value and a dict to annotate a queryset
I have a scenario where I want to annotate a queryset with externally prepared data in a dict. I want to do something like the following: value_dict = {"model1": 123.4, "model2": 567.8} qs = ModelClass.objects.annotate( value=Value(value_dict.get(F('model__code'), 0)) ) The results currently show all as 0 as the F() doesn't seem to be the best way to look up the dict seeing as it doesn't return a string and it is resolved further down the track. Your help and suggestions would be much appreciated I'm currently on Python 3.6 and Django 1.11 -
Logical operations in django filter
I need to get my queryset where: (a="a" AND b=None) OR (a=None AND b="b") I know about Q objects in django, but this syntax doesn't works: cls.objects.filter(models.Q(a="a", b=None) | models.Q(a=None AND b="b")) I am absolutely sure my database contains expected objects. But all I get is the empty queryset. I guess there is some problem with syntax here. But where? -
Accessing Django Templates after modifing the Django layout structure
I re-organized Django,the following way: config - settings - base.py - local.py urls.py wsgi.py also apps: - apps(level0) - acc(level_1) - users(level_2) - templates - users - acc_control(level_2) -att(level_1) - notes (level_2) - notifications (level_2) - mark(level_1) - config (level0) - templates(level0) Some apps are directly in apps folder, ex mark, others are in other subfolders, ex users BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] My issue is regarding templates access, because I receive the following error: \apps\acc\users\templates\users\templates\users\detail.html (Source does not exist) is repeating the internal folder; In the View the template is set as: template_name = 'users/templates/users/detail.html' I tried also: template_name = '/users/detail.html' -
Migration error in django models.py database
My app is installed correctly and its models.py reads: from django.db import models class Album(models.Model): artist = models.CharField(max_lenght=250) album_title = models.CharField(max_lenght=500) genre = models.CharField(max_lenght=100) album_logo = models.CharField(max_lenght=1000) class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_lenght=10) song_title = models.CharField(max_lenght=250) But whenever I run python manage.py migrate, I get the following error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\dougl\desktop\django websites\twenty_one_pilots\downloads\models.py", line 3, in <module> class Album(models.Model): File "C:\Users\dougl\desktop\django websites\twenty_one_pilots\downloads\models.py", line 4, in Album artist = models.CharField(max_lenght=250) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\db\models\fields\__init__.py", line 1042, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'max_lenght' What could be wrong? I'm still a beginner and I'm still learning about … -
What are the video streaming solutions and corresponding Django packages available for the online coaching web app? [on hold]
We are creating a Web App for online IELTS coaching. What are the video streaming solutions and corresponding Django packages available for the same? -
Python Django threaded comments ordering
I am creating a django comments app. I have created model Comments class Comments(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add = True) likes = models.IntegerField(default = 0) path = models.CharField(validators=[validate_comma_separated_integer_list], max_length = 100, blank = True, editable = False) depth = models.PositiveSmallIntegerField(default = 0) The way i store path tree is that: First comment will have path [1]. Reply to first comment will have path [1,2] Second comment will have path [3] Second reply to first comment will have path [1,4]. And so on. So something like this should happen. [1] [1,2] [1,4] [3] I display it by fetching using the following line: comment_list = Comments.objects.order_by('-path') The problem is it displays newest comment first like this: [3] [1] [1,4] [1,2] How do i correct it so that it prints oldest comment first? -
nginx file upload freezes
I'm testing a django website deployment. The site works without any issues when I connect directly to my gunicorn localhost and run it in debug mode (so that django handles file uploads itself). When I access the site with debug mode turned off through nginx (it binds to the same gunicorn localhost) everything works just as well, except file uploads. Whenever I try to upload a file > 1MB, the upload freezes at some point (with a 1.3MB file, my browser freezes at 70%). I've installed nginx into a conda virtual environment (conda install --no-update-dependencies -c anacoda nginx). Here is the etc/nginx.conf file: # nginx Configuration File # https://www.nginx.com/resources/wiki/start/topics/examples/full/ # http://nginx.org/en/docs/dirindex.html # https://www.nginx.com/resources/wiki/start/ # Run as a unique, less privileged user for security. # user nginx www-data; ## Default: nobody # If using supervisord init system, do not run in deamon mode. # Bear in mind that non-stop upgrade is not an option with "daemon off". # daemon off; # Sets the worker threads to the number of CPU cores available in the system # for best performance. # Should be > the number of CPU cores. # Maximum number of connections = worker_processes * worker_connections worker_processes auto; ## Default: … -
create new does returns 'list' object has no attribute 'create'
I am trying to create a autocomplete input which can create a new object. class CellLineAutocomplete(autocomplete.Select2QuerySetView): create_field = 'cell_line_name' model = CellLine def has_add_permission(self, request): return True def get_queryset(self): if self.q: return CellLine.objects.filter(cell_line_name__icontains=self.q) return [] def get_result_label(self, item): return item.cell_line_name When clicking the create option I receive the following error: Traceback (most recent call last): File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 48, in dispatch return super(ViewMixin, self).dispatch(request, *args, **kwargs) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 116, in post result = self.create_object(text) File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 92, in create_object return self.get_queryset().create(**{self.create_field: text}) AttributeError: 'list' object has no attribute 'create' I access the code of the autocomplete git repo: def create_object(self, text): """Create an object given a text.""" return self.get_queryset().get_or_create( **{self.create_field: text})[0] and edited it to work for me: def create_object(self, text): """Create an object given a text.""" return self.model.objects.get_or_create( **{self.create_field: text})[0] Is there a better way to solve my … -
display console output inside a template in Django
I'm working on a project in which I'm using Python(3.6) and Django(1.10), from few days I'm struggling to display the console output inside a Django template but couldn't find any solution. For example code below prints various statements to the console, I want to display these messages to the Django templates. if form.is_valid(): deployment = form deployment.user = request.user deployment.project = form.cleaned_data['project'] deployment.deploymentName = form.cleaned_data['deploymentName'] deployment.zone = form.cleaned_data['zone'] deployment.cluster = form.cleaned_data['cluster'] deployment.sourceFile = form.cleaned_data['sourceFile'] deployment.save() # Start awd deployment from here tempdir = tempfile.mkdtemp() saved_unmask = os.umask(0o077) temp_dir_path = os.path.join(tempdir) archive_path = os.path.join(settings.MEDIA_ROOT, 'archives/', deployment.sourceFile.name) print(archive_path) # Extract uploaded archive inside temporary dir patoolib.extract_archive(archive_path, outdir=temp_dir_path) # Try to retrieve path of dockerfile directory docker_glob = os.path.join(temp_dir_path, "*", "Dockerfile") print(docker_glob) docker_file = glob.glob(docker_glob)[0] docker_folder = os.path.dirname(docker_file) print(docker_folder) docker_client = docker.from_env() print("Start Building your docker image...") docker_client.login(username='arycloud', password='Abd37214@cloud') docker_client.images.build(path=docker_folder, gzip=False, tag=deployment.deploymentName) image = docker_client.images.get(deployment.deploymentName) shutil.rmtree(tempdir) img_id = image.short_id print(img_id) # prepare tag for image tag = deployment.deploymentName.lower() docker_api_client = docker.APIClient( base_url='unix://var/run/docker.sock') tagged = docker_api_client.tag(image=img_id, repository='arycloud/istio_dep', tag=tag, force=True) if tagged is True: print('image has been tagged!') print('Pushing....') pushing_image = docker_client.images.push(repository='arycloud/istio_dep', tag=tag) print(pushing_image) -
How to Remove duplicate data by field ‘agent__id’ and 'account', and count the field 'agent__id' by the same data
I want to Remove duplicate data by field ‘agent__id’ and 'account', and count the field 'agent__id' by the same data 。 My code is follow: list(AgentPayLog.objects.values('agent__id', 'account'). distinct().values('agent__id').annotate(agent_count=Count(F('agent'))). values('agent__id', 'agent_count')) the data is following: account_id agent_id 30001 1 30001 2 30001 2 the code print is following: agent_id agent_count 1 1 2 2 I want the data is following: agent_id agent_count 1 1 2 1 -
Disable double click in auto generated select tag
Greeting, I've successfully created a select field that looks exactly like in django admin manytomany field in my html page EXAMPLE. but now i want to disable on double click function from this field, I've tried dozen of method already from previous asked question in this site and I've already disable the entire page double click function but I still able to double click, can anyone help me with this thanks, below is my code : html : <div class="field"> <select name="settings-user" id="id_settings-user" multiple="multiple" class="selectfilter" data-field-name="User" data-is-stacked="0"> <option value={{ form.user }}</option> </select> </div> javascript : <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/third_party/jquery/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="/static/admin/js/SelectBox.js"></script> <script type="text/javascript" src="/static/admin/js/SelectFilter2.js"></script> <script> $(document).ready(function(){ $("*").dblclick(function(e){ e.preventDefault(); }); }); </script> -
How to check Post request of this format using Postman
I am checking json object post request using postman.The data is in format { "user": { "first_name": "akash", "last_name": "gondhale", "username": "akash@gmail.com", "email": "akash@gmail.com", "groups": [], "is_active": true }, Every time I am sending request I am getting error in postman is { "user": [ "This field is required." ] } How to send this fields as a Post request using Postman to Django server -
Execute windows script with python to startup django server and open browser
I'd like to write a python script to do following things. startup Django local server(manager.py runserver) Open browser and direct to http://127.0.0.1:8000 After Close the windows console, kill the python background task. For now, my script is something like below cmd = "python manage.py runserver" subprocess.call(cmd, shell=True) time.sleep(5.0) cmd = 'start "" "http://127.0.0.1:8000"' subprocess.Popen(cmd, shell=True) This script worked. But I'd like ask the proper ways to do this. For example, How to check "manager.py runserver" command has finished and startup, then open browser, instead sleep 5 Seconds. Can I detect Django server console be closed and do some tasks like kill process. -
Django managing state of a parent model, based on "child models" (models that have a fk to the parent model)
Designing a a system which needs state transitions of a model which are based on transitions of other models. I'm using Django FSM Example: class Foo(models.Model): baz = models.Charfield() state = FSMField(default='new') class Bar(models.Model): x = models.CharField() state = FSMField(default='draft') foo = models.ForeignKey(Foo) Use Case: Foo can have the following states - new, draft, complete, pending_approval, approved Foo can have multiple Bars Bar can have the following states - draft, complete Foo should move to complete automatically when all Bar's are complete, how can this be achieved -
Django user.save() not working once deployed
I have two forms on a webpage, which can be saved and this should update the user data. This works perfectly locally but once I deploy my application to Heroku the user.save() method does not work for one of the two forms. In my logs I see the following: 10.76.24.178 - - [10/Jan/2018:09:45:39 +0000] "POST /profile/edit HTTP/1.1" 500 27 "http://www.url.nl/profile/edit/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5" 2018-01-10T09:45:39.777946+00:00 heroku[router]: at=info method=POST path="/profile/edit" host=www.url.nl request_id=56c38d5d-138b-427d-9694-ac8e0dc2976f fwd="145.109.1.117" dyno=web.1 connect=0ms service=246ms status=500 bytes=234 protocol=http The method that causes this error is user.save() and this same method works on heroku for the other form and works for both forms locally. Any idea how I can resolve this or how I can get more insight into what is going wrong? -
Push rejected to herokuapp
I am trying to host my dango rest app on heroku. When i run git push heroku master I get the error log remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.4 (you are using python-3.6.3, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.4). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing requirements with pip remote: Collecting pkg-resources==0.0.0 (from -r /tmp/build_76cc8692e5f28e80c394427df6e4d58b/requirements.txt (line 9)) remote: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r / tmp/build_76cc8692e5f28e80c394427df6e4d58b/requirements.txt (line 9)) (from versions: ) remote: No matching distribution found for pkg- resources==0.0.0 (from -r /tmp/build_76cc8692e5f28e80c394427df6e4d58b/requirements.txt (line 9)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to myapp. remote: To https://git.heroku.com/myapp.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/myapp.git' push is rejected by heroku. please help. -
When in run test cases then I will get this error: psycopg2.OperationalError: cursor "_django_curs_140351416325888_23" does not exist
I'm tring to run test cases I got below error. Run commond : python manage.py test Type 'yes' if you would like to try deleting the test database 'test_project_management_db', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/runner.py", line 546, in setup_databases self.parallel, **kwargs File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/utils.py", line 187, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 77, in create_test_db self.connection._test_serialized_contents = self.serialize_db_to_string() File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 121, in serialize_db_to_string serializers.serialize("json", get_objects(), indent=None, stream=out) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/serializers/__init__.py", line 129, in serialize s.serialize(queryset, **options) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/serializers/base.py", line 80, in serialize for count, obj in enumerate(queryset, start=1): File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 117, in get_objects for obj in queryset.iterator(): File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 880, in execute_sql cursor.close() psycopg2.OperationalError: cursor "_django_curs_140351416325888_23" does not exist -
Preparing a user registration site using django including Login for existing user
A beginner, recently started to learn Django I have gone through the basic tutorial of Django for creating a first app(POLLING) given in documentation. I wanted to create a dummy website through which I'll be able to register a new user and login an existing user and logout them after successfully logging in. I tried to use Django Documentation for this (https://docs.djangoproject.com/en/1.11/topics/auth/default/#user-objects) But I don't get how to use the info in the documentation and convert that info into my views, forms and template ?? In other words I'm just confused on how to proceed!! -
django rest framework- usrename field showing "Deleted" when related lookup
I'm using Django==1.11 and django rest framework==3.7.3 I make two models - Post and User (Post object have their own user) When I get request to Post list view (in PostViewSet), I can't see my user's username field. (It's email now) - Only I can see is "Deleted". Is it because of Django itself, or django rest framework? I searched both code in github, but I can't find any code that make username field to "Deleted". I also trying making user_email field in serializer, but it happens the same. What happened? p.s. I use allauth and django-rest-auth for accounts. But I couldn't found any code too. Below is api response and part of my code. It obviously has email, and I checked twice in db. API response for posts { "user": { "id": 3, "password": "", "last_login": null, "is_superuser": false, "created_at": "2017-12-01T16:27:41.335721+09:00", "updated_at": "2017-12-01T16:27:41.335741+09:00", "email": "Deleted", "user_type": 2, "extra": null, "is_active": true, "is_staff": false, "groups": [], "user_permissions": [] }, "title": "test", "description": "", "logo": null, "deadline": null, "slug": "test-y3jj", "created_at": "2018-01-08T10:55:06.397192+09:00", }, Post serializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ( "user_email", "user", "title", "description", "logo", "deadline", "slug", "created_at", ) read_only_fields = ( "id", "slug", "created_at", ) … -
HighCharts Render Annotated Queryset in Jinja2 Template
In my Jinja2 template I want to render a JavaScript array similar to this: [{ name: 'test', data: [ [Date.UTC(1970, 9, 29), 0], [Date.UTC(1970, 10, 9), 0.4], ... ] }, { name: 'Transport', data: [ [Date.UTC(1970, 10, 25), 0], ... ] }] I already managed to build a rather complex queryset in my Django code. It looks like the following: (Category.objects.filter(expense__period=p) .annotate(day=Trunc('expense__date', 'day')) .values('title', 'day') .order_by('title', 'day') .annotate(Sum('expense__amount'), Count('id'))) Which results in: TITLE DAY EXPENSE__AMOUNT__SUM ID__COUNT test 2017-12-30 00:00:00+00:00 10.00 1 test 2018-01-08 00:00:00+00:00 2.70 1 test 2018-01-09 00:00:00+00:00 62.00 2 Transport 2018-01-03 00:00:00+00:00 111.00 1 Transport 2018-01-09 00:00:00+00:00 15.00 1 Transport 2018-01-10 00:00:00+00:00 12.00 1 I am stuck at this point and look for a performant way to apply the retrieved data to my template. Any idea how to break the rows into categories/loop over the results without querying the database multiple times? My models.py is: class Period(models.Model): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title') class Category(models.Model): title = models.CharField(max_length=100) class Expense(models.Model): period = models.ForeignKey(Period, on_delete=models.CASCADE, null=True) date = models.DateField(default=date.today) title = models.CharField(max_length=100) category = models.ForeignKey(Category, null=True) amount = MoneyField(max_digits=10, decimal_places=2, default_currency='EUR') -
LookupError: No installed app with label 'myproject' when get /admin/
i am using django'admin site, but an error occured, the error is "LookupError: No installed app with label 'myproject'" i have add myapp in installed-apps,but what is the app label with "myproject", anyone who can tell me what's going on?