Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving Angular app using Django
I have a DjangoREST-Nginx-Gunicorn build, and I am using angular as the frontend. This is the first time I work with this stack together, although I'm very familiar with Django. From what I'm used to, I'm serving pages using render with django templating. Since I am using REST and angular, the project build is kind of different and I wonder how should I serve the angular app through this stack. This is my project build βββ client β βββ client-app β βββ index.html βββ gunicorn_start.sh βββ run β βββ gunicorn.sock βββ server β βββ config β βββ __init__ β βββ manage.py β βββ __pycache__ β βββ requirements.txt β βββ static β βββ urls.py What I wish to do, is to serve client/index.html and let the angular app handle everything from there on. What would be the right way to do so? -
How to manage mongodb connection using mongoengine django
I am running a django project and using mongoengine as my ORM for MongoDB. The project uses daemons, celery, crons and calling django custom commands which are using the django project and stores massive data in the database (MongoDB Atlas). Here's my settings.py file where I'm building the mongodb connection using mongoengine CONNECTION_STRING = 'mongodb://{user}:{pwd}@{host}/{db}?replicaSet={replicaset}&ssl={ssl}&authSource={auth_source}'.format( user=env('DB_USERNAME'), pwd=env('DB_PASSWORD'), host=env('DB_HOST'), db=env('DB_DATABASE'), replicaset=env.str('DB_REPLICASET'), ssl=env.str('DB_SSL'), auth_source=env.str('DB_AUTH_SOURCE') ) DB_CONNECTION = mongoengine.connect(host=CONNECTION_STRING, connect=False) Suddenly I'm gettig alerts from MongoDb Atlas that connections have been overused. And I'm not sure how to handle connections in an optimised way or my existing settings are already optimised? Below is the screenshot which shows 450+ connections always open. Do I have to close the connection in every request class? any help is much appreciated. -
ElasticBeanstalk totally stucked when deploying
I am running Django app on elastic beanstalk, sometimes it got totally stuck when deploying, when it gets stuck, the website is not responding, the eb logs is not responding, i can't even ssh into the EC2 instance, it's just hanging forever. In this situation I have no means to have any useful debugging information to troubleshoot it. The only way to get out of this stucking situation is to terminate the EC2 instance manually and let elasticbeanstalk create a new one. Also sometimes it failed with this reason: Cannot allocate memory - /opt/elasticbeanstalk/hooks/appdeploy/enact/01stop_xray.sh I did research and a lot of ppl suggest increasing swapping memory on EC2, however this always happens before I can run the increasing swapping command. what else can I do? Notices that I am running django Channel in this env. here are my config: supervisord config: [unix_http_server] file=/opt/python/run/supervisor.sock ; (the path to the socket file) ;chmod=0700 ; socket file mode (default 0700) ;chown=nobody:nogroup ; socket file uid:gid owner [supervisord] logfile=/opt/python/log/supervisord.log ; (main log file;default $CWD/supervisord.log) logfile_maxbytes=10MB ; (max main logfile bytes b4 rotation;default 50MB) logfile_backups=10 ; (num of main logfile rotation backups;default 10) loglevel=info ; (log level;default info; others: debug,warn,trace) pidfile=/opt/python/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) β¦ -
how to use python to create a dynamic website without framework like django or flask? [on hold]
how to use python to create a dynamic website without framework like django or flask ? I mean here: You can work in PHP without any framework such as Codeigniter or laravel and you can work with ......... But I want to program the site from scratch without a framework and in Python language ? Do you have any suggestions for books or youtube videos -
Masterpass Merchant Integration API on Django 1.11
I am currently developing web based POS and Django 1.11 as my backend. My experience on API is only REST API on Django. I looked into Masterpass Merchant Integration API, I don't understand the API integration mentioned on the documentation. If there any alternatives for master card payment please suggest. -
collectstatic not reading settings file using git push heroku master but reads it when run on its own
If I enter >>> git push heroku master I get an error. Notice line 25 stating that I have not set the STATIC_ROOT setting. 1 remote: -----> $ python manage.py collectstatic --noinput 2 remote: Traceback (most recent call last): 3 remote: File "manage.py", line 22, in 4 remote: execute_from_command_line(sys.argv) 5 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line 6 remote: utility.execute() 7 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute 8 remote: self.fetch_command(subcommand).run_from_argv(self.argv) 9 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv 10 remote: self.execute(*args, **cmd_options) 11 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute 12 remote: output = self.handle(*args, **options) 13 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle 14 remote: collected = self.collect() 15 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect 16 remote: handler(path, prefixed_path, storage) 17 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file 18 remote: if not self.delete_file(path, prefixed_path, source_storage) 19 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 260, in delete_file 20 remote: if self.storage.exists(prefixed_path): 21 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/files/storage.py", line 392, in exists 22 remote: return os.path.exists(self.path(name)) 23 remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 50, in path 24 remote: raise ImproperlyConfigured("You're using the staticfiles app " 25 remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. 26 remote: 27 β¦ -
Django Heroku Push Fails With Grep Usage Error After First Time
I have a simple Django app that I'm trying to deploy to Heroku. I've followed the steps outlined in the Deploy your application to Heroku section here: https://devcenter.heroku.com/articles/deploying-python. I'm working off of the branch heroku. When I do git push heroku heroku:master, the first time it's able to push, everything succeeds and the app is deployed, however when I go to the app home page, I get a 503 error indicating that favicon.ico is missing. Then I make a commit with any small change, and try pushing again, and I get the following error: Counting objects: 4, done. Delta compression using up to 8 threads. Compressing objects: 100% (4/4), done. Writing objects: 100% (4/4), 360 bytes | 0 bytes/s, done. Total 4 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: Usage: grep [OPTION]... PATTERN [FILE]... remote: Try 'grep --help' for more information. remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute β¦ -
Django CBV UserPassesTestMixin test_func not running
The test_func doesn't appear to run at all. Right now I'm just checking if the user is staff, as an easy test. Here's the code: class MyModelCreate(CreateView, UserPassesTestMixin): def test_func(self): print("checking if user passes test....") return self.request.user.is_staff model = MyModel .... However, when I go to the create page for this model, anyone can edit it, and there is no output to the python console showing that the test_func runs. The view is called: urlpatterns = [ ... url(r'^create/$', views.MyModelCreate.as_view(), name='my_model_create'), ] -
Trying to allow user to select birthday - django
I have a form in a django project, and i want the user to enter his birthday so that i can be saved in the database and used later in the project... I have a model and i want to create a Modelform which will ask for the date and then format it and save it in the database. i have been trying to figure this out for 3 days and cant get it to work.. I have had to delete my database file around 5 times because it was not working and messing up the database... WHen the user submits the form, the return is three seperate items which include dob_month, dob_day, dob_year with the correct date informaiton Here is what i have so far. models.py file class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # server first_name = models.CharField(max_length=25, default='first') last_name = models.CharField(max_length=25, default='last') dob = models.DateField(auto_now_add=False, blank=True) city = models.CharField(max_length=45) # user state = models.CharField(max_length=25, default='state') phone = models.BigIntegerField(default=0) # user privacy = models.SmallIntegerField(default=1) # user created = models.DateTimeField(auto_now_add=True) # server here is thhe forms.py file class ProfileForm(forms.ModelForm): split_choices = (('1', 'public'), ('2', 'private')) privacy = forms.TypedChoiceField( choices=split_choices, widget=forms.RadioSelect, coerce=int ) dob = forms.DateField(widget=extras.SelectDateWidget) class Meta: model = Profile β¦ -
django rest framework viewset permission based on method
So I'm writing my first project with DRF and I'm having some issues with setting up permissions for my viewsets. I already have authentication working with djangorestframework-jwt. Currently, I have a few different ViewSets defined. What I would like to do is allow the owner of a model object to make any changes they would like to that object, but prevent everyone else (aside admins) from even viewing the objects. Basically, I need a way of applying permission classes to specific methods to allow only admins to view 'list', owners to 'update, destroy, etc' and authenticated users to 'create'. Currently I have something like this: class LinkViewSet(viewsets.ModelViewSet): queryset = Link.objects.all() serializer_class = LinkSerializer with a model of class Link(models.Model): name = models.CharField(max_length=200) url = models.URLField() # another model with a OneToMany relationship section = models.ForeignKey('homepage.LinkSection', related_name='links', on_delete=models.CASCADE owner = models.ForeignKey('homepage.UserProfile'), related_name='links', on_delete=models.CASCADE) and the permissions class I want to apply class IsOwner(permissions.BasePermission): def has_object_permissions(self, request, view, obj): return obj.owner == request.user.userprofile I'm sure it's possible to achieve this by writing completely custom views but I have a gut feeling that there is an easier way to do this especially since this is basically the last thing I have to do β¦ -
TransactionManagementError obscuring root exception
When code is executing within a transaction.atomic block and an exception is raised, the database handler is marked as needing rollback. If, still within that transaction.atomic block a subsequent query is performed, the following error will be raised: TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' At this point, the actual root error is obscured and pretty difficult to access, leaving you needing to jump into Django's transaction code. A simple example that can result in this error: def someview(request): with transaction.atomic(): // do some things instance = SomeModel.objects.create(...) // some other db queries @receiver(post_save, sender=SomeModel) def non_critical_side_effect( sender, instance, created, raw, using, update_fields, **kwargs ): try: // some query that causes a database error SomeModelLog.objects.create(some_non_none_field=None) except IntegrityError: //notify ourselves, go on pass How do you work out what's really going on when you hit this scenario, and how do you routinely avoid this scenario? (Self-answer below - but genuinely interested in other's thoughts!) -
ImportError: cannot import name 'UserForm'
I'm using pretty much the same code that I have already gotten to work in a different project so I can't really pinpoint the problem other then it looks to be coming from something in my URLs as it pertains to the views? Other than that I'm not really sure why I'm getting this error. Please help. Error Traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/base.py", line 327, in execute self.check() File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks_run_checks return checks.run_checks(**kwargs) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/anaconda/envs/test/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/anaconda/envs/test/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/anaconda/envs/test/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/anaconda/envs/test/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/anaconda/envs/test/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File β¦ -
Why am I getting "NoReverseMatch at /" error?
I am getting the next NoReverseMatch error: NoReverseMatch at / Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name. Exception Location: /home/ivan/.local/lib/python2.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/ivan/My_website/essostrade (copy 1)', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/ivan/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk2'] Server time: Fri, 25 Aug 2017 22:51:14 +0000 But the thing is that there is no 'logout' neither in the highlighted main.js line in the template, nor somewhere else in the templates. Here are my templates: main.html: {% extends "base.html" %} {% load staticfiles %} {% block additional_css %} <link type="text/css" href="{% static "main.css" %}" rel="stylesheet"> {% endblock %} {% block content %} <div id="header"> <h1>ΠΡΠ°Π°Π²ΠΎΡΡΠΊΠ°Ρ Π»Π°Π²ΠΎΡΠΊΠ°</h1> </div> <!-- <div id="leftmenu"> <ul> {% url "main" as page_url %} <li><a href="{{ page_url }}"{% if page_url == current_url %} class="current"{% endif %}>ΠΠ»Π°Π²Π½Π°Ρ</a></li> {% if user.is_authenticated %} <li class="indented"><a href="/admin/">ΠΠ΄ΠΌΠΈΠ½ΠΊΠ°</a></li> <li class="indented"><a href="{% url "logout" %}">ΠΡΠΉΡΠΈ</a></li> {% endif %} </ul> </div> --> <div id="main"> {% block main %} {% β¦ -
how to ssl encrypt my django project on digitalocean with gunicorn server
i can't figure out what to do using the tuorial on that page https://certbot.eff.org/#ubuntuxenial-other could anyone help please -
How to save ManyToMany field with a through relationship
I'm trying to register and link some teams with video games. Until now, now problem, I had these models class Team(models.Model): name = models.CharField(max_length=15, null=False) tag = models.CharField(max_length=4, null=False) description = HTMLField(blank=True, null=True) logo = models.FileField(upload_to=user_directory_path, validators=[validate_file_extension], blank=True, null=True) games = models.ManyToManyField(Games, verbose_name="Jeu") owner = models.ForeignKey(User, verbose_name="Créateur") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return self.name class Games(models.Model): guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID") title = models.CharField(max_length=100, null=False, verbose_name="Titre") logo = models.FileField(upload_to='media/games/', validators=[validate_file_extension], blank=True, null=True, verbose_name="Logo du jeu") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return self.title And I saved or update my team thanks to this form : class GamesChoiceField(ModelMultipleChoiceField): def label_from_instance(self, obj): logo = '<img src="%s{url}"/>'.format(url=obj.logo) %(media) return mark_safe("{logo} {title}".format(title=obj.title, logo=logo)) class TeamForm(forms.ModelForm): game = Games.objects.all() games = GamesChoiceField(widget=forms.CheckboxSelectMultiple, required=True, queryset=game) logo = forms.ImageField(required=False, widget=forms.FileInput) class Meta: model = Team fields = ('name', 'tag', 'logo', 'games' ) I used this view to save my form. Very simple : form = TeamForm(request.POST, request.FILES, instance=Team.objects.get(owner=request.user)) if form.is_valid(): form.save() The cool stuff is I can add an instance. So when the form is called, it remembers my last registering. So for the field 'game', I have some ⦠-
Django path to templates folder in settings.py
I am newly learning Django and was following the Learn Django 1.11 Tutorial. Here is my current project tree: βββ manage.py βββ muypicky β βββ init.py β βββ old_settings.py β βββ settings β β βββ base.py # Contains the settings (like shown in the tutorial) β β βββ init.py β βββ urls.py β βββ wsgi.py βββ requirements.txt βββ restaurants βββ templates # Tempelates Folder βββ index.html I am trying to add the path to the tempelates folder in the settings folder. But the error shown django.template.loaders.filesystem.Loader: .../muypicky/tempelates/index.html (Source does not exist) Current setting.py file TEMPLATES = [{ 'DIRS': [os.path.join(BASE_DIR, 'tempelates')], },] Looking at the error, the file path is wrong because it goes into /muypicky/tempelates which is incorrect. So how do I get to root folder and then into tempelates folder with the given file tree in setting.py (base.py). Any further queries, just ask and many thanks in anticipation. -
django: IntegrityError: UNIQUE constraint failed: startupconfort_startup.id
Each time the Django ORM is creating an object, I'm trying to create an object but I'm getting the following error In [1]: Startup.objects.count() Out[1]: 0 In [2]: Startup.objects.create(title='airbnb') --------------------------------------------------------------------------- IntegrityError ... IntegrityError: UNIQUE constraint failed: startupconfort_startup.id In [3]: Startup.objects.count() Out[3]: 1 In [4]: Startup.objects.last() Out[4]: <Startup: airbnb> In [5]: Startup.objects.create(title='facebook') ... IntegrityError: UNIQUE constraint failed: startupconfort_startup.id In [6]: Startup.objects.count() Out[6]: 2 my model class Startup(TimeStampedModel): title = models.CharField(verbose_name=_(u"Title"), max_length=32) slug = models.SlugField(blank=True, null=True) brand_url = models.URLField(blank=True, null=True) At first I think the Django ORM didn't create the object but yes it does have created it. But I don't know why do I have this integrity error when in fact the ORM is creating the object -
ConnectionDoesNotExist at django 1.10.5 project multiple data base
I am trying to connect with a mysql database from which i need to take some information and store in a postgres database. Both connection are configured in the database settings. I'm trying to create the models from de mysql database by python manage.py inspectdb --database=bd_mysql > app_name/models_mysql.py but i've got ConnectionDoesNotExist("The connection %s doesn't exist" % alias) as error. The mysql databse alrady exists. I've got some models and migrations for postgres database, different from the mysql database. -
How to save more than one record using django forms
I have a simple form, this is a part of my view code: if request.method == 'POST': form = testForm( request.POST ) if form.is_valid(): record = form.save(commit=False) record.save() Everything works great, the tools saves data, but I am trying to send more than one record, I mean I am sending for an instance 10 records, but program can save only one. what is the best solution to solve this problem ? Thanks in advance, -
Move types to settings.py
In one of my apps I have a file called lifecycle with types like so TYPES = { 'viaf:personal': "986a7cc9-c0c1-4720-b344-853f08c136ab", # E21 Person 'viaf:corporate': "3fc436d0-26e7-472c-94de-0b712b66b3f3", # E40 Legal Body 'viaf:geographic': "dfc95f97-f128-42ae-b54c-ee40333eae8c" # E53 Place } I want to move them into my settings.py folder so that can be configurable from there. I am new to Django and am not sure how to go about this. What is the best way to go out doing so? -
How to optimize code in django - python
I'm trying to show the permissions that a group has in django this to show them in a "drupal" style template and I'm doing them but my problem is that it takes too long to make the query and paint it in the template. My concern is there is some way to improve to optimize my code. view img up(accomplished),down(views and template.html) views : def GroupPermissionsView(request): titulo = "Groups Permissions" group=Group.objects.all() permission = Permission.objects.all() context = Context({ 'titulo': titulo, 'group':group, 'permission':permission, }) return render( request, 'forms_permissions.html', context ) template: <table class="table table-striped table-inverse table-responsive table-bordered"> <thead> <tr> <th>Permission</th> {% for grupo in group %} <th>{{grupo}}</th> {% endfor %} </tr> </thead> <tbody> {% for permiso in permission %} <tr> <td><b>{{permiso.name}}<b></td> {% for grupo in group %} {% if permiso in grupo.permissions.all %} <td><input type="checkbox" name="" checked="checked"></input></td> {% else %} <td><input type="checkbox" ></input></td> {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table> -
Django, creating a functional search bar and search results page
I'm having trouble working with inherited code to make a functional search bar. I've been having the most trouble properly creating a search_results page. I stripped down my search_results page to having only one line. search_results.html: <div>You searched for {{ query }}</div> but right now, the search_results page doesn't render {{ query }}. No text that the user previously entered appears. All that shows up on that page is "You searched for" searchbox.html <form class="search" action="{% url 'search' %}" method='post'> {% csrf_token %} <input type="search" placeholder="Search here..." name="usr_query" value='{{ request.GET.usr_query }}' required> <button type="submit">Search</button> </form> views.py def search(request): query = request.POST['usr_query'] print "QUERY: " print query t = loader.get_template('gtr_site/test_search_results.html') c = Context({ 'query': query,}) return HttpResponse(t.render(c)) I was getting a little cautious and added that "print" statement... and it does print out what the user enters in the search bar. But that isn't being generated on my search_results page. Whats the reasoning for this? -
Adding Additional Hallo.js formatting features to Wagtail CMS RichTextField
How can I enable halloformat underline and hallojustify in Wagtails RichTextEditor? There doesn't seem to be any documentation on this. Thank you. -
count distinct number for multiple table fields in one queryset django
I need to count sum of distinct values of for each column(aa, bb, cc in this case) from a table with one queryset. If I do this: x = a_table.objects.filter(m = m_number) .annotate(a=Count('aa', distinct=True)) .annotate(b=Count('bb', distinct=True)) .annotate(c=Count('cc', distinct=True)) .values_list('a', 'b', 'c') When I print x, I got: <QuerySet [(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)]> How do I get result like this within one queryset: a=4 b=4 c=4 -
Multiple nested inline forms in Django
I'm trying to build a form with nested inline forms with models AA, BB and CC (below) . aa0 . bb0 . cc0 . cc1 . bb1 . bb2 . cc2 . cc3 I tried to use extra_views InlineFormSet and UpdateWithInlinesView (below) but I got the message "'CC has no ForeignKey to 'AA'". How could I implement this nested inline forms with or without extra_views? I prefer not to use outdated libraries. There is an answer to a similar problem here, but with an outdated library. # models class AA(models.Model): title = models.CharField(max_length=70) class BB(models.Model): title = models.CharField(max_length=70) aa = models.ForeignKey(AA) class CC(models.Model): title = models.CharField(max_length=70) bb = models.ForeignKey(BB) # forms class AAForm(forms.ModelForm): class Meta: model = models.AA fields = ['title'] # views from extra_views import InlineFormSet, UpdateWithInlinesView class BBInline(InlineFormSet): model = models.BB class CCInline(InlineFormSet): model = models.CC class EntryUpdateView(UpdateWithInlinesView): model = models.AA form_class = forms.AAForm inlines = [BBInline, CCInline]