Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
run django web application with apache and mod_wsgi with python3 virtuaenvironment on ubuntu
This is the first time I am deploying django app on apache with mod_wsgi,using python3 virtual environment. directory like below (DJango_RestFramework) User@User-virtual-machine:~/Project/Sample$ dir db.sqlite3 manage.py Sample static Added STATIC_ROOT = os.path.join(BASE_DIR, "/home/User/Project/Sample/static/") at the bottom of settings.py file then applied ./manage.py collectstatic right after then changed /etc/apache2/sites-available/000-default.conf file like below <VirtualHost :*80> Alias /static /home/User/Project/Sample/static <Directory /home/User/Project/Sample/static> Require all granted </Directory> <Directory /home/User/Project/Sample/Sample> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess Sample python-path=/home/User/Project/:/home/User/Project/DJango_RestFramework/lib/python3.5/site-packages WSGIProcessGroup Sample WSGIScriptAlias / /home/User/Project/Sample/Sample/wsgi.py </VirtualHost> finally applied these commands 1.chmod 664 /home/User/Project/Sample/db.sqlite3, 2.sudo chown :www-data /home/User/Project/Sample/db.sqlite3, 3.sudo chown :www-data /home/User/Project/Sample, 4.sudo service apache2 restart got Internal Server Error If I checked at error.log it' was showing that [Tue Dec 12 15:02:32.095065 2017] [wsgi:error] [pid 1331:tid 140188564576000] [remote 127.0.0.1:5937] ImportError: No module named 'django'. don't know where I mistaken please help me. thanks in advance! -
ppt open in Djanago
Django the powerpoint generated using python-pptx library has error message I am using this way But I am getting an Error " name 'Presentation' is not defined" what should I do? -
Bypass Django to serve static files with Nginx
I'm trying to serve static files with Nginx, but it seems like Django takes control of the path and keeps giving a 404 because it's not a valid URL within the Django app. Here's the Nginx server setup: server { listen 443; server_name localhost; client_max_body_size 500M; location /static/ { autoindex on; root /app/interfaces/web/static; } location / { uwsgi_pass django; include /app/interfaces/web/django/uwsgi_params; } } I have tried all following combinations: /static/ and /static With and without autoindex on root and alias When I try to access a file in the /static/ directory, I get the following 404 error from Django: Page not found (404) Request Method: GET Request URL: https://172.16.6.158/static/test.css Using the URLconf defined in django.urls, Django tried these URL patterns, in this order: ^ ^$ [name='index'] ^history/ ^config/ ^admin/ The current path, static/test.css, didn't match any of these. I also tried to set STATIC_URL in Django settings, but I don't think that should be neccessary since I'm trying to bypass Django. And I didn't make any difference anyway. Does anyone know what I'm doing wrong? Do I need to change configuration somewhere else. -
Is this an okay way of doing a Django Rest Framework Serializer Update Method?
I notice the DRF docs say you should pop each field off the validated_data dict in the update method as such: def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) instance.save() return instance However lets say you had a models with lots of fields. Would it not be easier to do something like the below? Or am I missing something? def update(self, instance, validated_data): for attr, value in instance.__dict__.iteritems(): new_value = validated_data.get(attr, value) setattr(instance, attr, new_value) instance.save() return instance Still learning Python so I'm not sure if I'm doing something unsafe or stupid here. -- Dean -
InterfaceError: connection already closed
I'm running a celery(4.1.0) task with django(1.11.6) using psycopg2(2.7.3), getting these errors after 5-6 hour of deploying the app on production.one of the related issue on django issue tickets. Tried various solution of reconnecting the connection using try and except, handling InterfaceError. Any help will be appreciated. Checked and Applied some of the solutions, but nothing seems to be working, Celery Worker Database Connection Pooling Traceback InterfaceError: connection already closed File "billiard/pool.py", line 358, in workloop result = (True, prepare_result(fun(*args, **kwargs))) File "celery/app/trace.py", line 537, in _fast_trace_task uuid, args, kwargs, request, File "celery/app/trace.py", line 482, in trace_task I, _, _, _ = on_error(task_request, exc, uuid) File "celery/app/trace.py", line 330, in on_error task, request, eager=eager, call_errbacks=call_errbacks, File "celery/app/trace.py", line 164, in handle_error_state call_errbacks=call_errbacks) File "celery/app/trace.py", line 212, in handle_failure task.on_failure(exc, req.id, req.args, req.kwargs, einfo) File "telemetry/tasks.py", line 29, in on_failure save_failed_task(self, exc, task_id, args, kwargs, einfo) File "telemetry/celery_failure.py", line 46, in save_failed_task existing_task_first = existing_task.first() File "django/db/models/query.py", line 564, in first objects = list((self if self.ordered else self.order_by('pk'))[:1]) File "django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "django/db/models/sql/compiler.py", line 882, in execute_sql cursor = … -
Which Web Framework should I Learn first Django or Node.js as a begginer? [on hold]
I have 6 months of front-end experience now i want to learn back-end web development so please help me which web framework should I choose Django or Node.js? -
`python manage.py runserver` will termination in the remote server.
Whether the runserver have time limit? In my remote server virtual environment, I use runserver command to start my development server(by my Mac, my Mac use ssh connected to the remote server) : (venv)$ python3 manage.py runserver 183.97.12.26:8001 and after scores of minutes, it will broken up by itself, if I do not use my Mac(my Mac maybe dormancy). So, how can I make it do not break off. Who can tell me the issue is cause by the command or by the virtualenv? -
How can i use limit offset pagination for viewsets
Views.py class CountryViewSet(viewsets.ViewSet): serializer_class = CountrySerializer pagination_class = LimitOffsetPagination def list(self,request): try: country_data = Country.objects.all() country_serializer = CountrySerializer(country_data,many=True) return Response( data = country_serializer.data, content_type='application/json', ) except Exception as ex: return Response( data={'error': str(ex)}, content_type='application/json', status=status.HTTP_400_BAD_REQUEST ) Settings.py i have added 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', in my urls.py router = routers.DefaultRouter(trailing_slash=False) router.register(r'country', CountryViewSet, base_name='country') urlpatterns = [ url(r'^', include(router.urls)), ] When i try with this url http://192.168.2.66:8001/v1/voucher/country its returning all data. But when i am trying with this url http://192.168.2.66:8001/v1/voucher/country/?limit=2&offset=2 but it is returning 404 error. I am new to django.kindly help me :) -
Nginx. Point two domains to the same location
I have pretty basic nginx configuration which routes all requests to somebot.io to gunicorn server on port 8001. I own another domain some.bot. How to configure nginx to route requests to both domains to the same gunicorn server? I tried to change server_name to server_name somebot.io some.bot; but this didn't help and some.bot responded 400. Should I have separate server block for the second domain? server { listen 443 ssl; server_name somebot.io; ssl_certificate ... ssl_certificate_key ... ... if ($http_host != $server_name) { return 400; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://localhost:8001; } } server { listen 80; server_name somebot.io; return 301 https://$http_host$request_uri; } -
Getting python malloc segmentation fault when start running django runserver after update macOS to High Sierra
I'm struggling to run Django app server in my local. And it does not work since I've updated my macOS to High Sierra from Sierra yesterday morning. I'm using Django 1.10.5 Python 2.7.14 When I run the ./manage.py runserver, it shows the error message like below. Performing system checks... System check identified no issues (0 silenced). python(4381,0x70000269c000) malloc: *** error for object -x7fe76b38a860: Non-aligned pointer being freed (2) *** set a breakpoint in malloc_error_break to debug [1] 4359 abort ./manage.py runserver And I found one issue from here Dynamic library problems with Python and libstdc++ the error message looks quite similar, but couldn't find any similarity so far. -
Precedence in saving in Django Admin with TabularInline
I have 2 models Company and Product. class Company(SEO, MetaData): is_active = models.BooleanField(default=False) class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) is_active = models.BooleanField(default=False) With the following rules: 1) If the Company is_active is False, a Product can't be come active 2) If a Company that active was True becomes False all the Product is_active become False Rule 1, in Product Model: def clean(self): super().clean() if self.is_active: if not self.company.is_active: raise ValidationError( {'is_active': 'The Company need to be checked an validated first'}) return self.is_active Rule 2, in Company Model: (with help from the stackoverflow): def save(self, *args, **kwargs): # if the active state was changed and is False if self.__original_is_active != self.is_active and self.is_active is False: # update does direct changes in database doesn't call save or signals self.products.update(is_active=False) super().save(*args, **kwargs) The issue: I added the Product Model in Company Admin as TabularInline. For Rule 2, when I toggle is_active for Company from True To False and try to save, the Rule1 (ValidationError) appear, and can't be saved. This is strange for me because the update to the product is_active is done before the Company Form is saved, so it should have the previous value. I think that is_active for Product … -
Django Many To Many field with filter
I am trying to add a filter to my ManyToMany field. I have a model User and a model Notification. Notification is connected with User by a ManyToMany field. I want to be able to send a Notification to all users that are for example located in Bulgaria or filter them based on another property in the user model which is not predefined(i.e. The person who creates the Notification does not know pre-creation the filter field). I tried using raw_id_fields for User in Notification admin page. I can then chose and filter Users I want to add based on filters in the Model but I can only choose one user at a time and if I have to add, for example 10k users this can be quite inconvenient. I want to be able to either use raw_id_field and select multiple instances at once, or add some field filtration to filter_horizontal or I don't know. -
How should i implement custom counter of instances with some type?
Here's my model: class MyModel(BaseModel): no = models.PositiveIntegerField() # Human-friendly no -> counter that starts from 1 for every type type = models.ForeignKey(MyModelType) I set the value for the no field in model's pre_save signal: @receiver(pre_save, sender=MyModel) def mymodel_pre_save(sender, instance, *args, **kwargs): if not instance._state.adding: return obj_count = MyModel.objects.filter(type=instance.type).count() instance.no = obj_count + 1 The bug with this code is that it produces different objects having same no number. Probably it happens when multiple users create objects at the same time. What's the best way to fix it? Would moving assignment to .save() method of the model suffice in high-load environment? -
Copy InMemory file to remote server
Is there a way to copy a file in request.FILES to a remote location such as 100.100.1.100/home/dbadmin/EncFiles in Django? I have consulted from this and this questions but I don't need to log on to the server to copy file. I have a simple file in my memory that I need to send to another server. How do I do that? -
how to grab the hour from a timefield - django
I have a model and form with a TimeField and I want to make a change for the hour once the timefield is extracted from the form that was submitted and stored. I want to update the hour in the time. can anyone help me with this... here is the view start_time = cd['start_time'] update_time = start_time update_time.hour = update_hour update_time.save() So the start_time is a timefield that submitted. I want to grab the hour from that start time to change it. how can i do that... -
How to stop Django to create lot of unnecessary tables
I have two databases defined in my setting.py file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'monitoring', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', }, 'source' :{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'source_db', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '*****', 'PORT': '****', } } I need to access some tables in source_db which django is not allowing to do so unless I migrate the db. So, once we run command python manage.py migrate --database=source , Django is creating some tables in server db. Since we are not allowed to create tables in server db, is there any way to stop django doing so? This is the list of tables which we don't want to create. +--------------------------------+ | Tables_in_source_db | +--------------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | dashboard_monitoring_features | | dashboard_monitoring_modelinfo | | dashboard_monitoring_product | | django_admin_log | | django_content_type | | django_migrations | | django_session | +--------------------------------+ -
Django add brackets to django models field
I was trying to add brackets to my django fields how to do it Only with brackets there is syntax error models.py class Customer(models.Model): name = models.CharField(max_length=1000) Region =models.CharField(max_length=1000,choices=Region, default='-') Status =models.CharField(max_length=1000,choices=Option, null=True) APP_SERVER\(Prod\)=models.CharField(max_length=1000,blank=True, null=True) -
Which row is deleted in DISTINCT ON in postgresql
When I use DISTINCT ON in postgresql (distinct in django) which rows are deleted in the group of rows with same fields? -
Easy_install virtualenv/Pip install virtualenv - not working
I am working on the company's server and pip install or easy_install is not working. I am not able to install virtualenv. This is the result for easy_install: PS C:\> easy_install virtualenv Searching for virtualenv Reading https://pypi.python.org/simple/virtualenv/ Download error on https://pypi.python.org/simple/virtualenv/: [Errno 11001] getaddrinfo failed -- Some packages may not be found! Couldn't find index page for 'virtualenv' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: [Errno 11001] getaddrinfo failed -- Some packages may not be found! No local packages or working download links found for virtualenv error: Could not find suitable distribution for Requirement.parse('virtualenv') PS C:\> This is what I get when I run the pip install command: PS C:\> pip install virtualenv Collecting virtualenv Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pi ._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03600ED0>: Failed to establish a new onnection: [Errno 11001] getaddrinfo failed',)': /simple/virtualenv/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pi ._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03600E10>: Failed to establish a new onnection: [Errno 11001] getaddrinfo failed',)': /simple/virtualenv/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pi ._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x03600FF0>: Failed to establish a new onnection: [Errno 11001] getaddrinfo failed',)': … -
How do I define multiple objects of the same type (django-places placesfield object) in a model in django?
Here's what I mean. I have this model: from places.fields import PlacesField class Lol(models.Model): source = PlacesField() destination = PlacesField() The issue is that whenever I select the source location, the same is selected for the destination and vice versa. What I have tried: I created two extra models to which Lol will be the foreign key, but I don't want to do that. Is there any other solution to this issue? -
Custom javascript to elements of django-summernote widget dont work?
I have some problems with django-summernote application. In toolbar of widget I have button (.btn-fullscreen). I want to change some blocks when user click this button, so I add javascript but unfortunatly it dont work. $(".note-toolbar").on("click", ".btn-fullscreen", function () { // Some code console.log('CLICK'); <!-- Dont work }); $(".btn-fullscreen").click(function(){ // Some code console.log('CLICK'); <!-- Dont work } I notice that this problem happens only when I'm trying to contact with elements of the widget. There is no problems with elements outside of widget. What can be the reason of this strange behavior? This is how I load static files: CSS: <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/codemirror.min.css"> {# Codemirror CSS #} <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/theme/monokai.css"> {# Monokai CSS #} <link rel="stylesheet" type="text/css" href="{% static "summernote/summernote.css" %}"> {# Summernote CSS #} <link rel="stylesheet" type="text/css" href="{% static "summernote/django_summernote.css" %}"> {# Django-Summernote CSS #} JS: <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/codemirror.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.29.0/mode/xml/xml.js"></script> <script src="{% static 'summernote/jquery.ui.widget.js'%}"></script> <script src="{% static 'summernote/jquery.iframe-transport.js'%}"></script> <script src="{% static 'summernote/jquery.fileupload.js'%}"></script> <script src="{% static 'summernote/summernote.min.js'%}"></script> <script src="{% static 'summernote/ResizeSensor.js'%}"></script> <script type="text/javascript"> $(".note-toolbar").on("click", ".btn-fullscreen", function () { // Some code }); $(".btn-fullscreen").click(function(){ // Some code } </script> -
I'm unableto install django
enter image description here I tried install the django by using regular commands.but it is not installing -
Django python manage.py runserver giving exception Datafile not found, datafile generation failed
After upgrading one of my packages (django-registration), I received this error while trying to run python manage.py runserver The output was as I have shown below. I thought that python3.5/site-packages/confusable_homoglyphs/categories.py might be missing and I re installed the package confusable_homoglyphs , but to no avail .It threw the same error Also after that, a file name =3.0.0.txt was created inside my project folder which had this written below Requirement already satisfied: confusable_homoglyphs in ./myvenv/lib/python3.5/site-packages I tried to remove the package and add that package (even inside n outside my virtual env). But it threw the same error as below. (myvenv) shubhendu@shubhendu-HP-Pavilion-g6-Notebook-PC:/home/foodballbear$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f320538d400> Traceback (most recent call last): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 141, in <module> categories_data = load('categories.json') File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/utils.py", line 33, in load with open('{}/{}'.format(os.getcwd(), filename), 'r') as file: FileNotFoundError: [Errno 2] No such file or directory: '/home/foodballbear/categories.json' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 144, in <module> if generate(): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 111, in generate file = get(url) File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/utils.py", line 24, in get return urlopen(url).read().decode('utf-8').split('\n') File "/usr/lib/python3.5/http/client.py", line 461, in read s = self._safe_read(self.length) … -
What is require knowledge and practice to develop MVC applications
I am trying to develop MVC application with php but I am not able to understand how to start with database development. Do I need to develop database first approach or other? -
Blockchain API Error: Wallet Password incorrect [And It's correct]
I want to work with blockchain api in my django web app. After installing the blockchain-service module and starting the server, I input the right wallet password and I'm getting error: main wallet password incorrect The endpoint http://localhost:3000/merchant/d536-46464-9575756-38474646/enableHD?password=pooo Versions: Nodejs: 8.9.1 npm: 5.5.1 wallet-service: 0.26.0 Could this be a bug with blockchain module or what am I missing?