Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination not working with ReadOnlyModelViewSet using django restframework
I have a ReadOnlyModelViewSet something like this class ViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = DetailsSerializer permission_classes = (IsAuthenticated, IsActive) def get_serializer_class(self): if self.action == 'list': return ListSerializer return DetailsSerializer def get_queryset(self): queryset = MyModel.objects.all() queryset = MyFilter().filter(self.request, queryset) queryset = queryset.prefetch_related( 'field1', 'field2', 'field3', 'field4' ) return queryset Hooked this up in urls like this router = routers.SimpleRouter() router.register(r'base', ViewSet, base_name='base') urlpatterns = [ url(r'^', include(router.urls)), ] I have enabled pagination globally by setting this in settings file: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, } When I make GET request without page query params or with page=1, i.e. the First page is coming fine. { "count": 3, "next": "http://localhost:8000/api/v1/base/?page=2", "previous": null, "results": [ { "id": 2, "name": "Apple", }, { "id": 3, "name": "Banana", } ] } When I make GET request to page 2, it not returning data, this what's being returned : { "detail": "Invalid page." } I tried digging into paginator files of django & drf and I have found that the count property of django paginator is somehow getting wrongly updated. Any help/suggestion/direction is much appreciated. -
How to fixJSON_PARSING_ERROR: Unexpected character?
I'm using Django to send notifications to android users and requests library to handle the post request. This is my code snippet where I send the actual request to FCM. def sendNotification(rule_name): url = "https://fcm.googleapis.com/fcm/send" headers = {'Authorization': '********************', 'Content-Type': 'application/json'} myDict = {"to": "/topics/rules", "data": { "rule_name": rule_name } } r = requests.post(url, headers=headers, data=myDict) print r.status_code print r.text However the response that I get when I print the status code and text is: 400 JSON_PARSING_ERROR: Unexpected character (t) at position 0. Can you please point out what is wrong here with my code? -
Trying to install Django channels but getting the following error
enter image description here An exit status2 is being shown. -
Difference between test_urls.py and test_views.py
I'm currently learning how to write tests in Django: I've used the approach to create an extra test folder which has test files for every "Django module". tests/ test_urls.py test_views.py test_models.py ... My problem is that I don't know the exact different between the test_urls.py file and test_views.py For example I have this test: def test_login_url(self): path = reverse('login') response = self.client.get(path) self.assertEqual(response.status_code, 200) Should I place this test in the test_urls.py file or in test_views.py The "login" url is in the urls.py file but the view that belongs to that url is in views.py Which file should I choose? Are there any best practices for this? -
Format of DRF error messages
I was wondering if anyone knows why is it that DRF doesn't capitalise the first letter of the user object in the error message and is there a simple way to correct this? Error message for create user: { "password": [ "This field is required." ], "email": [ "user with this email already exists." ] } models.py class User(AbstractBaseUser, PermissionsMixin): created = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email serializers.py class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ('id', 'password', 'email') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = models.User(email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user views.py class UserListView(generics.ListCreateAPIView): queryset = User.objects.all() def create(self, request, *args, **kwargs): serializer = RegisterUserSerializer(data=request.data) if serializer.is_valid(): self.perform_create(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
create a web page with django and run k-means on selectable features
I'd like to create a web page that shows features. The user select +2 features and click on 'run' to build clusters with k-means algorithm. I'd like to know if django is capable of doing that. Python is the only language I can manipulate. Please provide me with steps. Thanks. -
filterset_fields with DjangoFilterBackend not working
My class: class InvoicePeriodViewSet(viewsets.ModelViewSet): permission_classes = ( permissions.AllowAny, ) queryset = models.InvoicePeriod.objects.all() serializer_class = serializers.InvoicePeriodSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filterset_fields = ('days_interval', ) it's not working at all. I searched in other stack overflow questions and they didn't help me (here, here, here and here). I have 'django-filter' (django-filter==1.0.4) added to my apps, my django version is (Django==1.11.1) and rest (djangorestframework==3.8.2) I really don't want to add a filter_class. I have other view with filterclass and it's working but I don't want to make so many filterclasses. It would be perfect that the filterset_fields feature worked. If not I will have to create the filter_class by a function so I won't have to create 30+ of them. -
How to download fpdf output file in django
I am trying to direct download the generated file by fpdf.output('myfilename.pfd','D') in the browser using Django view. for single python file it works properly but I am unable to do it into the Django view -
Can' install Django 1.11 version with python 2.7 virtual environment
I am trying to setup django-2.0 & django-1.11 version in my system with virtual environment.I done the django-2.0 version with python-3 and am able to ran server. But i am facing issue when am able to install django-1.11 with python-2.7 it's installing Django-2.0 instead of django-1.11 >>> import django >>> print(django.get_version()) it's giving 1.11 django-admin startproject projectcName When am ran this command it's installing Django-2.0 and my django_admin --version is 2.0 -
Django: SQL result as dictonary
From the django documentation ( https://docs.djangoproject.com/el/2.1/topics/db/sql/ ) I'm using the function: def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] together with def my_custom_sql(self,sql): with connection.cursor() as cursor: cursor.execute(sql) row = dictfetchall(cursor) return row trying in the console: testen = my_custom_sql(Ausgaben,"SELECT TYP, count(*) Anzahl, sum(Summe) Summe FROM hhdata_Ausgaben group by typ") testen [{'Typ': 'Drogerie', 'Anzahl': 1, 'Summe': 6.0}, {'Typ': 'Essengehen', 'Anzahl': 1, 'Summe': 4.0}, {'Typ': 'Lieferant', 'Anzahl': 1, 'Summe': 50.0}, {'Typ': 'Taschengeld', 'Anzahl': 1, 'Summe': 5.0}] type(testen) <class 'list'> The result looks like a dictonary but it is a list and I can't access the key and values in my template: {% for key,value in testen.items %} <li><a href="{{key}}">{{value}}</a></li> {% endfor %} What am I doing wrong here? -
download link for an instance of django file field
i write make an xml file and save it to the database with filefield and i want to make a download link to template. it is my view: def xmlFile(request): all = request.POST data = dict(all) username = User.objects.get(username=request.user) xml = xmlFirst.dataToXml(data) with open('web/data/Fuzzy'+ str(username.username)+'1.xml','w') as myfile: myfile.write(xml) xmlFile = XmlFile(username= username, upload='Fuzzy'+ str(username.username)+'1.xml') xmlFile.save() xmlLink = XmlFile.objects.first() a = xmlLink.upload context = {'data':a} return render(request, 'xmlFile.html', context) how can i reach the download link? and my template is : <!DOCTYPE html> <html> <head> <title>aa</title> </head> <body> <a href="{{data}}">{{data}}</a> </body> </html> when i click on that link it has http://localhost:8003/xmlFile/FuzzyMirab1.xml that i want to be my file path that is in web data FuzzyMirab1.xml -
ImportError: No module named config (did you rename settings/local-dist.py?) when i try any command
IN project i have Settings folder inside that folder i put base.py,local.py,shell.py,test.py when i try to runserver it show me no module name config error.when i run any command like pytohn manage.py shell or manage.py runserver.N project i have Settings folder inside that folder i put base.py,local.py,shell.py,test.py when i try to runserver it show me no module name config error.when i run any command like pytohn manage.py shell or manage.py runserver. __init__.py """ Settings for online24 """ from .base import * try: from .local import * except ImportError as exc: exc.args = tuple( ['%s (did you rename settings/local-dist.py?)' % exc.args[0]]) raise exc Shell.py from .dev import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'cmsonline', 'USER': 'postgres1', 'PASSWORD': 'online244', 'HOST': '127.0.0.1', 'PORT': '5432' }, } test.py from .base import * DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", "USER": "", "PASSWORD": "", "HOST": "", "PORT": "", }, } SECRET_KEY = '{{ secret_key }}' local.py from . import base import config INSTALLED_APPS = base.INSTALLED_APPS + ('django_nose',) DATABASES = { 'default': { 'ENGINE': config.DB_ENGINE, 'NAME': config.DB_DATABASE, 'USER': config.DB_USERNAME, 'PASSWORD': config.DB_PASSWORD, 'HOST': config.DB_HOST, 'PORT': config.DB_PORT, }, }, } ) MANAGERS = ADMINS EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' CACHES = { 'default': { 'BACKEND': … -
Django solr setup on production(aws)
Django with solr haystack connection is working fine on development but how can I implement in aws ec2 instance (production) without using java --jar start.java. -
SSO for django and odoo (Single sign on)
I want to implement SSO in between Django application and Odoo ERP based application. I tried to create one client application from I want to switch to Django and Odoo and my client application is also in Djnago -
Push rejected to heroku since fail to compile python app
I try to deploy a Django app to Heroku and the push get rejected. The result shows that : Push rejected, failed to compile Python app. From the error script, it seems that the model "ConfigParser' is not found. How could I deal with it? Some part of the detailed command result scripts are as followed: remote: Collecting views==0.3 (from -r /tmp/build_ed5220ea80c3d6e758ae010 6d17c8450/requirements.txt (line 54)) remote: Downloading https://files.pythonhosted.org/packages/1b/d9/5598d 590f9467c364704397cbb0ebc9b33481b84e947c2af31cc1dc9fa11/views-0.3.tar.gz remote: Collecting w3lib==1.19.0 (from -r /tmp/build_ed5220ea80c3d6e758ae 0106d17c8450/requirements.txt (line 55)) remote: Downloading https://files.pythonhosted.org/packages/37/94/40c93 ad0cadac0f8cb729e1668823c71532fd4a7361b141aec535acb68e3/w3lib-1.19.0-py2.py3-non e-any.whl remote: Collecting Werkzeug==0.14.1 (from -r /tmp/build_ed5220ea80c3d6e75 8ae0106d17c8450/requirements.txt (line 56)) remote: Downloading https://files.pythonhosted.org/packages/20/c4/12e3e 56473e52375aa29c4764e70d1b8f3efa6682bef8d0aae04fe335243/Werkzeug-0.14.1-py2.py3- none-any.whl (322kB) remote: Collecting zope.interface==4.5.0 (from -r /tmp/build_ed5220ea80c3 d6e758ae0106d17c8450/requirements.txt (line 57)) remote: Downloading https://files.pythonhosted.org/packages/ac/8a/65753 2df378c2cd2a1fe6b12be3b4097521570769d4852ec02c24bd3594e/zope.interface-4.5.0.tar .gz (151kB) remote: Collecting psycopg2>=2.6.1 (from -r /tmp/build_ed5220ea80c3d6e758 ae0106d17c8450/requirements.txt (line 58)) remote: Downloading https://files.pythonhosted.org/packages/37/88/40748 331bf75d068a07bbea7dc658faceb0ce2e9fffdde550e76d5475e59/psycopg2-2.7.5-cp37-cp37 m-manylinux1_x86_64.whl (2.7MB) remote: Collecting MySQL-python (from mysql==0.0.1->-r /tmp/build_ed5220e a80c3d6e758ae0106d17c8450/requirements.txt (line 31)) remote: Downloading https://files.pythonhosted.org/packages/a5/e9/51b54 4da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip ( 108kB) remote: Complete output from command python setup.py egg_info: remote: Traceback (most recent call last): remote: File "<string>", line 1, in <module> remote: File "/tmp/pip-build-t_7e9for/MySQL-python/setup.py", line 13, in <module> remote: from setup_posix import get_config remote: File "/tmp/pip-build-t_7e9for/MySQL-python/setup_posix.py", line 2, in <module> remote: from ConfigParser import SafeConfigParser remote: ModuleNotFoundError: No module named 'ConfigParser' remote: remote: ---------------------------------------- remote: Command "python … -
unable save data to database sqlite using django
This is the request i am getting from user: [29/Aug/2018 11:48:19] "GET/build/operation=create_node&id=6&text=New+node HTTP/1.1" 500 14864 I tried this way but not working: views.py def basetest(request): cu_id = request.user.id if 'operation' in request.GET and "id" in request.GET and "text" in request.GET: operation = request.GET['opearation'] pid=request.GET['id'] nodename=request.GET['text'] if "create_node" == operation: p=Buildkb4.objects.create(parent=pid,created_by=cu_id,text=nodename) p.save() elif "rename_node" == operation: p=Buildkb4.objects.update(text= text).filter(parent=pid) p.save() return render(request,"registration/basetest.html") urls.py: path('buildknowledge/', views.basetest, name='buildkb'), -
Switch Remote User in remote authentication / windows authentication in Django
I want to give option "Signin as Different User" in my windows authentication webapp. After searching too many options I didn't find anything. I tried def signindiffuser(request,template_name): return render(request,template_name,status=401) It is helping me to switch user but asking for windows credentials again and again and not refreshing the page when submitting them. Please suggest. Thanks in Advance. -
Django rest-framework with GenericViewSet: Filter results base on query parameters from the url
My application is using GenericViewSet with ListModelMixin. I have used filter_backends and filter_class to filter out results. (see 'list': serializers.BookingListSerializer from screenshot below) I am working on the following brief: Let's say I have a list of animals which are pre-filtered (using filter_backends) and then shown on UI to the user. Users can further filter results based on some search criteria from UI (let's say name, type, color). These filterations are handled by filter_class. In a separate Tab on UI which only shows animals of type Dogs rather than the entire collection of animals. And which can again be filtered further based on the name & color. I must create 2 separate end-points to show both kinds of results to the user (to have more control over results...ya screw DRY!). But I can't figure out how to create them in Django as both animals and dogs use the same django modal and the filter backends and filter class are applied only to the actual modal ie. on the list of animals. I need simple def list1(request) and def list2(request) where I can filter the query_set based on request params and my filter backends and filter classes. -
Apache Error: While writing python logs into file outside the project directory
I am working on a Django project and using Apache as web server. Everything is working fine with python manage.py runserver But while running the application through apache I am not able to write my python app logs into the stated path which is outside the project directory. Project directory /home/ubuntu/saas-DocumentProcessing Log files are in /home/ubuntu/log/SaasAap/SaasAap.log and /home/ubuntu/log/error/error.log My 000-default.conf content <VirtualHost *:8000> ServerAdmin abc@xyz.com ServerName my_ip ServerAlias my_ip DocumentRoot /home/ubuntu/saas-DocumentProcessing/ WSGIScriptAlias / /home/ubuntu/saas-DocumentProcessing/src/wsgi.py Alias /static/ /home/ubuntu/saas-DocumentProcessing/static/ ErrorLog /home/ubuntu/log/error.log CustomLog /home/ubuntu/log/custom.log combined <Location "/static/"> Options -Indexes AllowOverride All Require all granted </Location> <Location "/"> AllowOverride All Require all granted </Location> <Directory /home/ubuntu/saas-DocumentProcessing/static> Order allow,deny Allow from all </Directory> <Directory /home/ubuntu/log> Order allow,deny Allow from all </Directory> WSGIDaemonProcess saas-DocumentProcessing python-path=/home/ubuntu/ saas-DocumentProcessing python-home=/home/ubuntu/saas-DocumentProcessing/ve nv WSGIProcessGroup saas-DocumentProcessing </VirtualHost> -
How to use CompositeForeignKey in a model
I have installed django-composite-foreignkey using pip in an Anaconda cmd interface while having the virtual environment active. When I use CompositeForeignKey like this: PersOrg = CompositeForeignKey(Organisation, on_delete=CASCADE, to_fields={'ClientId', 'OrgCode'}) I get the error: NameError: name 'CompositeForeignKey' is not defined I have tried: import django-composite-foreignkey but get the error: import django-composite-foreignkey ^ SyntaxError: invalid syntax. How do I make the model aware of the existence of CompositeForeignKey? or is there a better way to refer to a multiple field foreign key. I have a database where multiple clients will register and e.g. define their own staff working in their organisation. Typically, a model will have this definition: class Person(models.Model): ClientId = models.ForeignKey('clients.Client', on_delete=models.CASCADE, to_field='id') PersNumber = models.PositiveIntegerField(null=False) PersSurName = models.CharField(max_length=40, null=False) PersNames = models.CharField(max_length=40, null=False) PersIsStaff = models.BooleanField(null=False) PersMobile = models.CharField(max_length=13) PersWork = models.CharField(max_length=13, blank=True) PersEmail = models.EmailField(max_length= 80, blank=True) PersWorkTitle = models.CharField(max_length=40) PersOrg = CompositeForeignKey(Organisation, on_delete=CASCADE, to_fields={'ClientId', 'OrgCode'}) class Meta: unique_together = (('ClientId', 'PersNumber'),) def __str__(self): """Return a string representation of the model""" return str(self.PersNumber) + ' - ' + self.PersSurName + ' - ' + self.PersNames In each model there will be a client id and one (or more) other fields that are unique together. As in the example … -
Django generate custom ID
I saw this answer but there is no specific answer yet. I want to create custom id that starts with letter. When a new record comes into database I want to change the id to A00001, .... A00002, .... A00010, ...A10000 etc. The id will be always in range 99999- 00001 so how can I do that? my model is simple: class Custom(models.Model): id = models.AutoField(primary_key=True, editable=False) -
How to have DecimalFields without explicitly mentioning decimal_places and max_digits as in Postgres
I plan to have the following table in Postgres create table Transaction ( tax_amount decimal ); I wish not to specific number of digits explicitly. For Django model, I use tax_amount = models.DecimalField(blank=True, null=True) I'm getting error billing.Transaction.tax_amount: (fields.E130) DecimalFields must define a 'decimal_places' attribute. billing.Transaction.tax_amount: (fields.E132) DecimalFields must define a 'max_digits' attribute. I was wondering, how can I have Django translated to equivalent Postgres SQL, without mentioning decimal_places and max_digits explicitly? -
How to parse the following dict in django templates?
I have a following dict structure passed to my Django template, whose keys or length are unknown to me: config_values = { 'Kafka': { 'KAFKA_BROKER_URL': 'localhost:9092', }, 'Redis': { 'REDIS_HOST': 'localhost', 'REDIS_PORT': '6379', }, } I want to show it in my templates as shown below Kafka KAFKA_BROKER_URL = localhost:9092 Redis REDIS_HOST = localhost REDIS_PORT = 6379 I'm relatively new to python and dicts. -
Django/Angualr 4 CORS issue
I am running two angular 4 apps served through two django different apps (as static files served. That is working perfectly fine). I have a "parent app" and a "child app". Both apps are served through their own Django application on their own identical app ( we literally copied the django app to serve both the parent and the child). ] THE ISSUE: We are facing a CORS issue between loading the child app on the parent app in an iFrame. what's going on: The chld app is loaded by the parent appp Parent app: <div *ngIf="theRoute"> <iframe [src]="myUrl" appHeght id="myIFrame"></iframe> </div> My parent-app IFrame Component: ngOnInit() { // The Router is correct, and so are the params. this.myRouter = this.route.params.subscribe( params => { ... this.myUrl = this.sanitizer.bypassSecurityTrustResourceUrl('http://127.0.0.1:8201/'); // location of the child ... // more stuff, including change detection } ); } my PARENT DJANGO App - SETTINGS.PY: import os import datetime BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'my parent secret' DEBUG = True ALLOWED_HOSTS = '*' INSTALLED_APPS = [ 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'spa.middleware.SPAMiddleware', ] ROOT_URLCONF = 'my_project_proj.urls' TEMPLATES = [ … -
Parse JSON object in python Django framework
How to parse below JSON object in python to get part_number, product_name and quantity? {'products': [{'part_number': 'sda', 'product_name': 'asdas', 'quantity': '12'}, {'part_number': 'asd', 'product_name': 'dfg', 'quantity': '3'}]} kindly help. Thanks