Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Json response from mongoengine query using Django rest framework?
I am using Django rest framework along with mongoengine using package django-rest-framework-mongoengine. I am trying to get all values from a model and I want to convert query set into Json. I don't want to use Serializers. Query is: response = User.objects.all() return Response(status=status.HTTP_200_OK, data=response) In sql databases we can write User.objects.values() and this will give you json response. But its not working here. Please help me out in this. -
How django delete works
I would like to know if anyone knows an article about how Django delete works behind the scenes, like how the delete is done in my database, if after many objects deleted I will have to use vacuum. Thanks -
Data accessing & display in Django
I'm having trouble accessing database data in another template different than django administration. In the administration page I get results: But when I try to display them in another template: (No results available) Here's how my urls.py admin page and template urls looks like: urlpatterns = [ path('admin/', admin.site.urls), path('lista/', views.entitats, name = 'lista_entitats') ] Here's how my admin.py call to entity list and register looks like: class EntitatAdmin(admin.ModelAdmin): list_display = ('codi', 'nom', 'adreça', 'cp', 'correu', 'inspector') inlines = [DiaLliureDisposicioInline, VisitesDirectorCentreInline, ExitEscolarInline, ObresCentreInline, OfertaEstudisInline, NEE_alumnatInline, FormacioInline, ProjectesInline, ProfessorsInline, DespesesFuncionamentInline] search_fields=('nom',) list_per_page=5 admin.site.register(Entitat, EntitatAdmin) In my views.py this is how I ask for the template (and where I feel I'm not getting db information well): from entitats.models import Entitat def entitats(request): lista_entitats = Entitat.objects.all() context = {'llista_entitats': lista_entitats} return render(request, 'entitats.html', context) And finally my template, where I try to display the list of entities: {% if context.llista_entitats %} <ul> {% for question in objects_list %} <li><a href="/admin/entitats/entitat/{{ entitat.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>Ninguna entidad disponible.</p> {% endif %} Sorry if it's loong, I'll delete if there's something not necessary, and THANKYOU in advance. -
django makemessage syntax error
When i write django-admin makemessages in cmd , it shows these errors : CommandError: errors happened while running msguniq C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite \locale\django.pot:25:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:25: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:25: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:25: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:25: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:42:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:42: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:42: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:55:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:55: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:55: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:60:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:60: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:60: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:60: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:60: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:65:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:65: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:65: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\django.pot:70:3: syntax error msguniq: too many errors, aborting the files in the locale folder are django.po and django.mo , so what is django.pot ??? which it has syntax error in it ? -
how to generate variables in django module based upon admin input
class country(models.Model): Country_Name = models.CharField(max_length=80) def __str__(self): return self.Country_Name class state(models.Model): state_con = models.ForeignKey(country, on_delete=models.CASCADE) number_of_states = models.IntegerField() state_name = models.CharField(max_length=80) def __str__(self): return self.state_names How can I store all the state names in a single variable state_name? or How can I auto-generate x number of state_name fields based upon admin input in number_of_states? For example, if the number of states is 5, can I auto-generate 5 charfields. -
how to clone full inheritance tree model
Normally, if want to clone a model object. It happens as follow: class ModelA(): field obj = ModelA.objects.get(id=1) obj.id = None obj.save() Here, it will save the clone the object with new id. But how to clone the full inheritance tree. class ModelA(): field class ModelB(ModelA): field obj = ModelA.objects.get(id=1) Now if we do the same, only ModelA will be clone in db, but how to clone Model B also which has same ptr id as obj. I tried using, obj.ModelB.ptr_id = None obj.ModelB.save() None works. -
Django translation: can't find msguniq
I would like to do the translation inside Django application. I was following the this tutorial but I run into problems. After I run the code python manage.py makemessages -l 'de' I get the error CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. The weird thing is, that I have the gettext already installed Warning: gettext 0.19.8.1 is already installed and up-to-date To reinstall 0.19.8.1, run `brew reinstall gettext` I have the settings set as: # Translations # Provide a lists of languages which your site supports. LANGUAGES = ( ('en', _('English')), ('de', _('German')), ) # Set the default language for your site. LANGUAGE_CODE = 'en' # Tell Django where the project's translation files should be. LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) print(LOCALE_PATHS) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Do anyone know what could go wrong? -
Why pycharm community cant run my django app?
So I've did: $mkdir MyProject $cd MyProject $django-admin startpoject myproject $cd myproject $django-admin startapp myproject Then I open pycharm, choosing open project using folder with file manage.py Then I've created new python-configuration named myproject with scriptfile manage.py and parameter runserver, clicked on save and trying to run it but I got weird error: Error running 'myproject': Cannot run program "/tmp/bitcoinprice.py/venv/bin/python" (in directory "/home/blacknite/Fworld/Python/MyProject/myproject"): error=2, No such file or directory I dont understand, why pycharm tries to run some venv that is in some not related project of also not related with django parrent directory? -
heroku Error: Cannot find module '/app/index.js'
I am hosting a university project on heroku and i need to host a django app which also needs an npm library but i searched alot on how to do this and eventualy i thought i got the hand of it but now i am getting this error: 2018-06-14T10:19:22.798022+00:00 app[web.1]: throw err; 2018-06-14T10:19:22.798023+00:00 app[web.1]: ^ 2018-06-14T10:19:22.798024+00:00 app[web.1]: 2018-06-14T10:19:22.798026+00:00 app[web.1]: Error: Cannot find module '/app/server.js' 2018-06-14T10:19:22.798028+00:00 app[web.1]: at Function.Module._resolveFilename (module.js:547:15) 2018-06-14T10:19:22.798029+00:00 app[web.1]: at Function.Module._load (module.js:474:25) 2018-06-14T10:19:22.798030+00:00 app[web.1]: at Function.Module.runMain (module.js:693:10) 2018-06-14T10:19:22.798031+00:00 app[web.1]: at startup (bootstrap_node.js:191:16) 2018-06-14T10:19:22.798033+00:00 app[web.1]: at bootstrap_node.js:612:3 this is my package.json: { "name": "dpl-webtech", "version": "1.0.0", "description": "DBL - Webtech Group D24", "main": "index.js", "scripts": { "start": "nf start" }, "repository": { "type": "git", "url": "git+https://github.com/spiderangel123/DPL-WebTech.git" }, "author": "Ahmad Alsarakbi", "license": "ISC", "bugs": { "url": "https://github.com/spiderangel123/DPL-WebTech/issues" }, "homepage": "https://github.com/spiderangel123/DPL-WebTech#readme", "engines": { "node": "8.11.2", "npm": "6.1.0" }, "dependencies": { "npm": "^6.1.0", "phantomjs-prebuilt": "^2.1.16" } } and here is my procfile: web: gunicorn DBL.wsgi web: node ./index.js -
Celery discovers all previous tasks despite disabling app.autodiscover_tasks() and CELERY_IMPORTS
Celery discovers all previous tasks despite disabling app.autodiscover_tasks() and CELERY_IMPORTS. I am using: django==2.0 celery==4.1.0 amqp==2.2.2 I had been importing a module from CELERY_IMPORTS for a long time and it was working fine, when I removed it from CELERY_IMPORTS it keeps finding it which is a very weird behaviour. I understand that that may be cached somewhere since it had been working for months but isn't there some command to refresh the cache. If there is which cache should I refresh combu, celery, rabbitmq? This question was asked in previous question but no solution was found so this seems like an issue in the core functionality in celery and a solution needs to be found. -
How django fix the compatibility?
Recently I was dived in Django,and I wondered that how the developer make a compatibility of the different Django version ? Not talking about the detail of the change ,but just the name of API of and the path of the API. Here is a example : Before Django 1.10 in settings.py Django provides django.utils.deprecation.MiddlewareMixin to ease creating middleware classes that are compatible with both MIDDLEWARE and the old MIDDLEWARE_CLASSES. All middleware classes included with Django are compatible with both settings. What I try is : import django if django.get_version() > '1.11.0': MIDDLEWARE= ('...','....') else: MIDDLEWARE_CLASSES = ('...','....') -
Dynamically Add Fields to Django Models & Migrate & Return on Template
I want superuser or agent to be able to add fields to user profile on the go during collection of data from users. For example, the agent will click add new field button via frontend, and the link will automatically create the field, add to the 'Profile' model and makemigrations via django South. Now I tried doing this via inlineformset factory adding additional fields. The problem is the fields are not being created in the database so saving data inputted in the fields are not working too. I have 'Profile'model for user details and 'Userform' for details related to User model. So now below is my forms and views class BaseProfileEditInlineFormSet(BaseInlineFormSet): def add_fields(self, form, index): super().add_fields(form, index) form.fields['more_field'] = forms.CharField() form.fields['more_field'] = forms.CharField() views @login_required def edit_user_profile(request, pk): userpro = CustomUser.objects.get(pk=pk) user_form = UserForm(instance=userpro) ProfileInlineFormset = inlineformset_factory(CustomUser, Profile, exclude=['user','pub_date','modified_date','basic_verification','phone_confirmed'],formset=BaseProfileEditInlineFormSet, max_num=1, can_delete=False) formset = ProfileInlineFormset(instance=userpro) if request.user.is_authenticated and request.user.id == userpro.id: if request.method == "POST": user_form = UserForm(request.POST, request.FILES, instance=userpro) formset = ProfileInlineFormset(request.POST, request.FILES, instance=userpro) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=userpro) if formset.is_valid(): created_user.save() formset.save() return HttpResponse('saved data') return render(request, 'accounts/account_update.html', {'pk':pk, 'user_form': user_form, 'formset':formset,}) else: raise PermissionDenied What am I missing? Also do you think this … -
Django, Python: Best way to parse a CSV and convert to Django model instances
I have a page where a user uploads a CSV file. That bit works. I can read the CSV and turn it into lists. It takes a fair bit of time for something I thought should be faster (about 7 seconds to parse through and convert it to lists, for a 17mb CSV file). I'm wondering now though, what would be the best approach to doing this? The code I have so far is very convoluted (written a long time ago by a CS graduate colleague that has since left) and I think I want to rewrite it as it's too slow. I haven't worked with CSVs before. Right now this is what I have: import codecs import csv import sys def read_csv_file(self, file_path): is_file = False while not is_file: if os.path.exists(file_path): is_file = True result_data = [] csv.field_size_limit(sys.maxsize) csv_reader = csv.reader(codecs.open(file_path, 'rU', 'utf-8'), delimiter=',') for row in csv_reader: result_data.append(row) return result_data Is turning a CSV into lists (that I can then perhaps zip?) the best way to go about it? Ultimately, the goal is to create DB objects (in a loop perhaps?) that would be something like looping through each list, using an index to create objects, appending those … -
Lambda-specific package doesn't work on AWS lambda
I downloaded this lambda package from github so I can run my lambda function on AWS. I didn't use all the folders, I only took the ones I needed. So my .zip folder contains: lambda_function.py, Pillow, numpy, OpenCV and psycopg2. I uploaded that .zip file to my lambda function. However upon testing it returns this error: Unable to import module 'lambda_function': No module named 'PIL' Not sure why I'm getting this error as PIL is imported in my code (the code is provided by AWS): lambda_function.py from __future__ import print_function import boto3 import os import sys import uuid from PIL import Image import PIL.Image s3_client = boto3.client('s3') def resize_image(image_path, resized_path): with Image.open(image_path) as image: image.thumbnail(tuple(x / 2 for x in image.size)) image.save(resized_path) def handler(event, context): for record in event['Records']: bucket = record['s3']['bucket']['name'] key = record['s3']['object']['key'] download_path = '/tmp/{}{}'.format(uuid.uuid4(), key) upload_path = '/tmp/resized-{}'.format(key) s3_client.download_file(bucket, key, download_path) resize_image(download_path, upload_path) s3_client.upload_file(upload_path, '{}resized'.format(bucket), key) Any idea why I'm getting this error? -
Django 2.0 - Add admin template to regular view
I'm trying to add the template of the Django Administration to a simple app view with staff member permissions. I've added {% extends "admin/base_site.html" %} at the top of my view, but some parts of the header are missing. Normal admin header: Test view with admin template: my_app/urls.py: from django.urls import path from . import views urlpatterns = [ path('test/', views.test, name='test') ] my_app/views.py: from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import render @staff_member_required def test(request): return render(request, 'test.html') my_app/templates/test.html: {% extends "admin/base_site.html" %} {% block content %} <p>Test</p> {% endblock %} my_project/urls.py: from django.contrib import admin from django.urls import include, path admin.autodiscover() admin.site.site_header = "Test 1" admin.site.index_title = "Test 2" admin.site.site_title = "Test 3" urlpatterns = [ path('my_app/', include('my_proj.my_app.urls')), path('', admin.site.urls), ] Thank you! -
Filter objects by self relation
Here is my Django model: class Message(models.Model): text = models.TextField() parent = models.ForeignKey('Message', null=True, on_delete=models.SET_NULL) threads = ThreadManager() class ThreadManager(models.Manager): def get_queryset(self): return super(ThreadManager, self).get_queryset().filter() As you see, it uses a custom manager. In ThreadManager I want to filter messages which has a self relation. I mean parent refers to its record. (x.parent = x) How to write that filter? Is it possible at all? -
Referencing instance attribute in template passed from view.py - django 2.0
Hopefully a simple one... views.py def View(request): queryset = Example.objects.all() for obj in queryset : obj.x = 'String attribute added to model instance.' context = {'queryset ': queryset } return render(request, 'app/template.html', context=context) template.html {% for obj in queryset %} {{ obj.x }} {% endfor %} According to Stefano Contini's article this should work but in my example {{obj.x}} is not pulling through the string. What am I doing wrong? -
Interpreter Python Path - Django
i deploy a website (in Django) and i isolate a error from the Apache error_log that correspond to a problem of loading import. But i dont know how to solve it !!! wsgi.py """ WSGI config for MYSITE project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os import sys from django.core.wsgi import get_wsgi_application path = 'PATHTOMYSITE' if path not in sys.path: sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MYSITE.settings") application = get_wsgi_application() Running Python in sudo for test sudo /MYVIRTUALENV/bin/python3.6 wsgi.py lines code.... no error Running Python without sudo mod for test sudo /MYVIRTUALENV/bin/python3.6 wsgi.py lines code.... And at the line : application = get_wsgi_application() I have this error : File "<stdin>", line 1, in <module> File "/MYVIRTUALENV/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/MYVIRTUALENV/lib64/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/MYVIRTUALENV/lib64/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/MYVIRTUALENV/lib64/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/MYVIRTUALENV/lib64/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
Django ManyToManyField Approve Add
In our app I have a lot of ManyToManyFields, for which some need the add or remove action to be approved by a supervisor. At the moment we solve this by adding another Model, and when this model gets approved, the Field is added to the ManyToMany Field. I find this quite stupid to be honest, that I am doing the same work for every ManyToManyField and thought there might be a better solution for this. I played around with Django-FSM already and this is exactly what I need in our app, but it only works for a status field and not for doing something like described above. Does anybody has an idea on how to improve this process? -
Why does request not happen in Firefox browser?
I have two views linked to different templates. When I want to go to another page by using a link, everything goes fine. But not for Firefox... why does that happen ? I am using Django 2.0.3. Instead of getting a request to my link, I get just /?q= Anyone encountered something similar ? I also tried cleaning the cache. -
What Type Object comes from Django model
I have been practising with pure Django (django without js) for a while now.I have therefore decided to go some step further to include Jquery Ajax in my django.Where i can be able to insert some data dynamically into my html. The problem however is i don't know the type of object that comes from django, because in all cases i have tried (json , text) in my codes , it's like is not recognized. below is my jquery.The code works fine because am looping through a manually created data object. function ajaxLoad(item){ $.ajax({ type: 'POST', url : '../ajax/fetch_category/', data: { 'parameter':item }, cache:false, dataType: 'text', success: function(response_data) { var data = { 'slug': 'aerial-view-mombasa-city', 'title': 'Aerial view of Mombasa Citytar wars' } $.each( data, function(key,val){ console.log(key+' : '+val); }); }, error: function(XMLHttpRequest,textStatus,errorThrown) { console.log("XMLHttpRequest", XMLHttpRequest); console.log("textStatus", textStatus); console.log("errorThrown", errorThrown); } }); } But now if i try to loop through a response object from django response_data i get the following error :Uncaught TypeError: Cannot use 'in' operator to search for 'length' in {'slug': 'aerial-view-mombasa-city', 'title': 'Aerial view of Mombasa Citytar wars'} function ajaxLoad(item){ $.ajax({ type: 'POST', url : '../ajax/fetch_category/', data: { 'parameter':item }, cache:false, dataType: 'text', success: function(response_data) { … -
Download a file to local computer through link on other website
The code below is in a function called from a view. The website www.example.com called below is not owned by me. br = mechanicalsoup.StatefulBrowser( soup_config={'features': 'lxml'}, raise_on_404=True, user_agent="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13" ) br.open('http://www.example.com/Login.aspx') br.select_form('form[id=Login]') br["txtLogin"] = user_id br['txtpwd'] = password x = br.submit_selected("cmdLogin") x = br.open('http://www.example.com/frmClientView.aspx') br.select_form('form[id=aspnetForm]') br["ctl00$ContentPlaceHolder1$cmbSearch"] = "Client Code" submit_response = br.submit_selected() soup = BeautifulSoup(submit_response.content, 'lxml') table = soup.find(id="ctl00_ContentPlaceHolder1_grdDetail") The table has some href links to download files.The files are downloaded on the server. Is there some way to download the linked files on the local computer. Thanks in advance -
unable to install django-rest-swagger
I am trying to install django-rest-swagger into a virtual machine but it is giving error Failed Building wheel for simplejson i tried searching for some solution but as far as i was able to understand is that there is some dependency on visual studio... i have microsoft visual studio 2015 installed on my system I am attaching the installation report and see just before the error its written unable to find specified path and there is a path for library of visual studio first it shows that the specified directory wasn't found Error that came up while installing the package in continuation of the first image -
Django channels, disconnect
I have my WebSockets working with django channels. The last thing I'd like to do is close the socket if a user clicks a button, so in the frontend, I just send a disconnect message to the server: socket.send({action: 'disconnect'}); Then, in my consumer, I simply disconnect: async def receive(self, text_data): text_data_json = json.loads(text_data) if 'action' in text_data_json and text_data_json['action'] == 'disconnect': await self.disconnect(0) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) Why is my WebSocket not disconnecting properly? (I still receive messages) -
Django - Apache2 403 Forbidden
I created a django project under /home/toto/Desktop named dash_test and I wanted to serve my django application with apache2 and mod_wsgi. I installed the Apache web server, the mod_wsgi, and pip using this command sudo apt-get install python-pip apache2 libapache2-mod-wsgi. And I created a python virtual environment within the project directory named developer. The allowed_hosts in the settings.py looks like this : ALLOWED_HOSTS = ['xxx.xxx.xxx.xxx', 'localhost', '127.0.0.1'] I added the static_url and the static_root: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I did run a collectstatic And I configured apache by editing the 000-default.conf : <VirtualHost *:80> Alias /static /home/toto/Desktop/dash_test/static <Directory /home/toto/Desktop/dash_test/static> Require all granted </Directory> <Directory /home/toto/Desktop/dash_test/dash_test> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess dash_test python-home=/home/toto/Desktop/dash_test/developer python-path=/home/toto/Desktop/dash_test WSGIProcessGroup dash_test WSGIScriptAlias / /home/toto/Desktop/dash_test/wsgi.py </VirtualHost> when I try to access the localhost I get this error: Forbidden You don't have permission to access / on this server. Apache/2.4.18 (Ubuntu) Server at localhost Port 80 I am using MySQL and phpMyAdmin instead of db.sqlite3 Thanks a lot.