Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files not being served on Django
I am trying to serve static files in Django in development (DEBUG=True) mode. I have a directory structure like this: my_project/ ... static/ img.png In my settings.py I have this: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILE_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) and in my_project/urls.py I have this: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ # ... url(r'^admin/', include(admin.site.urls)), url(r'^', include('app.landing.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This all seems to be correct. When I visit http://127.0.0.1:8000/static/img.png though, I get a 404. What am I doing wrong? -
django included URLs with positional arguments
In URL patterns, I'd like to capture a positional argument in a common prefix and pass it to included URLs, like so: apis = [ url(r'^data/(\d+)$', view, name='some.view'), ... ] urlpatterns = [ url(r'^(\d+)/api/', include(apis)), ... ] The Django documentation seems to imply that this will work, but the view only receives one argument instead of the expected two in the above example. What's wrong here? -
how to pass realtime form arguments to a python script called by a django app
my django app calls a python cgi script: def query(request): if request.method == 'GET': output = subprocess.check_output(['python', 'query.cgi']).decode('utf-8') return HttpResponse(output, content_type="text/html") The query.cgi will be called by a form. How do I pass form args like "name=one&type=two" to the cgi. When I do subprocess.check_output(['python', 'query.cgi', 'name=one', 'type=two']). It works, but how do I pass the realtime online form input to cgi? Thanks a lot! -
django facebook and user password authentication
i am new in django, i require login with user and password or facebook, i am using rest framework for api endpoints. ¿How i can do it? i try with: django-rest-framework-social-oauth2 but don't work for my because i needs save additional info from user after first enter. I expect have 2 endpoint one sending user and password and another sending facebook auth token -
Django - Understanding RelatedManager remove method
So here I will be using classic Django Blog and Entry models from the documentation (link). I added null=True to the Entry's blog attribute. >>> cb = Blog.objects.get(name__startswith="Cheese") >>> gauda = Entry.objects.get(headline__startswith="Gauda") >>> cb.entry_set.all() [<Entry: Gauda>, <Entry: Emmentaler>] >>> cb.entry_set.remove(gauda) >>> gauda.blog <Blog: Cheese blog> I know that everything is fine and updated in database and if I query the second line from my example again that gauda.blog is gonna return None, but my question is why is gauda.blog not None without another query? -
How do I override Django's default admin templates and layouts
I am trying to override Django's default template. For now just the base_site.html. I'm trying to change the text django administration. I did the following: I created a folder in my app directory /opt/mydjangoapp/templates/admin I then copied the original django admin templates folder contents into admin and here are the contents: 404.html auth change_list.html delete_selected_confirmation.html index.html pagination.html search_form.html 500.html base.html change_list_results.html edit_inline invalid_setup.html popup_response.html submit_line.html actions.html base_site.html date_hierarchy.html filter.html login.html prepopulated_fields_js.html app_index.html change_form.html delete_confirmation.html includes object_history.html related_widget_wrapper.html I changed the contents of base_site, so that I have the title My App Admin as opposed to Django Administration I edited settings and set TEMPLATES as follows: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/opt/mydjangoapp/templates/'], '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', ], 'debug':True, 'loaders': ('django.template.loaders.filesystem.Loader','django.template.loaders.app_directories.Loader'), }, }, ] But unfortunately, Django version 1.8 seems to be ignoring my template changes and loading the original template files. Any suggestions as to how I can override the original layout for the admin. Bare in mind changing the title is just the beginning of the changes that I want to perform? -
Why can't I disable Django's Admin Console?
In my Django application, I was using the built-in admin console to help during development. I now want to disable this admin console. So I simply went to settings.py and removed django.contrib.admin from INSTALLED_APPS. I figured that should be all that's needed. However, when I do that, and re-start the server, I get the following error: File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 173, in check_dependencies "Put 'django.contrib.admin' in your INSTALLED_APPS " ImproperlyConfigured: Put 'django.contrib.admin' in your INSTALLED_APPS setting in order to use the admin application. How can I switch off the Django admin console properly? -
django calling a python script shows the html code instead of a webpage
my django app calls a python script(query.cgi). but when I run it, the website shows the html printout from that script instead of showing the output as a webpage. def query(request): if request.method == 'GET': output = subprocess.check_output(['python', 'query.cgi']).decode('utf-8') return HttpResponse(output, content_type="text/plain") The webpage shows: Content-Type: text/html <!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link type="text/css" rel="stylesheet" href="css/css_4.css" media="screen" /> <title>....</title> </head><body>.....</body></html> Thanks for any help!! -
Django migrations gives error when run separately in different machines
We are a team of developers working on Django project. We are facing issues with django migrations. if one developer makes changes in model and runs makemigrations>migrate sequence it generates some sqls in migrations directory. Now when other developer pulls the code, and run the same sequence it's putting code in bad state. We've been clearing our migrations directory locally to get rid of the issue, and sometimes clear all the data. Not sure what we're doing incorrectly. Please suggest the right way of using django migrations. Note - All of us use separate instances of DB in local machine. -
Serving secret API keys on page load
What are some best practices for serving API keys to the client provided that my keys exist in my production server's environment variables? Upon page load, assuming user has already been authenticated and is authorized, when and how do I send over an API key to the client? I have a Mapbox component and my plan was to fetch the single key I'd need from a RESTful endpoint. If authorized, I get the key back and my Mapbox tiles would load properly. Is this best practice? If I have other components in the future requiring different keys, do I keep that same API endpoint and just serve a bunch of keys once authenticated? I have a simple Django app connected to a GraphQL API but I welcome technology-agnostic approaches to this problem as well because I've found it difficult to find a simple answer online. -
Django Raw query usage
I am struggling to use the output of a raw query. My code is as follows: cursor.execute("select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2") currentSelectedTeams = cursor.fetchone() if not currentSelectedTeams: currentSelectedTeam1 = 0 currentSelectedTeam2 = 0 else: currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid currentSelectedTeam2 = currentSelectedTeams[1].teamselectionid I get the following error: currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid AttributeError: 'long' object has no attribute 'teamselectionid' Any help would be appreciated, many thanks in advance, Alan. PS In case it helps the result of my query in MySQL is as follows: mysql> select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2; +-----------------+-------------------+-----------------+---------+ | fixturematchday | teamselection1or2 | teamselectionid | user_id | +-----------------+-------------------+-----------------+---------+ | 6 | 1 | 31 | 349 | | 6 | 2 | 21 | 349 | +-----------------+-------------------+-----------------+---------+ 2 rows in set (0.00 sec) -
STATIC_ROOT doesn't find my static files
I'm newbie in Django and I'm trying to find a way to load my css files in my project. Here is my settings.py file STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", #"django.contrib.staticfiles.finders.AppDirectoriesFinder" ) AUTHENTICATION_BACKENDS = ( # Uncomment the following to make Django tests pass: 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) I got a way to do it using the variable STATICFILES_DIRS, but it won't work together with the others similars variables. What should I do to fix it? EXTRA INFORMATIONS: My base.html file static files call: <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'icomoon_style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}" /> My folders disposal: OntoLogica (main folder) Ontologica (project folder) static folder icomoon_style.css style.css css folder bootstrap.min.css -
Run telegram bot as inside Django app
I have simple django-app and want to run a simple telegram bot that sends data from database/models to the chat on demand (using python-telegram-bot library). I know, that it's better to run it as standalone process, and that Django is not suited for that. But I want my bot to use Django model classes in order to obtain high-level access to data. The question is: how can I do it? I've tried to run it in standalone thread from wsgi.py, but got the following exception: Exception in thread Telegram-statbot-thread: Traceback (most recent call last): File "C:\Python3\lib\threading.py", line 914, in _bootstrap_inner self.run() File "C:\Work\Projects\Python\myapp\myapp\statbot\bot.py", line 49, in run init() File "C:\Work\Projects\Python\myapp\myapp\statbot\bot.py", line 26, in init updater.idle() File "C:\Python3\lib\site-packages\telegram\ext\updater.py", line 414, in idle signal(sig, self.signal_handler) File "C:\Python3\lib\signal.py", line 47, in signal handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler)) ValueError: signal only works in main thread -
How would I write the regex for this Django URL?
I'm trying to write a URLconf for a view that gets triggered by a button on my Django admin page. I should be able to select a record, click the export button, and it will trigger the view to do logic to the selected record. I tried writing it this way in my urls.py, def get_urls(self): urls = super(AttorneyAdmin, self).get_urls() my_urls = url(r"^/export/$", write_to_excel(), name='export/') return my_urls + urls urlpatterns = [ url(r'^admin/', admin.site.urls, name='admin'), url(r'^advanced_filters/', include('advanced_filters.urls')) ] Here is the error I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8300/export/?export=Export&csrfmiddlewaretoken=VUpNlfBD3eUFWB1WTq46ChdQRIQJj7GN&action=&select_across=0&_selected_action=DEF3 Using the URLconf defined in emarshal.urls, Django tried these URL patterns, in this order: ^admin/ ^advanced_filters/ ^uploads/(?P.*)$ The current URL, export/, didn't match any of these. How do I write the regex to account for this URL? -
Heroku using pip rather than pip3 in deployment
I'm having an issue with deployment for a simple Django application to Heroku. I have python 3.5.2 specified in runtime.txt so upon deployment to Heroku, it uses python 3.5.2. When I push to my Heroku repository though, Heroku will try pip installing my dependencies and rather than using pip3. I know there is a duplicate post out there, but I didn't find that answer sufficient. If anyone has had a similar problem, any advice would be great! -
Django-Rest get URL of related children list
I got a simple model related to django contrib auth User model. I'd like to have a CRUD for Company, but with related elements set as an url of a list rather then a list of elements (i.e. a link to employees list rather than list of urls of single employee). What's missing here? models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Company(models.Model): name = models.CharField(max_lenght=256) employees = models.ManyToManyField(User) serializers.py from rest_framework import serializers from django.contrib.auth import get_user_model User = get_user_model() from .models import Company class CompanySerializer(serializers.HyperlinkedModelSerializers): class Meta: model = Company fields = ('name', 'employees') class UserSerializer(serializers.ModelSerializers): class Meta: model = User fields = ('username', 'password', 'email') # and so on view.py from rest_framework import viewsets from django.contrib.auth import get_user_model User = get_user_model() from .models import Company from .serializers import UserSerializer, CompanySerializer class UserViewset(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() class CompanyViewset(viewsets.ModelViewSet): serializer_class = CompanySerializer queryset = Company.objects.all() urls.py from django conf.urls import url, include from rest_framework.routers import DefaultRouter from .views import CompanyViewSet, UserViewSet router = DefaultRouter() router.register(r'company', CompanyViewSet) router.register(r'users', UserViewSet) urlpatterns = [url(r^api/, include(router.urls))] -
Django: Where should I put queries about User which is in relation with other models
I am writing a Django app which define groups of user. A user can be part of many groups. I want to be able to retrieve, from a list of groups, users which are members of at least one of those groups and with no duplicate. So i wrote a query to accomplish that. That method will take a list of group_id and simply returns a list of users. My question is: where is the best place to put that method? I was thinking to create a custom manager for my Group model. But it don't seems logical as my method will return to me a list of Users. According to the doc: https://docs.djangoproject.com/en/1.8/topics/db/managers/ Manager of a model should contains queries about that model. After some research, I've seen that is not advised to extends the django.auth.models.User manager (at least in my case). For the moment, i will just put my method in a 'service.py' file, but I was wondering if there is not a more elegant way to accomplish what i am trying to do. Thanks by advance for your suggestions! -
Django: Need a way to restrict user to view media one after the other [after completing first video then second video has to enable otherwise not]
Requirement: I want to design a portal, where user can read/view media [eg: documents/ videos]. Let us suppose I have 10 documents which I will show in a web page. I want to make sure that user reads the first document then only second document will be available to read otherwise we have to disable the link. -
issue with create_user.py in django-cms
I just started using django-cms and am facing issues. I used virtualenv Traceback (most recent call last): File "create_user.py", line 4, in from django.contrib.auth import get_user_model File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/contrib/auth/init.py", line 7, in < module> from django.middleware.csrf import rotate_token File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/middleware/csrf.py", line 14, in from django.utils.cache import patch_vary_headers File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/utils/cache.py", line 26, in from django.core.cache import caches File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/core/cache/init.py", line 34, in if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/conf/init.py", line 48, in getattr self._setup(name) File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/conf/init.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Django return JSON with Logged in Cookie
I want to design a simple Django "RESTful" API without the need of using django-rest-framework. The endpoint is /api/login which accept only POST method with username and password in json. I want it to return {"status" : 0} for success with the session cookie to be used later at my other endpoints. Only when the user successfully logged in, the cookie will be set. I have imported the JsonResponse object from django.http but not very sure how to set the session for the user. def login(request): # some code omitted, like if request.method == "POST" credential = json.loads(request.body) username = credential['username'] password = credential['password'] user = authenticate(username=username, password=password) if user: if user.is_active: auth_login(request, user) else: return JsonResponse({"status" : 1, "err" : "Your account has been disabled"}) # TODO: Now return what? I have browsed the document but failed to find any useful tip. -
How to delete existing file when user uploads a new one
I've just successfully implemented a method similar to the one that Giles suggested for saving new images with a filename of the primary key of the model here: http://stackoverflow.com/a/16574947/5884437 Actual code used: class Asset(models.Model): asset_id = models.AutoField(primary_key=True) asset_image = models.ImageField(upload_to = 'images/temp', max_length=255, null=True, blank=True) def save( self, *args, **kwargs ): # Call save first, to create a primary key super( Asset, self ).save( *args, **kwargs ) asset_image = self.asset_image if asset_image: # Create new filename, using primary key and file extension oldfile = self.asset_image.name dot = oldfile.rfind( '.' ) newfile = 'images/' + str( self.pk ) + oldfile[dot:] # Create new file and remove old one if newfile != oldfile: self.asset_image.storage.delete( newfile ) self.asset_image.storage.save( newfile, asset_image ) self.asset_image.name = newfile self.asset_image.close() self.asset_image.storage.delete( oldfile ) # Save again to keep changes super( Asset, self ).save( *args, **kwargs ) def __str__(self): return self.asset_description e.g. User submits "MyPicture.jpg" on a blank 'new asset' form. Server first pre-saves the new asset to generate an (asset_id) primary key, then renames the file as [asset_id].[original_extension] (e.g. "26.jpg") and moves it to the correct folder. Unfortunately I've just found that this doesn't take into account files with different extensions, e.g. a user first uploads an image … -
How to maintain different country versions of same language in Django?
I would like to have a few different versions of the same language in Django, customized for different countries (e.g. locale/en, locale/en_CA, locale/en_US, etc.). If there is no language for specific country I would expect to use the default language version (locale/en)). Then in the settings file for each site I specify LANGUAGE_CODE and LANGUAGES. For some reason, even if I specify the following settings, the locale/en_US translations are still used: LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', ugettext('English')), ) Though I clearly specify that the language code should be en (not en-us). Am I missing something? Already tried to find the answer in multiple places, including Django documentation. -
Storing user permissions on rows of data
I have a table with rows of data for different experiments. experiment_id data_1 data_2 ------------- ------ ------- 1 2 3 4 .. I have a user database on django, and I would like to store permissions indicating which users can access which rows and then return only the rows the user is authorized for. What format should I use to store the permissions? Simply a table with a row for each user and a column for each experiment with Boolean? And in that case I would have to add a row to this table each time an experiment is added? user experiment_1 experiment_2 experiment_3 .. ---- ------------ ------------ ------------ -- user_1 True False False .. user_2 False True False .. .. Any reference literature on the topic would also be great, preferably related to sqlite3 functionality since that is my current db backend. -
How to handle concurrent modication in django?
I am trying to build a project(like e-commerce) with backend in django and integrate with android. (I am not building an website. I am trying mobile only. So I am using django-rest to create api) So my question is how to handle a case where two or more user can book an item at the same time when there is only a single item. (basically how to handle concurrent modification and access of data) ? Please help. I am stuck on this one. -
Kubernetes + MySQL : Creating custom database and user in a Kubernetes container
I am trying to create a Django + MySQL app using Google Container Engine and Kubernetes. Following the docs from official MySQL docker image and Kubernetes docs for creating MySQL container I have created the following replication controller apiVersion: v1 kind: ReplicationController metadata: labels: name: mysql name: mysql spec: replicas: 1 template: metadata: labels: name: mysql spec: containers: - image: mysql:5.6.33 name: mysql env: #Root password is compulsory - name: "MYSQL_ROOT_PASSWORD" value: "root_password" - name: "MYSQL_DATABASE" value: "custom_db" - name: "MYSQL_USER" value: "custom_user" - name: "MYSQL_PASSWORD" value: "custom_password" ports: - name: mysql containerPort: 3306 volumeMounts: # This name must match the volumes.name below. - name: mysql-persistent-storage mountPath: /var/lib/mysql volumes: - name: mysql-persistent-storage gcePersistentDisk: # This disk must already exist. pdName: mysql-disk fsType: ext4 According to the docs, passing the environment variables MYSQL_DATABASE. MYSQL_USER, MYSQL_PASSWORD, a new user will be created with that password and assigned rights to the newly created database. But this does not happen. When I SSH into that container, the ROOT password is set. But neither the user, nor the database is created. I have tested this by running locally and passing the same environment variables like this docker run -d --name some-mysql \ -e MYSQL_USER="custom_user" \ …