Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get own applications in Django
Is there a way I can get a list of the applications that belong to a Django project itself (ignoring the apps that are installed with pip). Said with other words: can I exclude the apps that were installed with pip from settings.INSTALLED_APPS? -
Store static files on S3 but staticfiles.json manifest locally
I have a Django application running on Heroku. To store and serve my static files, I'm using django-storages with my S3 bucket, as well as the standard Django ManifestFilesMixin. I'm also using django-pipeline. In code: from django.contrib.staticfiles.storage import ManifestFilesMixin from storages.backends.s3boto import S3BotoStorage from pipeline.storage import PipelineMixin class S3PipelineManifestStorage(PipelineMixin, ManifestFilesMixin, S3BotoStorage): pass The setup works, however the staticfiles.json manifest is also stored on S3. I can see two problems with that: My app's storage instance would have to fetch staticfiles.json from S3, instead of just getting it from the local file system. This makes little sense peformance-wise. The only consumer of the manifest file is the server app itself, so it might as well be stored on the local file system instead of remotely. I'm not sure how significant this issue is since I suppose (or hope) that the server app caches the file after reading it once. The manifest file is written during deployment by collectstatic, so if any already-running instances of the previous version of the server application read the manifest file from S3 before the deployment finishes and the new slug takes over, they could fetch the wrong static files - ones which should only be served … -
django extensions OSError: [Errno 2] "dot.exe" not found in path
I am trying to install django-extensions to visualize my models in my Django rest project. Complete stacktrace: (vb_env_drf) D:\Development\Bern\VB_rewrite\VB_DRF_Backend>pip install django-extensions Collecting django-extensions Using cached https://files.pythonhosted.org/packages/d4/b5/f141b351b49db2cb4c855cd8adbdb98cc49f3944a924ddfe51790bb46402/django_extensions-2.0.7-py2.py3-none-any.whl Requirement already satisfied: six>=1.2 in d:\development\bern\vb_rewrite\vb_env_drf\lib\site-packages (from django-extensions) (1.11.0) Requirement already satisfied: typing; python_version < "3.5" in d:\development\bern\vb_rewrite\vb_env_drf\lib\site-packages (from django-extensions) (3.6.4) Installing collected packages: django-extensions Successfully installed django-extensions-2.0.7 You are using pip version 10.0.0, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (vb_env_drf) D:\Development\Bern\VB_rewrite\VB_DRF_Backend>python manage.py graph_models -a -o myapp_models.png CommandError: Neither pygraphviz nor pydotplus could be found to generate the image (vb_env_drf) D:\Development\Bern\VB_rewrite\VB_DRF_Backend>pip install pyparsing Collecting pyparsing Using cached https://files.pythonhosted.org/packages/6a/8a/718fd7d3458f9fab8e67186b00abdd345b639976bc7fb3ae722e1b026a50/pyparsing-2.2.0-py2.py3-none-any.whl Installing collected packages: pyparsing Successfully installed pyparsing-2.2.0 You are using pip version 10.0.0, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (vb_env_drf) D:\Development\Bern\VB_rewrite\VB_DRF_Backend>pip install pydot Collecting pydot Requirement already satisfied: pyparsing>=2.1.4 in d:\development\bern\vb_rewrite\vb_env_drf\lib\site-packages (from pydot) (2.2.0) Installing collected packages: pydot Successfully installed pydot-1.2.4 You are using pip version 10.0.0, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (vb_env_drf) D:\Development\Bern\VB_rewrite\VB_DRF_Backend>python manage.py graph_models -a -o myapp_models.png Traceback (most recent call last): File "manage.py", line 22, in … -
Why can't we get the number of connected websockets in a channel group in django-channels?
I've read some of the issues related to this question and some of the questions asked here on stack overflow and as far as I can understand the overall answer is that because of some technical details, the performance drops off dramatically as you scale up a system. But I can't understand then how the channels can determined to which sockets send the messages if it doesn't keep track of the connected ones!? -
React duplicating a rendered div on click
I am learning React by migrating my project from js/jquery to react. In my project I have a function that duplicates a div block(with changed ids and data) on button click. So for example I have a div remade in react and a button that should add a new div on click: render() { return ( <div className="expense-block" id="expense-block-0" data-block="0"> </div> <button type="button" className="btn btn-primary custom-add-button add-row" onClick={this.addRow}><i className="fas fa-plus"></i> </button> ) } When I click the button it should duplicate the div with new ids. The result should be: render() { return ( <div className="expense-block" id="expense-block-0" data-block="0"> </div> <div className="expense-block" id="expense-block-1" data-block="1"> </div> <button type="button" className="btn btn-primary custom-add-button add-row" onClick={this.addRow}><i className="fas fa-plus"></i> </button> ) } How can I achieve this in React without using 0 js/jquery? Is that even possible? -
Ignore {% extends %} when included (Django templates)
I have a template which I want to be accessable from include and also to be accessable as a standalone page with extends. There is a Base.html: <!-- some html, navbar --> {% block content %} {% endblock %} <!-- footer and other stuff --> There is a HomePage.html: {% extends 'Base.html' %} {% block content %} <!-- some HomePage content --> {% endblock %} There is a MyTemplate.html: {% extends 'Base.html' %} {% block content %} <!-- some content from MyTemplate --> {% endblock %} What I want is to add MyTemplate.html's content to HomePage. If I will add {% include 'MyTemplate.html' %} to HomePage.html then I will get two navbars because Base.html is extended two times. But I still need MyTemplate.html be accessable as a standalone page with navbar and other Base.html stuff. How to ignore {% extends %} if the template is included from another one? At the moment as a workaround I added another file, say MyPage.html. This file extends Base.html and includes MyTemplate.html. HomePage.html also includes MyTemplate.html and MyTemplate.html doesn't extend anything. I just wanted to know if there is more appropriate way to do what I want. -
One-To-One relationship with two models on one side
I have three relations User, Film and Rating. For now, I have done my model Rating like so: class Rating(models.Model): ... user = models.ForeignKey('User', on_delete=models.CASCADE) film = models.ForeignKey('Film', on_delete=models.CASCADE) ... However here, a user can have several ratings for the same film and I would like that a user can only rate a film one time. So I added this after the previous code: class Meta: unique_together = ('user', 'film') Is there a better way to enforce the unicity mentioned above? I feel like this is just a lazy way of enforcing something that could have been done using relationships. -
django queryset annotate all field in childtable
models.py class Userinfo(models.Model): useruid = models.BigAutoField(db_column='UserUID', primary_key=True) useremail = models.CharField( db_column='UserEmail', unique=True, max_length=100) userpassword = models.CharField(db_column='UserPassword', max_length=128) passwordsalt = models.CharField(db_column='PasswordSalt', max_length=128) class Meta: managed = False db_table = 'userinfo' class Postinfo(models.Model): postuid = models.BigAutoField(db_column='PostUID',primary_key=True) useruid = models.ForeignKey( 'Userinfo', db_column='UserUID', on_delete=models.CASCADE) content = models.TextField(db_column='Content') class Meta: managed = False db_table = 'postinfo' if i get userlist and user's last post models.Adviceinfo.objects.all().annotate(lastpost="??").order_by("-useruid") what values in "??" like this {userinfofields,"lastpost":{postinfofields}} can i this ? -
Django rollback doesn't work
Using Django1.4.22 and 'autocommit' default is True. Since I can't change the default value, how can I turn it off temporarily so I can use rollback. Background: I was writing a script for database data deletion, and I wanna test if it will work before I really delete it. So I use dry_run to test if it is deleted and then rollback. @transaction.commit_manually def run(self, dry_run): try: assert self.database in self.validate_values.keys() assert self.table in self.validate_values.values() except AssertionError as e: logger.error("%s or %s is not available. \n Error: %s" % (self.database, self.table, e.message)) return self.cursor.execute(self.SELECT_PATTERN % self.PGDict) current_value = self.cursor.fetchall() if len(current_value) > 1: logger.error("You can only update one item at a time.\n Current value: %s" % current_value) return elif len(current_value) == 0: logger.error("No data.") return elif len(current_value) == 1: if dry_run: logger.warning("Data below will be deleted.\n") logger.info("Current value: %s" % current_value) transaction.savepoint() try: print current_value self.cursor.execute(self.DELETE_PATTERN % self.PGDict) self.cursor.execute(self.SELECT_PATTERN % self.PGDict) current_value = self.cursor.fetchall() assert len(current_value) == 0 transaction.rollback() logger.info("Dry run successfully.") self.cursor.execute(self.SELECT_PATTERN % self.PGDict) current_value = self.cursor.fetchall() print current_value return current_value except AssertionError as e: logger.error("Dry run failed. \n Error: %s" % e.message) return else: logger.warning("Data deleting...\n") self.cursor.execute(self.DELETE_PATTERN % self.PGDict) self.cursor.execute(self.SELECT_PATTERN % self.PGDict) current_value = self.cursor.fetchall() try: assert len(current_value) … -
code visualization in django
I was looking at a python code visualization tool (http://www.pythontutor.com/visualize.html#mode=display) that nicely draws a model with its functions: I am interested in having something similar for django projects where models could be visualized exactly like this, instead of just one class all the models could be visualized with a nice graphic. However graphic does not mean class or any uml diagram. Any pointers how to approach this? Any existing libraries that already achieve this or if there are none, what could be important to look at to build one? -
How to ensure some custom ID has not been created already in the past?
I have a model with some charField called custom_id. I am generating this ID randomly, and check if already exists in database before assigning it. So all my custom_ids are unique. However if I delete some entry from the database. The custom_id will become available again. I want to prevent that. I want the custom_id not to be ever usable again. How is that possible ? Is there a clean way to achieve that ? -
Connecting django multiple choice field with textinputs
In django models, I used models.MultipleChoiceField but i want that those variables in the set of choices to be linked to a textinput which will be saved into the django admin. So the user selects the choice then keys in a textbox and saves for that choice is that possible to implement? -
FIX ImportError: cannot import name 'patterns'
I am writing documentaton for the API I have already built. I have already installed drfdocs and added it in INSTALLED_APPS then configured the urls yet I get the following logs. I think the version of rest_framework_docs is importing patterns which I believe its deprecated to the new versions of django. How do I fix this? I have django 1.11 and using python3. I get the following logs when I try to run ther server: File "/usr/local/lib/python3.5/dist-packages/rest_framework_docs/urls.py", line 1, in <module> from django.conf.urls import patterns, include, url ImportError: cannot import name 'patterns' Views.py from django.conf.urls import include, url from django.contrib import admin from rest_framework.urlpatterns import format_suffix_patterns # from organizations.backends import invitation_backend from rest_framework.authtoken.views import obtain_auth_token from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'api/token/', obtain_auth_token, name='api-token'), # url(r'^account/', include('accounts.urls', namespace='account')), url(r'^hr/', include('hr.urls', namespace='hr')), url(r'^acc/', include('Accounting.urls', namespace='Accounting')), url(r'^payroll/', include('payroll.urls', namespace='payroll')), url(r'^bill/', include('bill.urls', namespace='bill')), url(r'^docs/', include('rest_framework_docs.urls')), url(r'^proc/', include('procurement.urls', namespace='procurement')), # url(r'^accounts/', include('organizations.urls')), # url(r'^authority/', include('authority.urls')), url(r'^organization/', include('organizations.urls')), url(r'^admin/', admin.site.urls), # url(r'^invitations/', include(invitation_backend().get_urls())), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
How to connect Google Cloud Storage from Django?
I'm trying to connect Google Cloud Storage. But I can't. I saw this page. Configure Django and Google Cloud Storage? So I made AMI account as Storage objects admin. And I put the account as Storage objects admin of the bucket. Then set my setting file like this. settings.py DEFAULT_FILE_STORAGE = 'storages.backends.gs.GSBotoStorage' GS_ACCESS_KEY_ID = '***@***.iam.gserviceaccount.com' GS_SECRET_ACCESS_KEY = '***' GS_BUCKET_NAME = '***' STATICFILES_STORAGE = 'storages.backends.gs.GSBotoStorage' I run this code from jupyter notebook. test.py MYPROJECT = 'my/project/path' import os, sys sys.path.insert(0, MYPROJECT) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "local_settings.py") import django django.setup() default_storage.exists('storage_test') I got this error. GSResponseError: GSResponseError: 403 Access denied to 'gs://***/storage_test'. I thin my GS_SECRET_ACCESS_KEY is not correct. Because I got GS_SECRET_ACCESS_KEY from "private_key_id" in my JSON key file. Is it correct?? or is there some mistake? If you have any solution about this problem, please tell me. -
Exclude related fields in model._meta.get_fields()
I have a model currently defined like this: class Category(models.Model): ID = models.AutoField() name = models.CharField() desc = models.CharField() Another model Subcategory has a ForeignKey defined on Category. When I run: Category._meta.get_fields() I get: (<ManyToOneRel: siteapp.subcategory>, <django.db.models.fields.AutoField: ID>, <django.db.models.fields.CharField: name>, <django.db.models.fields.CharField: desc>) However, I don't want the ManyToOneRel fields; I just want the others. Currently, I am doing something like this: from django.db.models.fields.reverse_related import ManyToOneRel field_list = [] for field in modelClass._meta.get_fields(): if not isinstance(field, ManyToOneRel): field_list.append(field) However, is there a better way to do this, with or without using the model _meta API? -
Listview Pagination not working correctly django
I'm Django beginner so I'm stuck in class-based pagination and I have followed many posts about pagination but unfortunate couldn't solve this error. if i search "love" in search box so URL become like this http://127.0.0.1:8000/search/?q=love and results show with pagination function but when i click on next pagination button then query get remove and url become like this http://127.0.0.1:8000/search/?page=2 and error raise: Invalid page (2): That page contains no results anyone can tell me from where I'm wrong? thanks Views.py from django.views import generic from .models import Album, Song from django.db.models import Q class Search(generic.ListView): template_name = 'music/search.html' paginate_by = 5 def get_queryset(self, *args, **kwargs): queryset_list = Song.objects.all() query = self.request.GET.get('q') if query: queryset_list = queryset_list.filter( Q(song_title__icontains=query)| Q(file_type__icontains=query) ).distinct() if not query: queryset_list = Song.objects.none() return queryset_list return queryset_list search.html {% if object_list %} <h1>Search result..</h1> {% for i in object_list %} <p>{{i.song_title}}</p> {% endfor %} <!-- pagination--> {% if is_paginated %} <ul class="pagination"> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif … -
Is sqlparse required and if yes, how do you install it?
I have two different Django projects. One uses PostgreSQL and one uses MySQL. In the postgres version, this worked. migrations.RunSQL('''CREATE OR REPLACE view skill_ranked_by_person_view AS SELECT link.id , skill.id skill_id , person.id person_id , concat( skill_rank.rank, ' — ', replace( concat(first_name,' ', middle_name, ' ' , last_name) , ' ', ' '), ' (', skill_rank.name, ')' ) person -- , * FROM people_personskill link INNER JOIN people_skill skill ON link.skill_id = skill.id INNER JOIN people_skillrank skill_rank ON skill_rank.id = link.skill_rank_id INNER JOIN people_person person ON link.person_id = person.id ORDER BY skill.rank desc, skill_rank.rank DESC'''), In the MySQL version, this failed. migrations.RunSQL(''' create view or replace client_view as select IDAutoInteger as id , concat(IDText,' - ', NameText) `client` from clients where IDText is not null order by concat(IDText,' - ', NameText) ; '''), with "sqlparse is required if you don't split your SQL " django.core.exceptions.ImproperlyConfigured: sqlparse is required if you don't split your SQL statements manually. Neither project has sqlparse in the requirements.txt file. Is sqlparse required and if yes, how do you install it? -
AttributeError: 'Type' object has no attribute '_state' django
Am trying to build my first project in Django .This is my code for the blog category model. i have already registered it the the admin file but i dont know why it through this error. # blog categories class Category(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=100,unique=True) class Meta: ordering = ('name',) verbose_name ='category' verbose_name_plural ='categories' -
Data migration for microservices
I have monolithic django project. But now would like to migrate to micro services by splitting code base into different django projects, but following issues exist with database Project uses single database, so would like to migrate data to multiple DBs as per micro-services architecture Foreign keys extensively to link across models. Splitting into multiple DB poses a challenge. Would appreciate sharing any help or experience in this migration process. -
Are there any libry in python to draw UML?
I'm new to python and going to do a project on user requirement analyze using NLP and draw UML diagram according to that.NLP analysing is already done and cannot do UML part ?? -
Introduce spell checking in Django's template form
When I write a form in django's template form, In the opening bowser of the form, there's not any magic function but a plain blank text area. How could I introduce the spelling check function to it? -
I am trying to customise my Django forms using widget tweaks for an app. I keep getting an error
I installed pip3 install Django-widget-tweaks and add widget_tweaks in INSTALLED_APPS[] in settings.py. when I run the server, getting the error:-ImportError: No module named 'widget_tweaks' error image can you please help me. -
Getting a GET request parameter in Jinja2 Template in Django
I need to get an get request value from an URL inside the Template, not in the .py file. Framework : Django. Templating Used: Jinja2. How to take value from the URl ? -
How do i get the DjangoRestSerializer to take fields in order to use them to calculate a model field
so i'd like to have my Serializer take in some fields like sum1 and sum2 and calculate a model field such as Sum. -
Pdf in djjango-rest-framework
I am trying to make pdf in django `from xhtml2pdf import pisa from django.http import HttpResponse from django.template.loader import get_template from django.template import Context from rest_framework.views import APIView from .models import Brand class ABCView(APIView): def post(self, request,format=None): report = Brand.objects.all() template_path = 'profile_brand_report.html' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Report.pdf"' context = {'report': report} template = get_template(template_path) html = template.render(Context(context)) print (html) pisaStatus = pisa.CreatePDF(html, dest=response) return response` but i am getting an unexpected error i don't know what i am doing wrong , I am getting this error argument of type 'Context' is not iterable or is there any other way to do it .thanks for help in advance