Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error on Travis: RuntimeError: populate() isn't reentrant
I am maintaining a project, with Travis CI implemented, and from one day. All my builds start failing without me touching anything or any dependence update ... I guess that Travis changed something, I tried to investigate, but honestly I have no clue. If I run a previous build which perfectly worked, now it fails with this everytime I call python manage.py ##whatever## $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 35, in <module> execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/django/apps/registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant By the way, I obtain the exact same error with Python 3.6 and 3.5. $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 35, in <module> execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/django/apps/registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant And naturally, this issue is impossible to reproduce on my own machine ... It's running just fine locally. Any … -
Django 2.0 how to display different view (readonly and etc) base on user permission
Hi My goal is to show the same table but different user have different field as 'readonly' base on their user permission. I have created user account from User module where I have assigned permission to individual user so I can use template tag {{perms.app.readonly}} in html or PermissionRequiredMixin in my class base view (updateview). Here is html {% for my_divider in form %} <tr> <td class="col-form-label col-form-label-md">{{ my_divider.label }}</td> <td>{{ my_divider }}</td> </tr> {% endfor %} If I simply user template permission and do {{my_divider.readonly}}. The entry field disappeared entirely, which is not what I want. I added readonly attr to the form class as below class IssueInput(forms.ModelForm): class Meta: model = TrackHeader fields = '__all__' widgets = {'google_url': forms.TextInput(attrs={'class': 'FlexField', 'readonly':'readonly'})} This is exactly what I want where user can see the content of the field but cannot edit it. But I cannot figure out how to make it work with PermissionRequiredMixin that certain user with permission will be able to edit but others can only read. Do I have to create additional view to link with different froms.py? But again, urls.py dictates which view in views.py to use. so where does the user permission condition comes in? … -
Could not start gunicorn on DigitalOcean Ubuntu 16.04
I have setup a Django app on DigitalOcean and I can start the app on 8000 port and which works Ok after starting the app by runserver command. But I could not make the gunicorn start through systemd Service File. I have following code for gunicorn.service file and file location is /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=peter Group=www-data WorkingDirectory=/home/peter/tplive ExecStart=/home/peter/tplive/virtualenv/bin/gunicorn - access-logfile --workers 3 --bind unix:/home/peter/tplive/app/appcore.sock appcore.wsgi:application [Install] WantedBy=multi-user.target Project directory path: /home/peter/tplive tplive app appcore _init_.py settings.py urls.py wsgi.py store staticfiles manage.py site.log virtualenv Procfile requirements.txt I don't have any appcore.sock file inside the app folder. When I run sudo systemctl start gunicorn from tplive/app then it's showing message Failed to start gunicorn.service: Unit gunicorn.service not found. I have also tried to run the command from inside the /appcore directory but got same result. I am quite confused about the file path, the .sock file and overall how the gunicorn should work! My project is using Python 2.7, Django 1.11 and nginx server. Thank you! -
Django moves compiled static file to STATIC_ROOT
I am running Django 2.1 and Python 3.6 in two projects and I am using django-sass-processor to compile my scss files. I have a problem during development that after every change I have to run ./manage.py compilescss to get my css files in correct location. It is due to the fact that when I render a template that uses generated file this file is generated in STATIC_ROOT directory instead of next to *.scss file to which localhost:8000/static/main.css points. After running compilescss it does properly compile next to main.scss file. I have made a question to the library owner, but he states that this is django related problem so I am posting here. In case someone would like to read: https://github.com/jrief/django-sass-processor/issues/110 -
Can't get OneToOneField to work with forms
I'm trying to add more fields to Django's default User model. I'm using the OneToOneField method. I want to create a signup page that allows the user to fill out a username, password, email, and other fields that I will add into a separate Profile model. I've using some code snipets i've found, and tried to make it work. However, I keep geting a IntegrityError at /account/signup/ UNIQUE constraint failed: accounts_profile.user_id error. I think the problem is that right when when the User gets created, a Profile gets created as well. Then When A new Profile gets created using the User's primary key it gives an error because a Profile for that primary key already exists. Can someone show me the correct way to do this? Here's all the relevant code: models.py: from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): GENDER_CHOICES = ( ('MALE', 'Male'), ('FEMALE', 'Female') ) user = models.OneToOneField(User, on_delete=models.CASCADE) middle_name = models.CharField(max_length=30, blank=True, default='') prefix = models.CharField(max_length=6, blank=True, default='') suffix = models.CharField(max_length=10, blank=True, default='') def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_or_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.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import … -
Connecting django-mssql to mssql server (azure)
I am relatively new to python and very new to django. I am attempting to connect to a MSSQL server with django. I installed django-mssql (maybe it needs to be put somewhere in the directory of the project?). However, when using the following in my settings.py, I get the error: 'sqlserver_ado' isn't an available database backend. 'default':{ 'ENGINE': 'sql.server_ado', 'NAME': 'db_name', 'USER': 'usr', 'PASSWORD': 'pwd', 'HOST': 'host.cloudapp.azure.com', } I have searched extensively to attempt to solve this problem, but other solutions seem to be hidden or possibly out of date (here). I am using a Mac. Any help & or direction would be much appreciated! -
Trying to extend to base file in Django
So I am trying to extend many files (let's name them sidebar1.html, sidebar2.html AND content.html) to 1 main file (global.html) The problem is whenever I run it, it doesn't show the sidebar but it shows the contents of content.html. this is the global page (for side bar): <div style="color: white;"> {% block sidebar %} {% endblock %} </div> and this is the global page (for content): <div class="segment"> <div class="container" style="margin:25px 35px 10px 300px;"> {% block main %} {% endblock %} </div> </div> sample content: {% extends "global_base_ui.html" %} {% block main %} content {% endblock %} this is the side bar content: {% extends 'global_base_ui.html' %} {% block sidebar %} <div class="item"> <a class="title"> <i class="dropdown icon"></i> <b>Manager's Tools</b> </a> </div> {% endblock %} -
How to display radio button instead of checkbox on change list admin panel?
Overview: Hi, I'm trying to do the question. I already have a custom template overiding change_list.html in my templates/admin/app_name/model_name/ directory, so anyone I give it to can know how to use it properly. To do that I went to the repository here, copied change_list.html, and added the html I needed. Now I want to make it so the check boxes on this list are all radio buttons instead. I need to do this to help prevent problems with some custom actions I wrote. I only want one at a time to run. Any help is appreciated. What I already tried: On this SO post, I tried the formfield_overrides option, making my own ModelForm with a widget, a SOME_CHOICES option, and the radio_fields option on the django docs. But they only they work if I click into each object on the list, then they override the fields on the next page... Whereas I only want each checkbox to be a radio button on the change_list.html page (the landing page when you click an app). I also went through the change_list.html, and found the code I need to edit should be somewhere between this block: {% block result_list %} {% if action_form … -
data getting repeated when fetched from the database while trying to display in bootstrap modals in django
I am new to Django and was trying to display data after fetching from the database This is my template code: {% for obj in object_list %} <!-- Button trigger modal --> <div class="card w-75"> <div class="card-body"> <h3 class="card-title" data-toggle="modal" data-target="#exampleModalLong" style="color: green">{{obj.Name }}<br></h3> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModalLong">Show Policy</button> </div> </div> i got correct reponse till here and was getting different datas as in different content of the data but after this all the code is showing the first data (the same content) only . <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle"> <h1>{{ obj.Name }}</h1><br> </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h3>Department</h3><br> {{ obj.Department }}<br> <h3>Policy</h3> {{ obj.Policy }}<br> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endfor %} please help. -
Visual Studio code Django Python debugger points to an older virtualenv
I was having some issues with my .virtualenv folders (had 2 projects working in parallel, and one virtual environment was looking at the other), so I manually deleted them and re-did a pipenv/pip install of just 1 project. I verified that the new folders for the same project got created. However, when I try to debug the project using Visual Studio Code, it gives me this error: & : The term 'C:\Users\userId\.virtualenvs\project-1abcde2S\Scripts\python.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. Where the project-1abcde2S points to the folders I deleted. Is there anyway to ensure that new virtual environments get picked up in Visual Studio code? any other tips on debugging a Django project would be helpful! -
JS tracking with Django/Python
I am currently implementing Google's gtag.js on my e-commerce website. I now read that it is also possible to also track refunds. As I handle my refunds backend with webhooks, I wonder, how to send 'browser' javascript signals to Google Analytics as described here. Do you have an approach to that? -
How to scale Django web-app that relies heavily on dynamic and unique data? Is caching an option?
How can I cache all of the HTML pages that a user will see after they visit the site for the first time each day? I have a Django web-app and I'd like to design it to be as scalable as possible. The problem is the data is dynamic and unique on a per-user basis. I've seen online that one of the best ways to get Django to scale is to implement caching. I've also seen that caching can be a big problem in Django sites where the site relies on dynamic data. For the sake of example, let's day that I have a Django flashcard application. When a user visits the homepage it loads the most overdue flashcard and presents it to the screen. Without any caching, the next page would not be loaded until the user clicks "Show Answer" and selects whether the flashcard is "Good" or needs to be reviewed "Again" (Please see this video of Anki flashcards as an example if needed). With my site, let's say that the user has 100 upcoming flashcards for review. What can I do in Django to get these HTML pages to be delivered fast, in advance of them actually … -
How can I safely override the django.contrib.admin.utils quote() method?
It appears that the quote() and unquote() methods inside django.contrib.admin.utils do not effectively handle underscores in primary keys. Specifically, I have some string-type primary keys that look like cus_C2xVQnht and when I use the django admin interface to edit them via the small pencil icon, the popup window will display an error like Customer with ID "cusÂxVQnht" doesn't exist. Perhaps it was deleted? (it is converting the C2 to the codepoint 00C2, aka Â. This is true for other valid codepoints as well (00C7, 00C6, 001B, etc) If I manually go to the customers model and find the ID, I can pull it up and edit it just fine, but it seems the URL encoding doesn't work right when the primary key has an underscore in it. After quite a lot of digging I managed to find these two functions buried deep inside django.contrib.admin.utils: def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' and similarly problematic characters. Similar to urllib.parse.quote(), except that the quoting is slightly different so that it doesn't get automatically unquoted by the Web browser. """ if not isinstance(s, str): return s res = list(s) … -
Django Packages for a two-sided marketplace?
does anyone have advice about how I would create a 2-sided marketplace in Django? I have looked at the eCommerce options on Django packages and have read through the documentation of those eCommerce packages but it is not clear how I can use those packages to create a two-sided marketplace. Any advice would be greatly appreciated. Thanks. -
Retrieve input value from js script to django view
I have created an html input in a js script this way: var compte = document.createElement("input"); compte.setAttribute("name", "compte"); I need to retrieve that input value into a django view. Usually, I use the name attribute of the input: num=request.POST['compte'] In this case, it didn't work knowing the html input was created using javascript. So how do I get the value? -
How to log SQL for empty queries in Django?
For system performance and analysis, I'm trying to log all the queries generated in a Django app using some custom middleware. However, queries without any results throw an EmptyResultSet exception. Oddly, this bug is a feature, and the Django devs have refused to fix the ORM to allow printing the SQL for querysets when there are no results. Their rationale is that the query must be broken, but I've confirmed this is untrue. If I modify my database directly so that no records are returned, a perfectly printable query suddenly becomes an EmptyResultSet exception that can't be rendered. That said, is there any workaround? All I need is the SQL the ORM generates. I don't care about the results or executing the query. I'm not sure why Django is executing the query in order to generate the SQL. -
Django + Netmiko + Python ( multiple sessions issue)
I am writing to get your experienced guidance on a peculiar issue I face now. The details are as follows Setup: Tool developed with Netmiko library(python language) , and Django Web framework 2.0.6. Tested with inbuilt Development server of django 3.6.5 and also with IIS in Windows server 2012 Objective: Enables netadmin team ( more than one access/session at same time) to access the tool and execute some show commands and configure switch interfaces and port. Program flow: The flow of the program as follows 1) User access the Web page 127.0.0.1:8000 and then provide the Switch IP address with credential 2) Netmiko connectionhandler now does auto detect feature to check whether it is a cisco or hp switch 3)Now netmiko execute few show commands like show interface and gather the details on dictionary type variable(in this case I still use the netmiko connection handler established in step 2, to avoid delay in re login) 4) Dictionary type variable is now displayed in html page in table format 5) Now user is allowed to configure the switch, with the task like vlan changes, bouncing the interfaces etc. ( in this case I still use the netmiko connection handler established in … -
Django Search And View more
i have search results in form of table i want to add Detail page button which can send the id of the result to another function in view.py so i can query it from database {% if sr %} {% for k,j in sr %} <tbody> <tr> <td>{{ k.id }}</td> <td>{{ k.chromosome }}</td> <td>{{ k.gene_id }} </td> <td><a href="{{ j }}"> view</a></td> </tr> {% endfor %} {% endif %} i want to send this k.id to another function def detailed(request): return render(request,"search/Detailed.html") so i can again perform a query from database by this id -
Default value format on Django DateField
I'm trying to specify a default date in a Django model like: from datetime import date class A(models.Model): date = models.DateField(default=date.today()) Okey this works, and I can see the default date in a modelform. But, when I change the form input_format to '%d-%m-%Y', the default date never appears in the field. I also try: from datetime import date class A(models.Model): date = models.DateField(default=date.today().strftime('%d-%m-%Y')) But it doesn't work. Can anyone help me? -
(windows server 2016) (python/Django) Couldn't import Django
The full error message: Traceback (most recent call last): File "manage.py", line 9, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django.core'; 'django' is not a package The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> ) from exc 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? I have tried adding django directly to the PYTHONPATH, no dice I have created a virtual environment and installed django in it, still nothing According to pip freeze I got Django 2.1.2 installed I'm pretty sure I'm using python 3 Apparently I can import django just fine (by just typing "import django" in an empty test.py file), but when I try to import django.core it gives me the following error: Traceback (most recent call last): File "test.py", line 7, in import django.core ModuleNotFoundError: No module named 'django.core'; 'django' is not a package (stackoverflow won't let me format it as code for some reason) -
Delay between serialization and string dump and Django Rest Framework API response
I'm using Django 2.1 and django rest framework to implement a REST API on my project. While trying to solve some serialization slowness in my project I realized that executing json.dumps(ChecklistSerializer(intelligence.models.Checklist.objects.get(id=4), many=False).data) on the terminal takes less than 2 seconds to finish whereas running the equivalent code on the view class ChecklistDetail(APIView): permission_classes = (permissions.IsAuthenticated, StaffPermission) def get(self, request, pk, format=None): # pylint: disable=E1101 checklist = Checklist.objects.get(pk=pk) serializer = ChecklistSerializer(checklist, many=False) return Response(serializer.data) is taking more than 60 seconds. Therefore my questions are: Does this time difference necessarily means that the slowness problem is not due to the serializers themselves? How can I profile all the timings in my API (including permisison check and related stuff)? Related Models: class ChecklistPillar(BaseModel): """A model to represent a checklist pillar. Some of the checklists characteristics are related to checklist pillars. Attributes: name (str): The name of the pillar. name_pt (str): The name of the pillar in portuguese. symbol (str): The symbol of the pillar. """ name = models.CharField(max_length=100, null=False, unique=True) name_pt = models.CharField( max_length=100, null=True, unique=True, blank=True) symbol = models.CharField( max_length=50, null=True, unique=True, blank=True) def __str__(self): if self.symbol is not None: return str(self.symbol) else: return str(self.name) def __repr__(self): return f'NoteType({self})' class ChecklistCharacteristic(BaseModel): """A … -
Why is a Django migration using the same random default on every row?
Note: I understand and am well aware of the difference between passing a function as a parameter and invoking a function and passing the result as a parameter. I believe I am passing the function correctly. Specs Django 1.11 PostgreSQL 10.4 Scenario: I have dozens of models in my application, with many existing records. I need to add a random seed to each of these models that will get created and set when a new model instance is created. I also want to generate the random seed for the existing instances. My understanding of how Django model defaults and Migrations work is that when a new field is added to a model, if that field has a default value set, Djano will update all existing instances with the new field and corresponding default. However, despite the fact that I'm definitely passing a function as the default, and the function produces a random number, Django is using the same random number when updating existing rows (e.g. it seems that Djano is only calling the function once, then using the return value for all entries). Example A shortened version of my code: def get_random(): return str(random.random()) class Response(models.Model): # various properties random … -
i want to add a time.gmtime(number of seconds) to a TimeField column in django model
I have changed the number of second into an HH:MM:SS format now i want to add it to a Time Field column type in django is their a way to do it? -
Django - Populate Field with data anothe field
I am creating a Custom User Class inside the APP Core. Within APP Management I have a Person Class. My Core.User Class has connection to the Management.Person Class. Within the two Classes I have an email field this email will serve as the login for the system. What I need to do is: When registering a User, the first thing to do is select the Person. and I need the User email field to receive the same email that is in the Person class How to do this? -
How to uniquely identify a paypal buyer in a django-based platform?
I am looking for a solution to keep track of the customers that pay a monthly subscription on my website. I use the IPN notification system from paypal and I can succesfully handle the data from the notification (payer's email, name, ID, etc). From another question I know that the payer_id from the system is not really an unique identifier for the buyer. I thought about making a log-in feature and somehow to link the account with all the client's payer_id's. Any suggestion please?