Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unapply migration
I have a custom made migration: class Migration(migrations.Migration): dependencies = [('blah', 'my_previous_migration'),] operations = [ migrations.RunSQL( sql=[("SQL HERE")], reverse_sql=[("SQL UNDO HERE")]) ] This migration is already applied. I want to create a migration to undo that migration, basically following what the docs say: unapply migration But I can't find any reference on how to unapply a migration or have a migration run the reverse_sql portion of the migration. -
Save Datetime in variable to reflect in HTML Django/python
I need to know how to save the date when a function was triggered. My function triggers a logic to create a report with calculations and new data every hour. My idea was to create a function that save the date this way: def last_modify(request): x = [] last_mod = str(datetime.now().strftime("%d/%m %H:%M")) context = { 'date': last_mod } x.append(context) render(request, 'news-dashboard.html', context) Not sure if I'm on the right path, and if I have to reflect it in the html template Last date modified: {{ date }} this is for the users to know when was the report last updated. Thanks for your time. -
Django 1.9 get kwargs in class based view
I was wondering if there is a way to get the kwargs directly in a class based view. I know this can be done in functions inside the class, but I'm having problems when I try this: views.py class EmployeesUpdateStudies(UpdateView): form_class = form_ES model = EmployeePersonal template_name = 'employeesControll/employees_studies_update_form.html' success_url = reverse('employee-details', kwargs={'pk': kwargs.get('pk')}) My url is the following url(r'^employees/detalles/(?P<pk>[0-9]+)/$', login_required(views.EmployeeDetails.as_view()), name='employee-details') -
Python/Django explain code
Sometimes I meet in the code of Django user.save(using=self._db), _db what it mean? Explain please -
Django - Is there a remote image field
I was wondering if there is a field (A model field) that represents a remote image. What I need is to add an image field to my model that isn't stored locally, but is given a remote URL and can only be viewed, not edited or uploaded. Thanks in advance! -
Handling Uploaded Files in Django
I am getting a file from user which is of xlsx or csv format . I am saving the data of the files into my Database using "django-excel". But after i perform "request.FILES['file'].save_to_database()" then if i try to access the uploaded file's contents using request.FILES['file'] again then I am unable to access them . How can I resolve this problem ? -
gunicorn failed to start worker process while working withDjango app
Good Afternoon, I am developing a Django App and trying to develop it using gunicorn and nginx as web server loadbalancer for http. when trying to start gunicorn from within an venv (the app is being developed within a venv )using ../bin/gunicorn biblio_cfv.wsgi: application I get these errors [2016-10-14 16:37:13 -0400] [22618] [INFO] Starting gunicorn 19.6.0 [2016-10-14 16:37:13 -0400] [22618] [INFO] Listening at: http://127.0.0.1:8000 (22618) [2016-10-14 16:37:13 -0400] [22618] [INFO] Using worker: sync [2016-10-14 16:37:13 -0400] [22621] [INFO] Booting worker with pid: 22621 [2016-10-14 20:37:22 +0000] [22621] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/eddyraz/proyectos/www/VPS_WEB_DEVEL/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/home/eddyraz/proyectos/www/VPS_WEB_DEVEL/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/home/eddyraz/proyectos/www/VPS_WEB_DEVEL/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/home/eddyraz/proyectos/www/VPS_WEB_DEVEL/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/eddyraz/proyectos/www/VPS_WEB_DEVEL/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/home/eddyraz/proyectos/www/VPS_WEB_DEVEL/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/home/eddyraz/proyectos/www/VPS_WEB_DEVEL/lib/python3.5/site-packages/gunicorn/util.py", line 368, in import_app app = eval(obj, mod.__dict__) File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing I checked the file util.py withon gunicorn code and found nothin wrong here is the function of the code that gives the error. def import_app(module): parts = module.split(":", 1) if len(parts) == 1: module, obj β¦ -
How to load angular2 files to Django template?
I have app structure like this: βββ project | |ββ templates β β βββ index.html β βββ __init__.py β βββ models.py β βββ urls.py β βββ serializers.py β βββ views.py βββ static | βββ app | β βββ app.component.spec.ts | β βββ app.component.ts | β βββ app.route.ts β β βββ component1.component.ts | β βββ component2.component.ts β β βββ main.ts | βββ system.config.json β βββ tsconfig.json β βββ typings.json βββ db.sqlite3 βββ LICENSE βββ manage.py and I'm trying to load angular2 files into my django template index.html, so the file looks like this: {% load static from staticfiles %} <!DOCTYPE html> <html> <head> <base href=/ > <title>Hello! </title> <meta charset=UTF-8> <meta name=viewport content="width=device-width,initial-scale=1"> <script src="https://unpkg.com/core-js/client/shim.min.js"></script> <script src="https://unpkg.com/zone.js@0.6.25?main=browser"></script> <script src="https://unpkg.com/reflect-metadata@0.1.3"></script> <script src="https://unpkg.com/systemjs@0.19.27/dist/system.src.js"></script> <script> System.import('{%static '/app/main' %}').catch(function(err){ console.error(err); }); </script> <link href="{%static '/css/stylesheet.css' %}"> <link href="{%static '/css/bootstrap.min.css' %}"> </head> <body> <img src="{%static '/assets/logo.png' %}"></img> <as-my-app>Loading...</as-my-app> </body> </html> My problem is that all the static files load just fine, but my browser constantly shows error while loading /static/app/main saying it wasn't found. How come Django can't find it if it finds other static files? -
Django: Passing a csrf token through ajax to an UpdateView 405 method not found error
I am creating an FAQ app. In my article detail page I am attempting to implement a vote up system. The goal is to allow a user to vote up an article if they find it useful. I do not want the page to be refreshed when the user clicks the vote up button. I have chosen to use an Ajax call from the template along a url to an UpdateView. Django needs a csrf token to be passed along. The problem I am encountering is a 405 (Method Not Allowed) error. I have verified in my network setting in chrome dev that the csrf token is being generated and assigned in the http header. I think the issue may lay in the view but everything I have tried so far has come up short. Any direction would be helpful. The Url: url(r'^ironfaq/article/vote/(?P<pk>\d+)$', ArticleVoteView.as_view()), The Template Script: {% block scripts %} <script> $(document).ready(function(){ var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); function post_call(vote_data){ var data = new FormData(); var id = {{ object.id }}; β¦ -
packaging django application and deploying it locally
I've never worked with Django before so forgive me if a question sounds stupid. I need to develop a web application, but I do not want to deploy it on a server. I need to package it, so that others would "install" it on their machine and run it. Why I want to do it this way? There are many reasons, which I don't want to go into right now. My question is: can I do it? If yes, then how? -
How to handle generator code inside a decorator?
I'm attempting to write a login_required decorator for authenticating requests to a protected view in Django using a WSGI middleware. Here's my code: def login_required(f, request_class=HTTPRequest): def _wrapper(*args, **kwargs): if not isinstance(args[0], request_class): req = request_class(environ=args[0]) else: req = args[0] wsgi_app = WSGIController() settings = wsgi_app.settings google_client = client.GoogleClient( settings.OAUTH2_CLIENT_ID, access_token=settings.OAUTH2_ACCESS_TOKEN, scope='email', redirect_url=settings.OAUTH2_REDIRECT_URL, login_path="/session_login/") wsgi_app = google_client.wsgi_middleware(wsgi_app, \ secret=settings.SECRET_KEY) def process_middleware(environ, start_response): return wsgi_app(environ, start_response) response = process_middleware(req.environ, f) return f(*args, **kwargs) return _wrapper How can I handle the response object (generator) to redirect the user to the oauth login page ? -
Are there significant performance differences in Django versions
I'm thinking of implications on speed--like are there substantial improvements on the ORM that would drastically increase a user experience? What versions denote these major improvements? -
Django: Access foreign key image in template
I have the following models: class Car(models.Model): # some fields class CarPhotos(models.Model): image = models.ImageField(upload_to='somewhere') car = models.ForeignKey(Car) in views.py: def car_list(request): cars = Car.objects.all() return render(request, 'borsa/car_list.html', {'cars': cars}) in car_list.html: {% for car in cars %} <a href="car/{{ car.pk }}/view/"> <img class="media-object tmbpic" src="{{ car.carphotos_set.all.0.image.url }}" alt="kola"> </a> The first method i've used was to use inline formsets but I had no clue how to access the images. Can you please point me in the right direction of how to access images according to Car objects ? I mean every Car must have a couple of images and I need to display only the first one in list view, but then I need to display all of them in Detail view. Thanks in advance. -
Django template tag to convert epoch time to human readable time
Is there a Django template that converts epoch time to 'human readable' time (same as naturaltime from Humanize)? I've tried a custom template tag that returns datetime.fromtimestamp(value) - but this shows timestamps as Month Date Year Time am/pm. I tried another one that returns '%(time)s ago' % {'time': timesince(value).split(', ')[0]} (using timesince), but timesince doesn't seem to allow epoch time as an argument. -
django: multiple db and contenttype
I am creating a Django project with one app called 'db_manager'. I would like to create two db: one for the db_manager models, and one for the core django models (auth, admin, contentTypes, session...) First, I run the migrations to create the core models in the adw_core db. Then, I run the migrations to create the db_manager models in the adw_facts db. I use this command: python manage.py migrate db_manager --database adw_facts I have a router set up that directs app to the appropriate db: settings.py DATABASE_ROUTERS = ['data_warehouse.db_routers.DatabaseRouter'] MAP_APPS_TO_DB = { 'db_manager': 'adw_facts', 'django.contrib.auth': 'adw_core', 'django.contrib.sessions': 'adw_core', } db_routers.py class DatabaseRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label in settings.MAP_APPS_TO_DB: return settings.MAP_APPS_TO_DB[model._meta.app_label] return None def db_for_write(self, model, **hints): if model._meta.app_label in settings.MAP_APPS_TO_DB: return settings.MAP_APPS_TO_DB[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **hints): # Allow any relation between apps that use the same database. db_obj1 = settings.MAP_APPS_TO_DB.get(obj1._meta.app_label) db_obj2 = settings.MAP_APPS_TO_DB.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in settings.MAP_APPS_TO_DB: return db == settings.MAP_APPS_TO_DB[app_label] return None When I run the migrations to create the db_manager models in the adw_facts db, I get the following error: RuntimeError: Error β¦ -
python django iam stack in this part of code shown below .error displayed un IndentationError: unindent does not match any outer indentation level
from __future__ import unicode_literals from django.db import models # Create your simplesite models here. class simplesite(models.Model): name=models.CharField(max_length=100) due_date=models.DateTimeField() #simplest app model class simplest(models.Model): simple_site=models.foreignkey(simplesite) name=models.CharField(max_length=100) due_date=models.DateTimeField() this is the error displayed when i run this command this the command python .\manage.py makemigrations simplest this is the error PS C:\django\simplesite> python .\manage.py makemigrations simplest Traceback (most recent call last): File ".\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Python27\lib\site-packages\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python27\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\django\simplesite\simplest\models.py", line 9 due_date=models.DateTimeField() ^ IndentationError: unindent does not match any outer indentation level any please help i am stack on that place .i am a beginner in python django framework -
Extending the page With menus
I create a new field for page extending the page, I follow the documentation for that. So now each page have a image. In my case I show the submenu in my template using this {% show_menu 2 100 100 100 "partials/menu_image.html" %} so in my menu_image.html I show my menu like this <ul> {% for child in children %} <li> <div class="project_item"> <a href="{{ child.get_absolute_url }}"> {% if request.current_page %} <img src="{% static request.current_page.iconextension.image.url %}"> {% endif %} <div class="title_project">{{ child.get_menu_title }}</div> <div class="description_project"> {{ request.current_page.PageDescriptionExtension.description_page }} </div> </a> </div> </li> {% endfor %} </ul> My problem here is that I want to show the image of each page here in the menu, for that I have to create a cms_menus.py so I have this from menus.base import Modifier from menus.menu_pool import menu_pool from cms.models import Page class MyMode(Modifier): """ """ def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): # if the menu is not yet cut, don't do anything if post_cut: return nodes # otherwise loop over the nodes for node in nodes: # does this node represent a Page? if node.attr["is_page"]: # if so, put its changed_by attribute on the node node.attr["changed_by"] = Page.objects.get(id=node.id).changed_by return nodes menu_pool.register_modifier(MyMode) β¦ -
Getting abstract class static field value
In my models I created an abstract base class to store information about last database modification. To do that I override save method where a static datetime field is updated with current time. When I try to retrieve last modification time, a DeferredAttribute object is returned and the only way to fetch that value I have found yet is by calling that field from an instantiated object. However, in this way I won't be able to read the value if all objects in the database are deleted. class Timestamp(models.Model): modified = models.DateTimeField(null=True) def save(self, *args, **kwargs): Timestamp.modified = timezone.now() super(Timestamp, self).save(*args, **kwargs) class Meta: abstract = True class Node(Timestamp): latitude = models.FloatField(default=0.0) longitude = models.FloatField(default=0.0) # ... # few more subclasses of Timestamp Is there a way to get modified field value without having a derived class object? -
Django hide field when creating new object
I want to hide field name when user is creating new object, but it must be visible if user wants to edit this object. I tried exclude method but it makes field invisible when i try to edit this field. -
How to accomodate APIView & ViewSet views in urls.py
How would one write a urls.py file to accomodate views created from APIView and ViewSet. entity.views.py from .models import Entity from .serializers import EntitySerializer class EntityViewSet(DefaultsMixin, ListCreateRetrieveUpdateViewSet): """ """ queryset = Entity.objects.all() serializer_class = EntitySerializer filter_fields = ('id', 'entity_number') class PersonProfileList(APIView): """ person profile """ def get(self, request, format=None): pass entity.urls.py from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework.urlpatterns import format_suffix_patterns from . import views entity_router = DefaultRouter() entity_router.register(r'entity', views.EntityViewSet) urlpatterns = [ url(r'profile/$', views.PersonProfileList.as_view(), name='profile_list'), # Is this correct? url(r'profile/(?P<pk>[0-9]+)/$', views.PersonProfileList.as_view(), name='profile_detail'), ] urlpatterns = format_suffix_patterns(urlpatterns) main urls.py from django.conf.urls import include, url from django.contrib import admin from entities.urls import entity_router, urlpatterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^entities/', include(entity_router.urls)), #This I know works url(r'^entities/', include(urlpatterns.url)), # This throws errors ] What is the best way to accomodate both types of Views in the same URL file and have them appear under one /entity unlike now when am getting two /entity entries. Also, once I get into the /entity page in the browsable API, how do I make the /entity/profile viewable since now it only shows /entity. See images for guide. Root Page Entities Page -
manage.py on DJANGO(production server)
I'm actually working on a Django project, I have remote access to the server directly, it's a production environment, but I try to execute any command with manage.py and it doesn't work, and I actually can't find the manage.py file, is it possible not having a manage.py even though it's a production environment? If it is, how can I include it from now on? I need it specially for migration, so if it can't be included is there some other way for migration (not South since I still need manage.py to make it functional) -
View not found for views with number at the end
I'm trying to do a reverse like this: print reverse("shows-view") This is in my urls.py: url(r'^shows/(\d+)$', views.show_details, name="shows-view"), Whenever I try to do that, it just returns: Reverse for 'shows-view' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['shows/(\\d+)$'] But if I try to access the page directly (http://localhost/shows/3333) then it works fine But if I do a reverse for other views like this: print reverse("shows-default-view") with the following declaration in the same urls.py file: url(r'^shows/', views.popular, name="shows-default-view"), then it works fine. Does anyone have any idea why? -
django-auth-ldap not working by the login interface
I'm trying to use Django-Auth_Ldap in my project but it is not working. My active Directory shema is: I've tested the connection on the cmd line by installing the ldap-utils package $ sudo apt-get install ldap-utils $ ldapsearch -H ldap://domain.com -D "ou=Resources,ou=Company, dc=domain,dc=com" -U "user_name" -w "user_password" -v -d 1 The connection test work fine. I am using below code to test python-ldap connection from the shell: import ldap con = ldap.initialize('ldap://domain.com') con.simple_bind_s('User_mail', 'User_password') results = con.search_s('ou=Users,ou=Resources,ou=Company,dc=domain,dc=com', ldap.SCOPE_SUBTREE, "(cn=User_name)") results python-ldap connection works fine. My problem is to connect with AD user from django login interface. settings.py: import ldap from django_auth_ldap.config import LDAPSearch # The URL of the LDAP server. AUTH_LDAP_SERVER_URI = "ldap://domain.com" AUTH_LDAP_BIND_DN = "cn='User_name',ou=Resources,ou=Company,dc=domain,dc=com" AUTH_LDAP_BIND_PASSWORD = "User_password" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=Users,ou=Resources,ou=Company,dc=domain,dc=com",ldap.SCOPE_SUBTREE, "(cn=%(user)s)") AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_REFERRALS : False } AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) views.py: from django_auth_ldap.backend import LDAPBackend auth = LDAPBackend() user = auth.authenticate(username="User_name", password="User_password") In the file django-ldap-debug.log: Ihave this error: Caught LDAPError while authenticating User_name: INVALID_CREDENTIALS({'info': '80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1', 'desc': 'Invalid credentials'},) How can I connect to my django application with AD users ? -
In Django, how can I set a modelfield from my view?
I have a model form page that works great currently. When the user uploads a file, i'm sending it through my file upload handler, and getting back JSON data. I would like to set my model field with the data returned. view.py. @login_required def STLupload(request): # Handle file upload if request.method == 'POST': formA = ObjectUp(request.POST, request.FILES) formB = FileUp(request.POST, request.FILES) a_valid = formA.is_valid() b_valid = formB.is_valid() if a_valid and b_valid: try: data = handle_uploaded_file(request.FILES['STL']) except: print ("didn't work") if data['response'] == "non-manifold": print ('u crazy dawg') else: #Maybe right here???? #formB.Ydim_mm = str(data['Ymm']) #formB.Zdim_mm = str(data['Zmm']) #Save current username comment = formA.save(commit=False) comment.user = request.user a = comment.save() b = formB.save(commit=False) b.objectid = comment b.valid = True #Maybe here? #b.Xdim_mm = str(data['Xmm']) b.save() #Flash success message messages.add_message(request, messages.SUCCESS, "File uploaded successful") # Redirect to the document list after POST return HttpResponseRedirect(reverse_lazy('STLup')) else: formA = ObjectUp() # A empty, unbound form formB = FileUp() and my models.py is below. class subfiles(models.Model): STL = models.FileField(_('STL Upload'), upload_to=user_directory_path_files, validators=[validate_file_extension]) Photo = models.ImageField(_('Photo'), upload_to=user_directory_path_files, validators=[validate_img_extension]) FileTitle = models.CharField(_('Title of file'), max_length=40, blank=True, null=True, unique=True) Xdim_mm = models.IntegerField(_('X dimension (mm)'), default=0) Ydim_mm = models.IntegerField(_('Y dimension (mm)'), default=0) Zdim_mm = models.IntegerField(_('Z dimension (mm)'), default=0) objectid β¦ -
django urlpattern wrong? need to accept 2 different parameters
I'm working on building a django app for a small little game I'm building to integrate it. Instead of re-writing my app to use django's membership system I've added my small little game login system to the django site. My issue is with my ChangePassword url pattern. url(r'^ChangePassword/(?P<userID>[0-9]+)/(?P<token>/?$)', changepassword, name='Change Password'), I get the following error in the terminal while trying to go to the page. Not Found: /members/ChangePassword/11/aw7MdMn4DaFoPp6W4P+c4IZWXRAF9g== [14/Oct/2016 16:53:53] "GET /members/ChangePassword/11/aw7MdMn4DaFoPp6W4P+c4IZWXRAF9g== HTTP/1.1" 404 3294 Am I missing a regex or do I have the pattern wrong? I've been going through user docs and question on here and found a solution yet. It needs to accept the userID and a special token so we know that we can reset/change the password.