Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Twitter get authenticated user followers
I am working on simple django project connected with Twitter api. I have to implement 2 things. 1.User autenthication using Twitter.(done). Showing logged user full name is done. 2.Show list of followers on landing page (right now i am just showing logged user full name using ). Question: How can i quickly use logged user auth token and key to send API requests to get follower ids? -
Django NoReverseMatch when using url in a template
I'm running Django 1.10 on Mac OS X. I'm trying to put some links in my templates but I got a NoReverseMatch Error in both templates. The error looks like this :NoReverseMatch at /kfet/ with the following sentence : Reverse for 'interface' with arguments '()' and keyword arguments '{'id_ienkli': ''}' not found. 1 pattern(s) tried: ['kfet/interface_du_klient/(?P<id_ienkli>\\d+)$'] Here is the urls.py in my app : #-*- coding: utf-8 -*- from kfet import views from django.conf.urls import url from . import views from kfet.models import klient from django.urls import reverse urlpatterns = [ url(r'^$', views.accueil, name='accueil'), url(r'^interface_du_klient/(?P<id_ienkli>\d+)$', views.interface_du_klient, name='interface'), url(r'^date$', views.date_actuelle), url(r'^achat/(?P<id_bouffon>\d+)/(?P<id_ach>\d+)$', views.achat,name='achat') ] Here is my views.py : #-*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render from kfet.models import klient,achetables from django.shortcuts import get_object_or_404 from django.urls import reverse from datetime import datetime def date_actuelle(request): return render(request, 'kfet/date.html', {'date': datetime.now()}) def accueil(request): liste_tokards=klient.objects.all() return render(request, "kfet/accueil.html",{'liste_tokards': liste_tokards} ) def interface_du_klient(request,id_ienkli): produits=achetables.objects.all() klient_selec=get_object_or_404(klient, id_klient=id_ienkli) if id_ienkli==0: return redirect('accueil') else : render(request, "kfet/interface_du_klient.html", {'client': klient_selec}, {'liste_produits' : produits}) def achat(request,id_bouffon,id_ach): klient_selec=get_object_or_404(klient, id_klient=id_ienkli) if id_ach==0: return redirect('interface_du_klient', id_ienkli=id_bouffon) else: klient_selec.acheter(id_ach) return render(request, "kfet/interface_du_klient.html", {'client': klient_selec}, {'liste_produits' : produits}) Here is my interface_du_klient.html : <h1>Bienvenue sur le site de la KFet !</h1> … -
Automatically cache view after cache expires in django
I have this in my views.py @cache_page(60 * 5) def get_campaign_count(request): return HttpResponse( json.dumps({ 'count': Campaign.objects.get_true_campaign_query().filter(dismissed=False).count() }, cls=DjangoJSONEncoder ), content_type='application/json') Getting the count takes some time (20-40 seconds) each time it loads, so I decided to add caching to it with a 5 minute expiration time. My question is, is it possible to tell django to automatically re-cache the page during expiration? Otherwise another user would have to go through the 20-40 seconds wait before getting the response before other users benefit from the cache. -
Django - MySQL - SELECT all columns WHERE one column is DISTINCT
So I'm reading this answer about selecting all columns of a table where only one of them is distinct, and it's exactly what I need, but unfortunately it's a MySQL question and not a django question, and I can't find a way to translate that to django. The answer is very simple: SELECT col1, col2 FROM mytable GROUP BY col2 But I can't find a way to do the same using django. Anything similar that gets me multiple columns of a model with one of them distinct will suffice. I'm using MySQL and Django 1.9. Thank you. -
How can I let Django load models from subpackages of apps?
I essentially have the following issue: Say, the model classes I define are in /app/cog/models.py, but Django only checks for them in /app/models.py . Is there any way to let Django dynamically read all the model classes in all models.py files in all subpackages of app? -
Django has no attribute 'Morsel'
When I run any python manage.py command I get this error. I can import django in a python shell so I'm not really sure why it can't find this specific module. Traceback (most recent call last): File "./docker/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 2, in <module> from django.core.handlers.wsgi import WSGIHandler File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 10, in <module> from django import http File "/usr/local/lib/python2.7/dist-packages/django/http/__init__.py", line 1, in <module> from django.http.cookie import SimpleCookie, parse_cookie File "/usr/local/lib/python2.7/dist-packages/django/http/cookie.py", line 22, in <module> Morsel = http_cookies.Morsel AttributeError: 'module' object has no attribute 'Morsel' -
Is it really possible to have free access to Google+ Domain APIs in Django?
I am trying to follow this tutorial: https://developers.google.com/+/domains/circles/listing. There is a Python quick starting guide saying to use domain-wide delegation of authority to get domain-wide access to user data: https://developers.google.com/+/domains/authentication/delegation. Looking into it seems that it goes really deep and I am not sure if this is going to help me in my case. It involves Google Apps, custom integration etc.., but I have a stand alone Django web app independent from Google. Here is my code: from oauth2client.client import OAuth2WebServerFlow SCOPES = ['https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/plus.circles.read'] REDIRECT_URI = 'http://myapp.com/oauth2callback/' def google_plus_friends(request): flow = OAuth2WebServerFlow(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=SCOPES, redirect_uri=REDIRECT_URI) auth_uri = flow.step1_get_authorize_url() return redirect(auth_uri) def oauth2callback(request): code = request.GET.get('code', '') flow = OAuth2WebServerFlow(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=SCOPES, redirect_uri=REDIRECT_URI) credentials = flow.step2_exchange(code) http = httplib2.Http() http = credentials.authorize(http) service = build('plusDomains', 'v1', http=http) circle_service = service.circles() request = circle_service.list(userId='me') while request is not None: # Here is where google api returns the error: circle_list = request.execute() if circle_list.get('items') is not None: # Google+ circles for the current user circles = circle_list.get('items') for circle in circles: logging.debug(circle.get('displayName')) ... It results in: < HttpError 403 when requesting https://www.googleapis.com/plusDomains/v1/people/me/circles?alt=json returned "Forbidden"> Is it possible to use those APIs in my Django app and do I need any payed Google … -
how to get values in get_context_data
Hi everyone My model has this attribute class Entry(models.Model): TYPES_CHOICES = ( ('none', 'not specified'), ('v', 'By Visit'), ('p', 'By Patient'), ) app_config = AppHookConfigField(HealthConfig) url = models.CharField(blank=True, default='', max_length=250) count = models.CharField(blank=True, default='', max_length=250) start = models.CharField(blank=True, default='', max_length=250) status = models.CharField(choices=TYPES_CHOICES, max_length=10, default='') in my view I have a generic List view like this class IndexView(AppConfigMixin, generic.ListView): model = Entry template_name = 'health/index.html' def get_queryset(self): qs = super(IndexView, self).get_queryset() return qs.namespace(self.namespace) def get_context_data (self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) values_to_pass = context['object_list'].values('url', 'count', 'start') context['object_list'] = values_to_pass print values_to_pass return context How to get the value url,count and start to join in one value and pass the the html file final= url + count + start now print values_to_pass return a empty list [] Any idea! -
heroku run python manage.py migrate -> No module named production
I am new to python/django and need some help. Currently, I am working on a book called hellowebapp and came across a problem during heroku deployment. When I type "heroku run python manage.py migrate", I get this message : the screen shot of the error message Running python manage.py migrate on ⬢ ryujihellowebapp... up, run.4755 (Free) Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/init.py", line 353, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/init.py", line 302, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/init.py", line 55, in getattr self._setup(name) File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/init.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/init.py", line 99, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: No module named production How can I fix the last part ? : __import__(name) ImportError: No module named production Also, when I type 'heroku open' and open the application in a browser, there is a message that says "Application Error". Everything works fine with no error message in localhost and seems like there was no issue I pushed the app to heroku. As soon as I started to work on the heroku migration part, the problem started to occur. Thank you. -
SignatureDoesNotMatch s3 python ios
HI I am new to python django tastypie.From past one month I am trying to upload an image from my ios app but couldn't able to succeed yet still I am trying to get this done but I am not able to do so.though my secret key and access key are both correct I am getting below error while uploading: <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> python server side code: class PreSignImage(Resource): results = fields.CharField(attribute='aws_string',readonly=True, null=True,blank=True) class Meta: object_class=FeedObject allowed_methods = ['get'] always_return_data = True authentication = Authentication() serializer = Serializer(formats=['json']) authorization = Authorization() include_resource_uri=False resource_name = 'upload_image' always_return_data = True def get_object_list(self, bundle): results = list() file_name=bundle.request.GET['file_name'] file_type=bundle.request.GET['file_type'] s3 = boto3.client('s3',aws_access_key_id=settings.AWS_ACCESS_KEY,aws_secret_access_key=settings.AWS_SECRET_KEY) presigned_post = s3.generate_presigned_url('put_object', Params = {'Bucket': settings.S3_BUCKET, 'Key': file_name}, ExpiresIn = 300) screenobj = FeedObject() screenobj.aws_string=presigned_post results.append(screenobj) #data=json.dumps({'data': presigned_post,'url': 'https://%s.s3.amazonaws.com/%s' % (settings.S3_BUCKET, file_name)}) #response=HttpResponse(content=data,status=200,content_type="application/json;") #response['Content-Length']=len(data) return results ios code: -(void) uploadImage:(UIImage *)image atUrl:(NSString *)url withMimeType:(NSString *)mimeType { NSData *imageData = UIImageJPEGRepresentation(image, 0.1); NSURL *requestURL = [NSURL URLWithString:url]; AFHTTPSessionManager *client = [[AFHTTPSessionManager alloc] initWithBaseURL:requestURL]; client.responseSerializer=[AFJSONResponseSerializer serializer]; NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:client.responseSerializer.acceptableContentTypes]; [contentTypes addObject:@"application/xml"]; client.responseSerializer.acceptableContentTypes=contentTypes; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setHTTPMethod:@"PUT"]; [request setHTTPBody:imageData]; [request … -
Django: get object's random atribute
Here is my model class: class Player(models.Model): name = models.CharField(max_length=50) photo = models.ImageField() games = models.IntegerField() minutes = models.IntegerField() points = models.IntegerField() assists = models.IntegerField() rebounds = models.IntegerField() steals = models.IntegerField() def __unicode__(self): return self.name I want to show one of these atributes randomly. What is the best way to do so? -
Syntax error Django(1.10.1) when doing py -3.5 manage.py runserver
` PS C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder> py manage.py runserver Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\ma y", line 367, in execute_from_command_line utility.execute() File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\ma y", line 316, in execute settings.INSTALLED_APPS File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__ , in __getattr__ self._setup(name) File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__ , in _setup self._wrapped = Settings(settings_module) File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__ , in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line ule return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder\config\settings\local.py", line 15, from .common import * # noqa File "C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder\config\settings\common.py", line 13 import environ File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\environ.py", l raise ValueError, "No frame marked with %s." % fname ^ SyntaxError: invalid syntax` Been trying to start a new Django project using Python 3.5 but I just cannot figure out what is causing this problem, maybe it's because of where my environ.py is stored? I'm really not sure, all help is appreciated! -
Django admin login_redirect url next parameter
I need a user to be redirected to a different page(for two factor authentication) once he logins inside the admin page. I tried to populate the LOGIN_REDIRECT_URL and it does not work. As per the document. https://docs.djangoproject.com/en/1.7/ref/settings/#login-redirect-url the default page is '/accounts/profile/' if the next parameter is not given. How can I pass the next parameter, do I need to change the login_page html to include the next parameter? -
Inconsistent json serializer in django.core.serializers
If I take a simple ListView, and wish to return JSON: from django.core import serializers from django.http import JsonResponse class MyListView(ListView): def get_queryset(self): return Thing.objects.all() def get(self, request, *args, **kwargs): data = serializers.serialize("json", self.get_queryset()) return JsonResponse(data, status=200, safe=False) This will give me "valid" json. However, the json will be delivered like this: It's not only an eyesore, if you then try to print that (eg via console.log), those """ on lines 2, 8, 11 will become \". (This has been noted in other questions). To parse that json in the browser, you need to run it through JSON.parse twice (or transpile the escaped chars another way). On the other hand, if I do the below code (and this is my present hack for getting around the problem): data = list(map(lambda thing: {"pk": thing.pk, <etc>}, self.get_queryset())) return JsonResponse(data, status=200, safe=False) This gives me valid json without the additional " chars (excuse the cat pic): My question: clearly, the browser is getting different inputs. Yes, they're both valid json (they pass validators) - but the first won't clear JSON.parse(). Is there any way to force the core serializer to conform to the second json output format? At present I'm having to write … -
Bootstrap's navbar doesn't work
Currently I am learning Django framework, I've decided to get familiar with it by making a simple Blog app, but I've problem with navigation bar, I'm trying to make a responsive navbar, with collapse classes etc. I've searched about this problem in this forum, but nothing helped, so I need personal help if possible. That's my code, please note that I did include bootstrap and bootstrap's javascript plugin. Thanks in advance. <div class="navbar-wrapper"> <nav class="navbar navbar-inverse navbar-static-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar" aria-expanded="false" aria-controls="navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">MyBlogName</a> </div> <div class="collapse navbar-collapse" id ="navbar"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Page 1</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> </ul> </div> </div> </nav> </div> -
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and i sn't in an application in INSTALLED_APPS
Whenever I try to run makemigrations or runserver, I get this error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. HOWEVER: Here it is in INSTALLED_APPS-- WSGI_APPLICATION = 'mysite.wsgi.application' import django django.setup() from django.contrib.contenttypes.models import ContentType # Application definition INSTALLED_APPS = [ 'django.contrib.contenttypes.models.ContentType', 'accounts.apps.AccountsConfig', 'posts.apps.PostsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_comments', 'django_comments_xtd', 'django.contrib.sites', 'category', #'vote', 'tinymce', 'django_wysiwyg', 'follow', 'djrichtextfield', 'ckeditor', #'likes', 'secretballot', 'hitcount', #'pinax', 'pinax.likes', #'pinax', #'pinax_theme_bootstrap', #'bootstrapform', #'voting', 'actstream', ] What could be causing this? It's explicitly stated in Installed_Apps, as you can see. -
Permission class on detail route not working
I'm new to DRF, but I'm trying to use a permission class on a @detail_route using the method in this stack thread: Using a permission class on a detail route My code currently looks like this : @detail_route(methods=['GET'], permission_classes=[IsStaffOrRestaurantUser]) def restaurant_dishes_ready_for_pickup(self, request, pk=None): ...stuff.... class IsStaffOrRestaurantUser(permissions.BasePermission): def has_object_permission(self, request, view, obj): print(request) print(view) print(obj) return False The print statements never get executed... I'm probably missing something but I've looked through the documentation and can't really figure it out, is my approach right at all? Thanks! -
ntegrityError NOT NULL constraint failed Request Method:POST
I have this function in my views. which worked on django 1.9 def post_create(request): form = PostForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) print(form.cleaned_data.get("title")) instance.save() context = { "form": form, } return render(request, "post_form.html", context) but this is what i get when i wrote it on django 1.10 : IntegrityError at /posts/create/ NOT NULL constraint failed: posts_post.updated Request Method: POST any ideas? -
render different page in the same div without reload page django
I am using django cms to create a website, I create a template for one specific kind of page. This page has a submenu. so in my template I show the submenu on the left side, I want to show the content of each page in the right site. So when I click on the item of my submenu in this template I don't reload the page, I only want to change the div with the info of this page. this is my template {% extends "base.html" %} {% load cms_tags menu_tags%} {% block title %}{% page_attribute "page_title" %}{% endblock title %} {% block content %} <div class="health_template"> <div class="container"> <div class="row"> <div class="col-xs-12 header_health_page"> <h1 class="pipe-title pipe-title--inset">{{ request.current_page.get_page_title }}</h1> <div class="breadcrumb_um"> <ul> {% block breadcrumb_mid %} {% show_breadcrumb %} {% endblock %} <ul> </div> </div> <div class="col-xs-2"> <ul class="menu_health"> {% show_sub_menu 1 %} </ul> </div> <div class="col-xs-10"> # here change the content </div> </div> </div> </div> {% endblock content %} Any idea? -
Django Restframework has_object_permission() function is not working for object permission
I'm in the process of debugging my custom permissions class and returning a value of False for my has_object_permission() function, but my I'm still able to access my API (GET request), via Restframework's API browser without authenticating and I can't understand why. Any help would be greatly appreciated. Please see code below. for whatever reasons, it appears that my has_object_permission function is not executing. Please Help urls.py router = BulkRouter() router.register(r'api1', SimpleViewSet1) urlpatterns = [ url(r'^test/', include(router.urls, namespace='api1')), ] views.py class SimpleViewSet1(generics.BulkModelViewSet): queryset = Barcode.objects.all() permission_classes = (MyUserPermission,) serializer_class = SimpleSerializer1 def get_queryset(self): user = User.objects.get(pk=2) return Barcode.objects.filter(owner = user) def get_object(self): obj = get_object_or_404(self.get_queryset()) self.check_object_permissions(self.request, obj) return obj permissions.py class MyUserPermission(BasePermission): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): return False serializer.py class SimpleSerializer1(BulkSerializerMixin, # only required in DRF3 ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta(object): model = Barcode # only required in DRF3 list_serializer_class = BulkListSerializer fields = ('barcode_number', 'barcode_type', 'owner') models.py @python_2_unicode_compatible class Barcode(models.Model): owner = models.ForeignKey('auth.User', related_name = 'barcodes') barcode_number = models.CharField(max_length=200) barcode_type = models.CharField(max_length=200) def __str__(self): return self.barcode_number -
Specifying "body" parameter in PUT/PATCH operations with Django Rest Framework
I'm using django-rest-swagger and django-rest-framework in conjunction to my web app project: I'm desperately trying to make my swagger UI looks better : better documentation and extra body parameters exposed with extra informations on methods When I use the viewsets.ModelViewSet with users : I have the body parameter. When I use the APIView I can't have these extra parameters or Model Example view in the right : My Views code : # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class AlertDetail(APIView): authentication_classes = (KairosTokenAuthentication) permission_classes = (IsAuthenticated,) """ Retrieve, update or delete a alert instance. """ def get_object(self, pk): try: return MonitEvent.objects.get(id=pk) except MonitEvent.DoesNotExist: raise Http404 def put(self, request, pk, format=None): alert = self.get_object(pk) serializer = AlertSerializer(alert, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, pk, format=None): alert = self.get_object(pk) serializer = AlertSerializer(alert) return Response(serializer.data) Alert Serializer : class AlertSerializer(serializers.HyperlinkedModelSerializer): server = serializers.ReadOnlyField(source='server.localhostname') class Meta: model = MonitEvent fields = ( 'id', 'server', 'event_message', # ... ) Any help would be appreciated ! -
Display specific events from google calendar
I am looking for a way to display specific event types from a google calendar as line items for upcoming events in order of when they will occur. Something like this: DD/MM - (Event title name) From X:XX a.m. - To X:XX p.m. DD/MM - (Event title name) From X:XX a.m. - To X:XX p.m. With those events linking to the calendar itself. My question is what would be the best way of going about this? I have the Google API Client Python installed; however, I am not sure if that is the best way. Any thoughts? -
django fails to load updated CSS
Django in my project its loading all the css characteristics even if i have deleted them. All the modifications in the html can be reflected but in css modifications doesn't shows up. Its like django is not loading the updated elements in the CSS file. Any clue how can i fix it ? My settings.py file :- import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '^&kq%o*0_&to!+l51tf@tnox6448q0&y7_arz0-uyp8txz5zb4' DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'blog', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' CKEDITOR_CONFIGS = { "default": { "removePlugins": "stylesheetparser", } } ROOT_URLCONF = 'MyBlog.urls' TEMPLATES_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'MyBlog.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT ='D:/projects/PyCharm projects/MyBlog/blog/media/' MEDIA_URL ='/blog/media/' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True -
MongoEngine object returning empty queryset when collection has entries in mongo database
So, this is my problem: I'm trying to return a queryset using MongoEngine 0.8.6 in Django 1.8.12. The model it's called Job and I already have some objects in the mongodb collection. However, when I do Job.objects.count() in django/shell I get 0 objects returned. If I do Job._get_colletion().count() I get the correct objects count from my Job collection. Already check if the Job object is using the correct collection in mongo and it is. But here's the funny part. I don't have this problem in any of my other environments: Local, Development and Staging. So, I checked the environments and they seem to be correct. I would really appreciate your help with this. Thanks. -
Create a custom lookup for multiple columns
i wanna search through columns (title and body) and return if they contains some specified text Mysql SELECT title , body FROM articles where match(title , body) against('some text' in Boolean mode) mysql query works just fine but when i want to develop a custom lookup. do not know how handle multiple columns for single column on docs we have. class Search(models.Lookup): lookup_name = 'search' def as_mysql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return 'MATCH (%s) AGAINST (%s IN BOOLEAN MODE)' % (lhs, rhs), params and then registering the class like models.CharField.register_lookup(Search) models.TextField.register_lookup(Search) now with one column (does not matters if title or body)it works fine best_matched_articles = Articles.objects.filter(title__search = 'home') how to do it with multiple column that have FULLTEXT index ?