Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: separating group editing permission from custom group extension permission
I have extended the group model and added a custom field and permission. I want to be able to give a user permission to edit this new field, but not have permission to edit any of the other group attributes. But if I do not grant the 'can change group' permission they cannot get to the group admin screen to access this new field. Is there some way to give them access to only the new custom field? -
How do I prevent django from accessing a database during a test?
I'm trying to write a django health check for a cloud app to determine if the server is still healthy. One of the checks determines if the database is still accessible. And I want to test if this works, so I'm writing a django test script to verify this. Except django is really good at keeping a database connection. Things which haven't worked: Using override settings: @override_settings(DATABASES={}) def test_dead_database(self): Popping the default database settings: from django.conf import settings old_db_eng = settings.DATABASES.pop('default') But Django keeps the database alive! How can I force the django database to go away within a test? -
Is it possible to use Django with an Access Database?
Is it possible to use an access database (.accdb) as the back-end for a Django application? -
Trouble Implementing Webpack for a Large Project
I have been struggling trying to find the best way to implement webpack into the frontend workflow of a large existing Django project. My two main concerns are: The bundled file that webpack outputs pollutes the global namespace, possibly creating naming conflicts between existing client-side scripts. The bundled file will be extremely large payload that would take too long to load. Generally the project is broken into apps. It might make more sense to have a bundled file specific to each app. Open to any other ideas. Help is very much appreciated! -
Django write to csv with some empty fields
I'm trying to write some search results to a CSV file, but with the ability to have some fields be empty. Right now it's writing the entire search string, but it's the only way I've found to deal with errors when there's no field. This is my code: if request.POST: if request.POST.get('search_type_id') == "1": response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Report Results.csv"' export_data = request.session['report_results'] report_results = Tree.objects.filter(id__in=[instance['id'] for instance in export_data]).order_by('-created_at') writer = csv.writer(response) writer.writerow(['Tree ID', 'Int ID', 'Site Address', 'Site Street', 'Date Planted']) for obj in report_results: writer.writerow([ [obj.id_shared, ''], [obj.id_int, ''], [obj.planting_site.site_address, ''], [obj.planting_site.site_street, ''], [obj.planted_date, ''] ]) return response Right now my CSV returns accounts for empty fields, but gives me a [250264, ''] as the Tree ID, for example. Is there a way I can tell it to substitute blank if there's nothing (fore xample, no obj.planting_site.site_address)? In doing this for JSON results pulled from another site I've been doing obj.get('tree_id', ''), but I can't do that when the objects are models saved internally. -
issues with setting up crudbuilder for django
I'm thinking that this is a simple problem to fix. The main error I'm getting when I runserver is crudbuilder.exceptions.NotModelException: No model defined in <class 'crudbuilder.abstract.BaseCrudBuilder'> class The github is located at https://github.com/asifpy/django-crudbuilder if you'd like to follow along. After a pip install for django-tables2 and django-crudbuilder I added both into my settings.py as such. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_tables2', 'my_project', 'crudbuilder', ] In my models.py, from django.contrib.gis.db import models from django.contrib.postgres.fields import ArrayField class my_model(models.Model): name = models.CharField(max_length=500) gender = models.IntegerField(null=True) and in my newly added crud.py, from crudbuilder.abstract import BaseCrudBuilder from my_project.models import my_model class MyModelCrud(BaseCrudBuilder): model = superman search_fields = ['name'] tables2_fields = ('name', 'gender') tables2_css_class = "table table-bordered table-condensed" tables2_pagination = 20 # default is 10 modelform_excludes = ['created_by', 'updated_by'] login_required=False permission_required=False # permissions = { # 'list': 'example.person_list', # 'create': 'example.person_create' # } For some reason my django app doesnt like my from crudbuilder.abstract import BaseCrudBuilder from line 1 of crud.py, but it does recognize crudbuilder as a legitimate INSTALLED_APP The sources for crudbuilder were pretty minimal. Out of the 5 docs pages I found, they all share the same exact example doc. I feel this may be a one … -
Passing context on an html with both POST and GET options
I have a html page with various submit buttons: <h3>Add Address</h3> <form method="post"> {% csrf_token %} ... <input type="submit" value="Add" name="_add_add"> </form> <h3> Update values </h3> <form method="post"> {% csrf_token %} ... <input type="submit" value="Add" name="_update"> </form> <h3>Address</h3> <form method="get"> ...display... My view.py is: def property(request): if request.method == 'POST': if '_update' in request.POST: ...update values... elif '_add_add' in request.POST: ...add addres.... else: ... graph default values... return render(request, 'address.html', {}, context) When there isn't a POST and simply a GET (like being redirected to the page), I get an CSRF error in the context (and it asked me to use request_context). Is it possible (and how) to automatically send a default context for the GET, and send a different context for POST without incurring the CSRF error? -
How to serialize Filefield or Imagefield data into json data in python django
i'm actually an amateur python programmer and am trying to use the django framework for an android app backend. everything is okay but my problem is actually how to pass the image in the Filefield to JSON. i have tried using SerializerMethodField as described in the rest framework documentation but didn't work. sorry if this question is off track but i seriously need help. -
Django mod_wsgi: ImportError: No module named '$myproject'
So I've been scratching my head for a while trying to figure this one out. I am on Ubuntu 16.04, with 2 different django projects. The intention here is to run both of the side by side on two separate domains on the same server, using two different files in the "sites-(enabled|available)" folder. One is working fine (and has been for a while, this second site is new). The second is not. I'm guessing it has to do with my wsgi settings. To complicate things, I am using lets-encrypt as well. I'm sure that that isn't the issue, but I'll post their confs just to be sure. Project one is in the dir /home/arlyon/arlyon and nr2 is in the dir /home/arlyon/threeswords. 000-default.conf <VirtualHost *:80> ServerName www.site1.com ServerAlias site1.com ServerAdmin mail@me.com DocumentRoot /home/arlyon/arlyon WSGIScriptAlias / /home/arlyon/arlyon/arlyon/apache/wsgi.py WSGIDaemonProcess arlyon python-home=/home/arlyon/arlyon/venv python-path=/home/arlyon/arlyon WSGIProcessGroup arlyon Alias /static/ /home/arlyon/arlyon/static/ <Directory /home/arlyon/arlyon/static> Require all granted </Directory> Alias /media/ /home/arlyon/arlyon/media/ <Directory /home/arlyon/arlyon/media> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =www.site1.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent] RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} !^www\..+$ [NC] RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] </VirtualHost> 000-default-le-ssl <IfModule mod_ssl.c> <VirtualHost *:443> ServerName www.site1.com ServerAlias site1.com ServerAdmin mail@me.com DocumentRoot /home/arlyon/arlyon # user/project/projectapp … -
Django CreateView field labels
I'm working on a project that has a Chapter, with each Chapter having a title, content, and order. I'd like to keep the field 'order' named as is, but have the field displayed in a CreateView as something else, like 'Chapter number'. The best information I've found recommends updating the "labels" attribute in the Meta class, but this isn't working for me. This is what I'm using now, which doesn't work: class ChapterCreate(CreateView): model = models.Chapter fields = [ 'title', 'content', 'order', ] class Meta: labels = { 'order': _('Chapter number'), } I've also tried using the 'label's attribute outside of Meta, but that didn't work either. Should I be using a ModelForm instead, or is there a correct way to do this? -
add extra field inside each page django cms 3.4.x
Hi everyone using this info I create a extension of the page like the image. When I click in CMS extension I have 3 more fields my problem is that this fields appear only in this area, and I want this extra field inside my page... It is posible... when I click and create a new page is posible to add more fields that the fields that exist by default Thanks in advance -
Advise request python env issue after upgrade to 16.04.1
After I upgraded my OS to stable version of 16.04.1 I found that my local django version dropped to 1.8.7 when i was using 1.9+. first reaction was to use pip install --upgrade django==1.9.7 but it gave me that pip is not found.. same as easy_install. After checking I can see that i have files in usr/local/bin/* taras@taras-Laptop:/usr/local/bin$ ls charm django-admin.py easy_install-3.4 pip2 pip3.4 sqlformat wstorm code django-admin.pyc idea pip2.7 pip.pyc virtualenv django-admin easy_install pip pip3 __pycache__ virtualenv-3.5 when my all files lies here: usr/local/lib/python2.7/dist-packages/* Please advise best solution for me to fix it(by saying fix it i mean to use my old python2.7 stuff by default) I was thinking about adding some env variable? but im not sure so i decided to ask first. Thanks -
Django still caching view with @never_cache
I'm using Django with Django Rest Framework and uWSGI. I have memcached set up on the server with pylibmc backend. I have Django configured for per-site cache so every view should be cached except ones that I exempt from it using the @never_cache decorator. I can't figure out why Django is still trying to cache my API views even with Django's @never_cache decorator added. I have an API that supports read write operations for a Draft model. When I make a draft update using the UpdateAPIView, then refresh the page, it is still showing the Draft data prior to the update. I've confirmed it's not browser side cache because network logs show 200 response, not 304, and if I clear memcached and refresh the page, then the updated Draft is correctly returned. This recently happened when I upgraded Django from 1.8 to 1.10, the ~15 pip package dependencies, the OS distro and its packages (so it's hard to pinpoint exactly what caused it). DRF Retrieve API View from django.views.decorators.cache import never_cache from django.utils.decorators import method_decorator class DraftDetail(generics.RetrieveAPIView): queryset = Draft.objects.all() serializer_class = DraftSerializer permission_classes = (permissions.IsAuthenticated, HasReadWriteAccess) @never_cache def dispatch(self, *args, **kwargs): return super(DraftDetail, self).dispatch(*args, **kwargs) I've also tried the … -
Serializer ForeignKey results in "Expected a dictionary ..."
My Model: class Font(ValidateVersionOnSaveMixin, models.Model): id = models.UUIDField(primary_key=True, editable=True) name = models.CharField(max_length=100, blank=False, null=False) class Glyph(ValidateVersionOnSaveMixin, models.Model): id = models.UUIDField(primary_key=True, editable=True) unit = models.CharField(max_length=100, blank=False, null=False, unique=True) font = models.ForeignKey(Font, on_delete=models.CASCADE) I want to post the following JSON to create an Glyph object: { fontId: "4a14a055-3c8a-43ba-aab3-221b4244ac73" id: "40da7a83-a204-4319-9a04-b0a544bf4440" unit: "aaa" } As there is a mismatch between the ForeignKey Field font and the JSON propertyfontId I am adding source='font' in my Serializer: class FontSerializer(serializers.ModelSerializer): class Meta: model = Font fields = ('id', 'name') class GlyphSerializer(serializers.ModelSerializer): fontId = FontSerializer(source='font') class Meta: model = Glyph fields = ('id', 'unit', 'fontId' ) But the result is an BAD REQUEST Error: {"fontId":{"non_field_errors":["Invalid data. Expected a dictionary, but got str."]}} -
Django HTTP Redirect After Logger Error
I would like to redirect the user to an error code in 4xx or 5xx after logging a CRITICAL or ERROR level issue. If I log an error anywhere except the View (Form or Model), how would I do this? What is the most Django-esque/Python-esque way to do this? I have forms that populate dropdowns dynamically. If I get an ERROR or CRITICAL issue there where I am unable to populate them, how should I redirect the user after logging the issue? I have though about the following options: Create a filter that handles the re-direct. Create a custom handler that redirects. Simply redirect with code after the logging. This would replicate code. Extend the logger class or wrap it. I am little new to Django. -
Expiring object relations in Django REST Model
I've been trying to tackle the question of having object relations expire after a set period of time using Django REST framework. Here's the general idea: I have a view that presents a list of objects i.e. accepts GET requests to retrieve information about this list: These objects have a one-to-many (foreign key) relationship with another type of object The other type of object provides useless information after 24 hours Therefore, I'd like to be able to have these related objects disappear from the view after one day. I figure there are three possible solutions, of which I'm not sure how to implement: Have relationship expire after 24 hours Related object deletes after 24 hours View filters against related objects that were created >24 hours ago Has anyone carried out something similar in the past and could provide a code snippet that demonstrates performing said implementation? Thanks for your help. -
How can I safely pass username/password from a custom form to django backend?
Django 1.8, jquery front-end I have a basic form, without sensitive data. However, if the user checks an optional checkbox field, it opens a modal form to prompt for authentication. When they input username and password in the modal form and hit submit, is it safe to read those with js and pass to the backend for processing with an ajax call like any other ajax payload? Edit to say it will of course go over https only. What other options are there? -
Changing data-tooltip with AJAX isn't working
I have a button in my html template: <a class="tooltipped" id="stash_recipe_tooltip" data-position="bottom" data-delay="50" data-tooltip="{{ stash_tooltip }}"> <div id="stash_recipe_btn" class="detail_footer_btn btn-floating col2 center"> + </div> </a> later, in the html file, I have: <script> function add_recipe_to_stash() { var stash_plus_or_minus = document.getElementById("stash_recipe_btn").innerHTML $.ajax({ url: '/ajax/add_recipe_to_stash/', type: 'GET', data: { # this goes to a django view that, in essence, returns a new 'stash_tooltip' var and 'stash_plus_or_minus' var 'stash_plus_or_minus': stash_plus_or_minus, }, dataType: 'json', success: function (data) { document.getElementById("stash_recipe_btn").innerHTML = data.stash_plus_or_minus; $("#stash_recipe_tooltip").attr('data-tooltip', data.stash_tooltip); } }); } function addClickHandlers() { $("#stash_recipe_btn").click( add_recipe_to_stash ); } </script> It seems like $("#stash_recipe_tooltip").attr('data-tooltip', data.stash_tooltip); should be changing my tooltip, but nothing happens. Any idea how to successfully update the data-tooltip without refreshing the page? I've tried different variations of the above line but I can't get it to update. -
django celeryd using wrong broker even after config_from_object
This is my celery file: from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') app = Celery('my_app', broker=settings.BROKER_URL) # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) and in my settings.py I have this: #Celery stuff BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' But when running celeryd this happens: - ** ---------- [config] - ** ---------- .> app: default:0x1052af590 (.default.Loader) - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (prefork) It doesn't seem like it's using the configuration that I have provided. What am I missing? -
Django apps with models.py in non-standard location
I've just started working on a codebase that the team I've joined is updating from using Django 1.4 to Django 1.8. Along with that change, it's being restructured into separate apps, and the layout is being changed in various ways. INSTALLED_APPS has some apps, let's call them foo and bar, but their models.py files have been put into db subdirectories, that is foo/db/models.py. Those models can be accessed from code (for example views) with from foo.db.models import SomeModel, and that seems to work. However, from my reading of https://docs.djangoproject.com/en/1.8/ref/applications/#initialization-process, particularly stage 2, models defined in foo/db/models.py rather than foo/models.py won't be found during application loading, which will cause a variety of issues. Is it possible to support this non-standard location of models.py with a custom AppConfig, or in some other way? To clarify, I think trying to have models.py in a non-standard location is a bad idea; I'm after confirmation to help make my argument to the rest of the team. -
Real Time calculation in django admin
i am working on a website in witch i have to do a javascript realtime calculation, i need a total price to be filled based on a list of checkboxes. My models are as follow class Student(models.Model): ... class Price(models.Model): student = models.OneToOneField(student, on_delete=models.CASCADE) service1 = models.PositiveSmallIntegerField(default="1000") service2 = models.PositiveSmallIntegerField(default="750") service3 = models.PositiveSmallIntegerField(default="350") class Facture(models.Model): month_choices = ( ('9', 'Jan'), ('10', 'Feb'), ... ) student = models.ForeignKey(Student, on_delete=models.CASCADE) month = models.CharField(max_length=3, choices=month_choices) service1 = models.BooleanField(default=True) service2 = models.BooleanField() service3 = models.BooleanField() total = models.PositiveSmallIntegerField() payed = models.PositiveSmallIntegerField() date = models.DateField(default=datetime.datetime.today) in admin.py, the models Price and Facture are display as TabularInline like so: class PriceInline(admin.TabularInline): model = Price formset = RequiredInlineFormSet can_delete = False class FactureInline(admin.TabularInline): model = Facture what i need is when i check some services, the total field should be filled with the sum of check services price from the Price model the field total must be stored in database for some cases.. any help would be appreciated -
How to run a CMD and open Bash when running a docker container?
I am having a rough time trying to figure this out. So I have a dockerfile based on an Ubuntu image. At the end of my dockerfile I have: CMD django-admin startproject $PROJECTNAME I was told in a previous post that the base Ubuntu image has a CMD to run /bin/bash so my command is actually overwriting this (not sure if this is relevant or not). The problem I'm encountering is if I run: docker run -i -t <containerid> Nothing happens.. docker ps shows no containers are running But if I run: docker run -i -t <containerid> /bin/bash The container starts running, I am in the shell, and docker ps shows that this container is running. Everything works as expected, but my django project is not there and my understanding is that running /bin/bash overrides the CMD in the dockerfile, which means django-admin startproject never gets run. From inside the container, I can run django-admin startproject $projectname and it creates the project with no issues, which tells me django and all its dependencies are installed, and my environment variables are being registered. However, I still suspect that there maybe is an issue with my CMD in my dockerfile and I … -
add a param ForeigKey to form, and that param be taken by URL
bassically i what to now how add a parameter ForeignKey to a model form, I whant that param is taken by the URL. I what that Document.task be complete automatically by the information in the URL. The URL be something like this: url(r'^category/(?P<category>[\w]+)/task/(?P<task>[\w]+)/file/$', views.model_form_upload, name='model_form_upload'), view: def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'core/model_form_upload.html', { 'form': form }) models: class Category(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, null=False, blank=False, class Task(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) task = models.ForeignKey(User) form: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'document', ) template: {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} -
Django Virtualenv running on Apache and CentOS
background: CentOS6 with SELinux httpd mod_wsgi installed and confirmed loaded Virtualenv running python 2.7 with django installed django app in /var/www/html/web virtualenv in /var/venv/mybox I tried everything on SO. The only exception is I did not turn SELinux off nor do I want to. In my httpd.conf file <IfModule mod_wsgi.c> WSGIScriptAlias / /var/www/html/web/myapp/wsgi.py WSGIPythonPath /var/python_venv/mybox/lib/python2.7/site-packages:/var/www/html <Directory /var/www/html> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> </IfModule> ... <VirtualHost *:80> ServerName myserver ServerAlias myserver ServerAdmin blah@blah.com <Directory /> Options FollowSymLinks AllowOverride None </Directory> WSGIScriptAlias / /var/www/html/web/myapp/wsgi.py ErrorLog /etc/httpd/logs/error.log LogLevel warn CustomLog /etc/httpd/logs/access.log combined </VirtualHost> In my wsgi.py import os,sys from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/html/web') sys.path.append('/var/venv/mybox/lib/python2.7/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") application = get_wsgi_application() The Apache errors mod_wsgi (pid=): Target WSGI script '/var/www/html/web/myapp/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=): Exception occurred processing WSGI script '/var/www/html/web/myapp/wsgi.py'. ImportError: No module named django.core.wsgi I tried changing the permissions as in the other posts. virtualenv should be pointing to the correct python ldd /etc/httpd/modules/mod_wsgi.so linux-vdso.so.1 => () libpython2.7.so.1.0 => /usr/lib/libpython2.7.so.1.0 () -
How to identify gaps in a sequential list using Django templates
If I have an ordered sequential list in my django template: my_list = [ (1, "Billy Holiday"), (2, "Louis Armstrong"), # Number 3 is missing! (4, "Ella Fitzgerald"), (5, "Frank Sinatra"), ] And I want to show something like this in my html: 1. Billy Holiday 2. Louis Armstrong -- Some rows may be missing -- 4. Ella Fitzgerald 5. Frank Sinatra Is there a clever way to do this? I'm trying to accomplish this using Django templates. The idea would be to look at the previous iteration of the loop, and identify if rows are missing based on the counter values.