Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Optimizing bulk inserts on a partitioned database?
I've reached a point where I'm being forced to partition a specific table. I'm using the Architect package to manage this, but with this transition comes the loss of foreign keys and bulk inserts. Since I'm now having to save every record individually, performance has bottomed out to unacceptable levels. Short of using transactions or threads to write multiple entries at once (neither of which I have tested so don't know how well/if they would work), are there any other obvious techniques I could use to increase performance of inserts to compensate for the loss of bulk_create? -
How can I debug "Exception while resolving variable 'exception_type' in template 'unknown'"?
I keep seeing DEBUG Exception while resolving variable 'exception_type' in template 'unknown'. in my django logs, followed by VariableDoesNotExist: Failed lookup for key [exception_type] in followed by what looks like a string representation of a a list of dictionaries containing the request, and my entire settings.py file. I feel like I just don't have enough information to debug this. All I know is there's a variable called exception_type in an unknown template. My code doesn't contain the string 'exception_type' anywhere. How can I debug this? Where should i be looking? -
Secure_ssl_redirect setting for django does nothing on heroku
I am deploying a Django app on heroku and trying to force https on all pages. I use the following settings for that: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Now when I visit www.mysite.de it does in fact not redirect me to https. Any ideas what I am missing? -
TemplateDoesNotExist at /books/index.html
I am trying to create my own project with Django version 1.10, but Running the server i get such exception: TemplateDoesNotExist at /books/index.html This is my folder structure: mysite/ books/ migrations template/ books/ index.html __init__.py admin.py apps.py models.py tests.py urls.py views.py mysite/ __init__.py dbsqlite3 settings.py urls.py wsgi.py tamplates/ base_books.html base.html dbsqlite3 manage.py settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], '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 = 'mysite.wsgi.application' mysite/books/urls.py : from django.conf.urls import url, include from books import views urlpatterns = [ url(r'^$', views.BooksModelView.as_view(), name='index'), url(r'^books/$', views.BookList.as_view(), name='books_list'), url(r'^author/$', views.AuthorList.as_view(), name='author_list'), url(r'^publisher/$', views.PublisherList.as_view(), name='publisher_list'), url(r'^books/(?P<pk>\d+)/$', views.BookDetail.as_view(), name='detail_list'), url(r'^author/(?P<pk>\d+)/$', views.AuthorDetail.as_view(), name='author_detail'), url(r'^publisher/(?P<pk>\d+)/$', views.PublisherDetail.as_view(), name='publisher_detail'), ] mysite/mysite/urls.py : from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^books/', include('books.urls', namespace="books")), url(r'^admin/', admin.site.urls), ] views.py : from django.views.generic.base import TemplateView from django.views.generic import ListView from django.views.generic import DetailView from books.models import Book, Author, Publisher # TemplateView class BooksModelView(TemplateView): template_name = 'books/index.html' def get_context_data(self, **kwargs): context = super(BooksModelView, self).get_context_data(**kwargs) context['object_list'] = ['Book', 'Author', 'Publisher'] return … -
Executing Django's sqlsequencereset code from within python
Django's sqlsequencereset command returns the SQL commands needed to reset sequences in the database. Is there an easy way to directly execute this returned code from inside python? Currently I'm: Using call_command to run sqlsequencereset Grabbing the output into an in-memory StringIO object (instead of writing to a file on disc) Removing the terminal color codes returned by sqlsequencereset Executing the SQL directly against Django's default database Other management commands automatically run the SQL by default (and only print out the output if you specify the --dry-run option). Am I missing something?! Code: import re import StringIO from django.core.management import call_command from django.db import connection app_name = 'my_app' # Get SQL commands from sqlsequencereset output = StringIO.StringIO() call_command('sqlsequencereset', app_name, stdout=output) sql = output.getvalue() # Remove terminal color codes from sqlsequencereset output ansi_escape = re.compile(r'\x1b[^m]*m') sql = ansi_escape.sub('', sql) with connection.cursor() as cursor: cursor.execute(sql) output.close() -
Django template forloop
Here's a excerpt from a Django template: <div id="list-of-things"> {% for key in things %} {% for thing in thing|get_dict_value:key %} <div id="thing-{{ count }}">{{key}}: {{ thing }}</div> {% endfor %} {% endfor %} </div> things is a dict and get_dict_value:key is simply thing[key]. What's needed in the final page is: <div id="thing-1">A: First thing</div> <div id="thing-2">A: Second thing</div> <div id="thing-3">B: Third thing</div> ... ...which means that I need some way of altering the count variable. Using forloop.counter here causes there to be duplicate values as the counter resets for each time through the outer loop. There doesn't seem to be any way to set a variable in this loop, so is there another means whereby count might be incremented as required? -
What should be in 'TEMPLATE_CONTEXT_PROCESSORS'
Lets say I've following code:(http://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html) from crispy_forms.helper import FormHelper class ExampleForm(forms.Form): [...] def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.helper = FormHelper() -- from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class ExampleForm(forms.Form): [...] def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-exampleForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.add_input(Submit('submit', 'Submit')) What should I write in 'TEMPLATE_CONTEXT_PROCESSORS'? I'm getting this error- Failed lookup for key [example_form] -
django-autocomplete-light with gm2m in modals bootstrap: doesn't show all choices
i I'm trying to get autocomplete-light with Gm2m , But autocomplete.GM2MQuerySetSequenceField doesn't shows all choices. View.py class RessourceAutocompleteView(Select2QuerySetSequenceView): def get_queryset(self): employees = Employees.objects.all() freecontracts = Frecontract.objects.filter(IS_ACTIVE=True) freeagencies = Freagencies.objects.filter(IS_ACTIVE=True) freelancers = Freelancers.objects.filter(IS_ACTIVE=True) if self.q: employees = Employees.objects.filter(EMP_FIRST_NAME__icontains=self.q) freecontracts = Frecontract.objects.filter(FIRST_NAME__icontains=self.q, IS_ACTIVE=True) freeagencies = Freagencies.objects.filter(AG_NAME__icontains=self.q, IS_ACTIVE=True) freelancers = Freelancers.objects.filter(FRE_FIRST_NAME__icontains=self.q, IS_ACTIVE=True) # # Aggregate querysets qs = QuerySetSequence(employees, freecontracts, freeagencies, freelancers) # qs = QuerySetSequence(employees) if self.q: # This would apply the filter on all the querysets qs = qs.filter(Q(EMP_FIRST_NAME__icontains=self.q)| Q(FIRST_NAME__icontains=self.q)| Q(AG_NAME__icontains=self.q) | Q(FRE_FIRST_NAME__icontains=self.q )) # This will limit each queryset so that they show an equal number # of results. qs = self.mixup_querysets(qs) return qs Forms.py : class QAMForm(autocomplete.FutureModelForm): def __init__(self, *args, **kwargs): super(QAMForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) TRANSLATOR = autocomplete.GM2MQuerySetSequenceField( queryset=autocomplete.QuerySetSequence( Employees.objects.all(), Frecontract.objects.all(), Freagencies.objects.all(), Freelancers.objects.all(), ), required=False, label=_("Traducteur(s)"), widget=autocomplete.QuerySetSequenceSelect2Multiple( 'qm:ressource-autocomplete'), ) PROOFREADER = autocomplete.GM2MQuerySetSequenceField( queryset=autocomplete.QuerySetSequence( # all models Employees.objects.all(), Frecontract.objects.all(), Freagencies.objects.all(), Freelancers.objects.all(), ), required=False, label=_("Relecteur(s)"), widget=autocomplete.QuerySetSequenceSelect2Multiple( 'qm:ressource-autocomplete'), ) PM = forms.ModelMultipleChoiceField(queryset=Employees.objects.filter(TYPE_RESOURCE__TYPE__in = ('PMJ', 'PMS')), required=False, label=_("PM(s)"),) # QA = forms.ModelChoiceField(queryset=Employees.objects.filter(TYPE_RESOURCE__TYPE__in=('PMJ', 'PMS')), # required=False) class Meta: model = Feedback fields = ['PM'] models.py: class Feedback(models.Model): #the fields TRANSLATOR = GM2MField() PROOFREADER = GM2MField() PM = models.CharField(max_length=250, blank=True, null=True) I apply it under modals bootstrap in … -
Create and read a Temporary file in a Django Command
I need to read a flow url as csv then this is what I do: class Command(BaseCommand): help = 'Admin command to import feed' def _download_flow(self, url): req = requests.get(url, stream=True) if req.status_code == 200: tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv") for line in req.iter_lines(): tmp.write(line) return tmp raise Exception('error:{}'.format(req.status_code)) def handle(self, *args, **options): catalog = self._download_flow(options['url']) with open(catalog.name, 'rU') as csvfile: reader = csv.DictReader( csvfile, delimiter=';', quotechar='"') for row in reader: raise Exception(row) catalog.close() Basically, from an url, I create a temporary csv file. Then, now I want to parse this file to work with lines but I don't know why my exception is not raised. (My file has content, i've checked). Do you have any clue to help me ? Thanks -
In javascript with variables and functions how would I write the syntax for if something is between a certain range? For example, between 0 and 0.34?
In javascript with variables and functions how would I write the syntax for if something is between a certain range? For example, between 0 and 0.34 -
Modify slug for every page of model on wagtail
I am trying to create a custom slug for every page of a specific Page model on Wagtail. I have been looking into and tried the RoutablePageMixin examples, but that seems to modify the url structure, not the slug itself. Here is what I am looking to do: Current page title: About Django current page slug: about-django page title I want: About Django page slug I want: awesome-things-about-django I looked at creating route method, but that didn't seem to modify the slug. Is there any way to prepend something onto your slug? I understand I can do this manually, but would prefer for it to happen automatically. -
Serving testpage while running django on nginx
I'm working through https://serversforhackers.com/video/letsencrypt-for-free-easy-ssl-certificates and https://certbot.eff.org/docs/intro.html , trying to add an ssl certificate to my site (django 1.8 on nginx on ubuntu 16.04). I want to be able to serve a test page from my server. My nginx document root is at /var/www/html. deploy@server:/var/www$ ll html/ total 40 drwxr-xr-x 3 root root 4096 Apr 26 21:17 ./ drwxr-xr-x 3 root root 4096 Apr 25 16:27 ../ drwxrwxrwx 2 root root 4096 Apr 27 11:16 .well-known/ -rw-r--r-- 1 root root 11321 Jun 21 2016 index.html -rw-r--r-- 1 root root 612 Feb 6 16:43 index.nginx-debian.html -rw-r--r-- 1 root root 11321 Apr 26 21:17 test.html nginx has has 2 config files. The first is default and has the following location block: location ~ /.well-known { allow all; } location ~ /.well-known/acme-challenge/ { allow all; } The second has : location ~* (?:^|/)\. { allow all; } location ^~ /\.well-known { allow all; } I want to be able to serve the test page by using: http://example.com/test.html Instead I get the screenshot above. How can I configure nginx or django to allow the test page to be served? If I paste http://www.example.org/.well-known/acme-challenge/6j3QzM4LGMRWaLYZXYTR98: " into the browser I get a 404 like in the screenshot. … -
Django- Reverse for 'question_detail' with arguments '()' and keyword arguments '{}' not found
When I type the slug in to the url I can see the detail view of that post however, I can't redirect to the newly formed post when it saves into db. The post's are getting saved but on the redirect I keep getting NoReverseMatch Error. (Reverse for 'question_detail' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'(?i)question/(?P[\w\-]+)/$']) I can't seem to crack it. questions-url.py: url(r'^(?P<slug>[\w\-]+)/$', QuestionDetailView.as_view(), name='question_detail') views- redirect (after form saved) : return reverse('questions:question_detail') views - detail view class QuestionDetailView(DetailView): template_name = "questions/question_detail.html" model = Question slug_url_kwarg = 'slug' models.py def get_absolute_url(self): return reverse('questions:question_detail', kwargs={'slug':self.slug, 'question_id':self.id}) -
Python create Ordered Dict with 30 most recent day keys
Hello I'm writing a Django application that reports on daily items purchased. I want to organize the data in a dictionary structure like so.. monthly_items = { "Apr-27" : [ list of objects purchased on April-27th ] "Apr-26" : [ list of objects purchased on April-26th ] "Apr-25" : [ list of objects purchased on April-25th ] "Apr-24" : [ list of objects purchased on April-24th ] ... "Mar-27" : [ list of objects purchased on March-27th ] } right now my code looks like this (start_date and end_date are configured for last month and today, respectively): month_dict = { 1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'June', 7: 'July', 8: 'Aug', 9: 'Sept', 10: 'Oct', 11: 'Nov', 12: 'Dec', } from collections import OrderedDict monthly_items = OrderedDict() # pull items from last 30 days items = Item.objects.filter(create_date__gte=start_date, create_date__lt=end_date).order_by('-create_date') for item in items: day = str(month_dict.get(item.create_date.month)) + '-' + str(item.create_date.day) day_items = monthly_items.get(day, []) day_items.append(item) this works great, and I get the dictionary structure that I want, but my problem is that if there are no items purchased on April 24th, there will be no key in the dictionary, and when I print my dict to … -
django-polymorphic-tree serializer
I would like to serialize all the nodes in my PolymorphicMPTTModel with their corresponding fields. Following the documentation django-polymorphic and django-mptt i get this: { "count":1, "next":null, "previous":null, "results":[ { "title":"Submenu", "subcategories":[ { "title":"Plato1", "subcategories":[ ] },enter code here { "title":"Plato2", "subcategories":[ ] } ] } ] } The structure is fine, but the fields of the children are missing. Models: class Menu(PolymorphicMPTTModel): parent = PolymorphicTreeForeignKey('self', blank=True, null=True, related_name='children', verbose_name='parent') title = models.CharField("Title", max_length=200) class SubMenu(Menu): titulo = models.CharField("Titulo", max_length=200,default="not defined") class Plato(Menu): titulo = models.CharField("Titulo",max_length=200,default="not defined") descripcion = models.TextField() ingredientes = JSONField() precio = models.PositiveSmallIntegerField(default=0) # Extra settings: can_have_children = False Serializers: class PlatoSerializer(serializers.ModelSerializer): class Meta: model = Plato fields = ('titulo', 'descripcion', 'ingredientes', 'precio') class SubMenuSerializer(serializers.ModelSerializer): class Meta: model = SubMenu fields = ('titulo',) class MenuItemModuleSerializer(serializers.ModelSerializer): subcategories = serializers.ListSerializer(source="children",child=RecursiveField()) class Meta: model = Menu fields = ('title','subcategories') View: class MenuView(viewsets.ModelViewSet): queryset = Menu.objects.all() queryset = queryset.toplevel() serializer_class = MenuItemModuleSerializer -
i am just wondering what could maximum recursion depth exceeded while calling a Python object error that is causing the running time error
the error comes on this line {% if user.is_authenticated %}can somebody help me . RuntimeError at / maximum recursion depth exceeded while calling a Python object Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11 Exception Type: RuntimeError Exception Value: maximum recursion depth exceeded while calling a Python object Exception Location: /usr/lib64/python2.7/site-packages/django/template/base.py in parse, line 515 Python Executable: /usr/bin/python Python Version: 2.7.13 Python Path: ['/home/harrugg2/projects/django/membersite', '/usr/lib/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] Server time: Thu, 27 Apr 2017 17:55:48 +0300 THIS MY base.html {% load staticfiles %} <html> <head> <title>member site</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <!-- Core CSS - Include with every page --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <link rel="stylesheet" href="{%static 'css/Footer.css' %}"> </head> <body> <nav class="navbar navbar-custom"> <!--div class="page-header"--> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Member site</a> </div> <form class="navbar-form navbar-left"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> {% if user.is_authenticated %} <div class="nav navbar-nav navbar-center"> <ul class="nav nav-pills" role="tablist"> <li role="presentation"><a href=class="glyphicon glyphicon-chat>Messages <span class="badge">3</span></a></li> </ul> </div> {% include "blog/includes/sidebar.html" %} … -
how to configure viewflow filter?
i have viewflow install on my local computer, but i don't have the filter like a demo online: http://demo.viewflow.io Follow the full tutorial on the quick start but Anyone know how to activate it? -
Django Allauth Error: NoReverseMatch at /accounts/facebook/login/token/
When trying to login using the fb js_sdk I receive the below error: Internal Server Error: /accounts/facebook/login/token/ NoReverseMatch at /accounts/facebook/login/token/ Reverse for '' with arguments '()' and keyword arguments '{'request': <WSGIRequest: POST '/accounts/facebook/login/token/'>}' not found. 0 pattern(s) tried: I'm sure it was working fine before I switched from oauth. Will switch back and test and update to see if it makes any difference settings.py INSTALLED_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'debug_toolbar', ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', '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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR + '/main/templates/allauth/',], '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', 'main.context_processors.get_search_query' ], }, }, ] AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) # ALLAUTH ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "optional" ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_SIGNUP_FORM_CLASS = 'main.forms.SignupForm' ACCOUNT_PRESERVE_USERNAME_CASING = True ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True ACCOUNT_SESSION_REMEMBER = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'js_sdk', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4', } } … -
Error with compiled Pillow on Python 3.6 virtualenv
I am running a linux box with ubuntu 14, it runs an apache2 server that hosts a Django application. This application imports PIL from the installed Pillow library. It was all working fine when I was on Python 3.5, however after upgrading to Python 3.6 and reinstalling Pillow in the Virtualenv, I get an error when the webserver tries importing PIL. When I run the Python interpreter it all imports fine as it uses the py script directly however as the webserver is using the installed and compiled pillow library it is failing. The error from Django shows the stack as such: Internal Server Error: /ticket-printing/ Traceback (most recent call last): File "/home/ubuntu/ipos-venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/ubuntu/ipos-venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/ubuntu/ipos-venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/ipos-venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/ipos/tickets/views.py", line 30, in stic_app PrintList.initiateSticApp(request) File "/home/ubuntu/ipos/tickets/models.py", line 434, in initiateSticApp BrandLogo.createBlankLogo() File "/home/ubuntu/ipos/store_admin/brands/models.py", line 108, in createBlankLogo from PIL import Image File "/home/ubuntu/ipos-venv/lib/python3.6/site-packages/Pillow-4.1.0-py3.6-linux-x86_64.egg/PIL/Image.py", line 56, in <module> from . import _imaging as core File "/home/ubuntu/ipos-venv/lib/python3.6/site-packages/Pillow-4.1.0-py3.6-linux-x86_64.egg/PIL/_imaging.py", line 7, in <module> __bootstrap__() File "/home/ubuntu/ipos-venv/lib/python3.6/site-packages/Pillow-4.1.0-py3.6-linux-x86_64.egg/PIL/_imaging.py", line 6, in __bootstrap__ imp.load_dynamic(__name__,__file__) … -
BackboneJS renders a forbidden page
In my Website I use Django (1.8) for Backend and BackboneJS for front end. I have a View that requires Permission, otherwise it throws 403 exception like this: url(r'^mymodel/create/$', view=views.MyModelCreateView.as_view()), and from django.views.generic import TemplateView from braces import views class MyModelCreateView(views.LoginRequiredMixin, views.PermissionRequiredMixin, TemplateView): permission_required = "core.add_mymodel" template_name = 'pages/base.html' raise_exception = True Where "base.html" is the base template. I am using a custom 403 page that extends the "base.html" inside base.html there is a container <div class="container viewcontainer"> which will hold all the backbone views rendred. and the BackBone router is like this: this.$content = $('.viewcontainer'); and routes: { "": "home", "mymodel/create/": "createMymodel", }, createMymodel: function () { var createMymodelView = new CreateMymodelView({ me: this.profile }); this.$content.html(createMymodelView.el) }, The problem is somehow weired: When I log in with a user that has "core.add_mymodel" permission, everything is working perfectly. But when I log in with a user that doesn't have "core.add_mymodel" permission, the Django View will respond by 403 Forbidden ruturned in the 403.html template which extends the "base.html" template; and SINCE THE "base.html" TEMPLATE CONTAINS <div class="container viewcontainer"> THE BACKBONE VIEW WILL RENDER THE CONTENT OF THE PAGE BY THE MYMODEL CREATION FORM ! SO WHAT YOU SEE IN THE … -
How to implement personal chats as well as group chats in django?
so far i have tried all the packages listed here either they are outdated or doesnt work like DJANGO-PRIVATE-CHAT any ideas how to do it ? I can use any python version so that is not a problem only problem is the django version. -
Where to put apps in Django?
Django documentation version 1.11 states: Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app right next to your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite. Does this means that this is the recommended location for apps? Why is it that this is being recommended in the first place? What is the advantage of having the apps available to be imported as its own top-level module rather than a submodule of mysite? -
Run unit tests without generating assets when using django-webpack-loader
I'm working on a Django project with some amount of front-end JavaScript code. I'm in the process of migrating the JavaScript packaging and minification from djanog-pipeline to webpack with django-webpack-loader. django-webpack-loader works by running webpack separate from any Django processes to generate packed bundles. django-webpack-loader will then read a JSON file written by webpack-bundle-tracker and use the information to insert the correct paths into HTML templates. This works flawlessly but there is one catch: Some of our unit tests will access the Django application using the integrated Django test client, which renders full HTML responses so that tests can inspect the generated result. Test may be run without any webpack-related setup having been done. So the packed bundles and JSON file may not exist. These are not necessary for the purpose of testing the frontend code, only the dynamically generated HTML is inspected. Having test fail just because someone forgot to run webpack leads to frustration. Ideally, I would have django-webpack-loader just use dummy URLs in the inserted <script> tags while running tests, removing the dependency on files generated by webpack. What options do I have to resolve this dependency? -
can't get sql server to work with django azure web app
I've tried for 3 days now and can't get this to work. I am following this tutorial from microsoft docs: https://docs.microsoft.com/en-us/azure/app-service-web/web-sites-python-create-deploy-django-app The app works fine with sql lite, but when I change it to the sql server, it stops working with the following error: django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: No module named 'sql_server' 2017-04-27 04:34:34.525084: wfastcgi.py 2.1.1 closed The app works for me locally by connecting to the same remote sql azure db, so the problem is definitely azure. I got the same error locally till I installed pyodbc-azure (https://github.com/michiya/django-pyodbc-azure). As suggested by Microsoft docs, and the library docs, the following is my Database connection specification in settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'django-myorg', 'USER': 'riz', 'PASSWORD': '#######', 'HOST': 'django-myorg.database.windows.net', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, } This is my third try setting this up, and I am frustrated by the lack of up-to-date documentation on Microsoft's part. I have tried troubleshooting where I could by following this guide: https://docs.microsoft.com/en-us/azure/app-service-web/web-sites-python-configure. I've tried building wheels for all the required libraries, but still having the same … -
Django django-location-field missing API Keys
I am using the https://github.com/caioariede/django-location-field library to build a Location View using Django. The issue is that I can't find a documentation saying how to define my own Google Maps API KEY. This is the code I have on my settings.py: LOCATION_FIELD_PATH = STATIC_URL + 'location_field' LOCATION_FIELD = { 'map.provider': 'google', 'map.zoom': 13, 'search.provider': 'google', 'search.suffix': '', # Google 'provider.google.api': '//maps.google.com/maps/api/js', 'provider.google.api_key': 'MY_API_KEY_HERE', 'provider.google.map_type': 'ROADMAP', # misc 'resources.root_path': LOCATION_FIELD_PATH, 'resources.media': { 'js': [ LOCATION_FIELD_PATH + '/js/jquery.livequery.js', LOCATION_FIELD_PATH + '/js/form.js', ], }, } But this solution dose not seem to work. maps.google.com/maps-api-v3/api/js/28/11/util.js:219 Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys I have been searching for a while now, but no luck in getting the answer.