Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django '1.10' : When I add 'django_bleach' to the INSTALLED_APPS setting , my website isn’t working
I've installed django-bleach package by running pip install django-bleach But after adding django_bleach to the INSTALLED_APPS setting , my website goes down : Secure Connection Failed The www.website.com page isn’t working My settings.py is : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # It's work 'bootstrap3', # It's work 'django_bleach', # My website goes down ] And the version of python and ... : Python==2.7.5 Django==1.10.1 django-bleach==0.3.0 What do you think could be the reason for this problem? -
How can I upload form/field contents to an IPFS node using Django?
I'd like to override the upload behavior of a django ImageField so that instead of uploading to some url, the file will be added to an ipfs node. For example, my model is something like: class Profile(models.Model): picture = models.ImageField(upload_to=upload_location, blank=True) I first try saving it as you would any other image, but then I give it an IPFS hash, which will allow the user to load the data client side. In my views I have the following code to get an instance of ipfs daemon running. import ipfsapi from subprocess import call os.system("ipfs daemon") api = ipfsapi.connect('127.0.0.1', 5001) When I try to run python manage.py makemigrations or runserver, however, the daemon runs but the rest of the command doesn't. Initializing daemon... Swarm listening on /ip4/127.0.0.1/tcp/4001 Swarm listening on /ip4/174.56.29.92/tcp/4001 Swarm listening on /ip4/192.168.1.109/tcp/4001 Swarm listening on /ip6/::1/tcp/4001 API server listening on /ip4/127.0.0.1/tcp/5001 Gateway (readonly) server listening on /ip4/127.0.0.1/tcp/8080 Daemon is ready How can I start an ipfs daemon and also a django server? It doesn't look like they're listening on the same port (Django 8000, IPFS 8080), so why am I running into this problem? -
Using a global static variable server wide in Django
I have a very long list of objects that I would like to only load from the db once to memory (Meaning not for each session) this list WILL change it's values and grow over time by user inputs, The reason I need it in memory is because I am doing some complex searches on it and want to give a quick answer back. My question is how do I load a list on the start of the server and keep it alive through sessions letting them all READ/WRITE to it. Will it be better to do a heavy SQL search instead of keeping the list alive through my server? -
How to detect if script ran from Django or command prompt?
I have a Python script that pauses for user input (using raw_input, recently I created a Django web UI for this script. Now when I execute the script via Django is pauses as it's waiting for input in the backend. How can I determine if the script was ran from Django or terminal/cmd/etc? I don't want to maintain 2 streams of code, one for web and another one for terminal. -
internationalization in django
I want to internationalize my django app. After playing around according to the documentation and following this question here I realized I don't need most of these options. In my settings file I only use this: USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) So I got rid off LANGUAGE_CODE and also didn't define any LANGUAGES. Then I only added this to my views from django.utils import translation created language translations with django-admin.py makemessages -l fr and django-admin.py compilemessages and translated the messages in the .po file. Now when I set the browser preference (Chrome) to French, all the text within {% trans my text %} in the html shows up translated. I guess it's explained here on a higher level, I am just a little confused that it is that simple. Or is this just a hack that I am using? -
remove first migration Django cms
I create my first custom plugin with my model like this. class Hello(CMSPlugin): guest_name = models.CharField(max_length=50, default='Guest') but now I want to change the name of my model and adds more fields. How to revert the first migration? I use this for see all my migrations ./manage.py showmigrations customPlugin customPlugin [X] 0001_initial I only have the initial, how to remove this migration to start again. thanks in advances -
The difference between applying permissions to separate object and list of objects in django rest framework
In my code permissions result differently to object and list of objects. Let's say we have one model of User: class User(auth.AbstractBaseUser, auth.PermissionsMixin): name = models.CharField(max_length=255, blank=True, null=True) profile_status = models.CharField(max_length=255, blank=True, null=True) and two rows in db: 1. name = "Dennis", profile_status = "private" # (not "public") 2. name = "Robert", profile_status = "private" # (not "public") and the viewset: class UsersViewSet(viewsets.CreateListRetrieveUpdateViewSet): queryset = models.User.objects.all() # doesn't matter... serializer_class = serializers.UserSerializer # doesn't matter... filter_class = filters.UsersFilterSet # doesn't matter... permission_classes = [IsProfileAccessStatus('public'), IsReadOnly] IsProfileAccessStatus('public') django permission returns True if object's profile_status equals 'public': def IsProfileAccessStatus(access_status=''): class IsProfileStatusOf(BasePermission): def has_object_permission(self, request, view, obj): return hasattr(obj, 'profile_status') and \ obj.profile_status== access_status return IsProfileStatusOf Back end returns users at /api/users/ and speicific one at /api/users/:name/. Different output On /api/users/Dennis/ drf returns exception according the IsProfileAccessStatus('public') permission. So it's okay. But for /api/users/ it returns both objects: [ { "name": "Dennis", "profile_status": "private" }, { "name": "Robert", "profile_status": "private" } ] So the question is Why django permissions are used this way? Why drf permissions are not applied for every instance? Thank you! -
Python Celery - Permission Issue - Unable to upload files from a download task
I have a Celery task whose job is to download files to a local directory, and then upload to a S3 bucket when download is complete. My issue is that with a recent update of the workers, I'm getting permission denied errors when accessing the folder to upload. The code was fundamentally unchanged other than from going to script-method to class based implementation. I made a task just to create the directories, with a single method call: os.mkdirs(path, 777) and it creates the directory with permissions 300 This is despite CELERYD_USERS='ubuntu' CELERYD_GROUP='ubuntu' CELERYD_CREATE_DIRS=1 in the config. According to the docs, the last option allows celery to create a directory owned byt the user/group specified above. That much is happening, but nothing is said about permissions. Is there any way around this? -
Not able to calculate to what range current date belongs in django?
I have period model and this model has a current property that should calculate what period is current. @with_author class Period(CommonInfo): version = IntegerVersionField( ) order_value = models.PositiveSmallIntegerField() start_date = models.DateField() end_date = models.DateField() name = models.CharField(max_length=30) duration = models.PositiveSmallIntegerField(null=True, blank=True) is_special = models.BooleanField(default=False) is_marked = models.BooleanField(default=False) _is_current = models.NullBooleanField( blank=True, null=True, default=None) #not_terminated_active_objects = NotTerminatedActiveManager() def __unicode__(self): return u'%s %i %s ' % ("#", self.order_value, self.name) def _is_current(self): if self.start_date <= datetime.datetime.now().date() <= self.end_date: self._is_current = True else: self._is_current = False @property def is_current(self): if self._is_current is None: self._is_current() return self._is_current However it is not calculated and I am not getting any error. What I am doing wrong? -
Passwordless User authentication with a Django or just any REST API system
I am implementing a webservice with a bunch of REST API. These REST API will all be invoked from a python command line interface script. When a userA, logged in as himself on a unix system, invokes that CLI python script, I would like the script to be able to invoke the REST API through the python HTTP client, but do it without having to use a password. Since he is already, authenticated as himself on the linux. How can this be implemented? Are there any Django packages/documentation that help with it? -
Django Selenium Test SyntaxError: missing )
I try to follow and customize taskbusters tutorials to my needs. I am having problems with selenium tests. I am trying to test my google app login . I use django-alluth and I created google api credentials. I use Firefox 49 and Selenium 3.0.0b3 . I arranged marionette driver and I dont have problem with making tests work. My test file : # -*- coding: utf-8 -*- from selenium import webdriver from django.core.urlresolvers import reverse #from django.contrib.staticfiles.testing import LiveServerTestCase from django.contrib.staticfiles.testing import StaticLiveServerTestCase from datetime import date from django.utils import formats class HomeNewVisitorTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def get_full_url(self, namespace): return self.live_server_url + reverse(namespace) def test_home_title(self): self.browser.get(self.get_full_url("home")) self.assertIn("Yogavidya", self.browser.title) def test_h1_css(self): self.browser.get(self.get_full_url("home")) h1 = self.browser.find_element_by_tag_name("h1") self.assertEqual(h1.value_of_css_property("color"), "rgba(200, 50, 255, 1)") def test_home_files(self): self.browser.get(self.live_server_url + "/robots.txt") self.assertNotIn("Not Found", self.browser.title) self.browser.get(self.live_server_url + "/humans.txt") self.assertNotIn("Not Found", self.browser.title) def test_internationalization(self): for lang, h1_text in [('en', 'Welcome to YogaVidya!'), ('tr', 'YogaVidya\'ya hoşgeldiniz!')]: activate(lang) self.browser.get(self.get_full_url("home")) h1 = self.browser.find_element_by_tag_name("h1") self.assertEqual(h1.text, h1_text) def test_localization(self): today = date.today() for lang in ['en', 'tr']: activate(lang) self.browser.get(self.get_full_url("home")) local_date = self.browser.find_element_by_id("local-date") non_local_date = self.browser.find_element_by_id("non-local-date") self.assertEqual(formats.date_format(today, use_l10n=True), local_date.text) self.assertEqual(today.strftime('%Y-%m-%d'), non_local_date.text) def test_time_zone(self): self.browser.get(self.get_full_url("home")) tz = self.browser.find_element_by_id("time-tz").text utc = self.browser.find_element_by_id("time-utc").text ny = self.browser.find_element_by_id("time-ny").text self.assertNotEqual(tz, utc) self.assertNotIn(ny, [tz, utc]) When … -
Error running development server with Postgres user in Django
Switching from user "postgres", I created a new Postgres user and changed my Django project to make use of this new user / credentials: sudo -u postgres -i psql -c "CREATE USER foo WITH PASSWORD 'xxxxxxxxxxxx' CREATEDB;" psql -c "GRANT ALL PRIVILEGES ON DATABASE bar TO foo;" In settings for Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bar', 'USER': 'foo', 'PASSWORD': 'xxxxxxxxxxxx', 'HOST': 'localhost', 'ATOMIC_REQUESTS': True } } But I get the error when using "python manage.py runserver": django.db.utils.ProgrammingError: permission denied for relation django_migrations -
How do I assign specific users to a user-uploaded file in Django + Apache
Im using django 1.10 + Apache in Linux. I've created a small webapp to upload documents (with dropzone.js) and want to implement the ability for a user to specify who can view/modify/delete a specific file but i can't figure out a way how. I attempted using a ManyToManyField but maybe im not understading the Field itself correctly. The "Document" model is this: class Document(models.Model): file = models.FileField(upload_to = 'files/') #validators=[validate_file_type]) uploaded_at = models.DateTimeField(auto_now_add = True) extension = models.CharField(max_length = 30, blank = True) thumbnail = models.ImageField(blank = True, null = True) is_public = models.BooleanField(default = False) accesible_by = models.ManyToManyField(User) #This is my attempt at doing this task. def clean(self): self.extension = self.file.name.split('/')[-1].split('.')[-1] if self.extension == 'xlsx' or self.extension == 'xls': self.thumbnail = 'xlsx.png' elif self.extension == 'pptx' or self.extension == 'ppt': self.thumbnail = 'pptx.png' elif self.extension == 'docx' or self.extension == 'doc': self.thumbnail = 'docx.png' def delete(self, *args, **kwargs): #delete file from /media/files self.file.delete(save = False) #call parent delete method. super().delete(*args, **kwargs) #Redirect to file list page. def get_absolute_url(self): return reverse('dashby-files:files') def __str__(self): return self.file.name.split('/')[-1] class Meta(): ordering = ['-uploaded_at'] My view to handle the creation of documents: class DocumentCreate(CreateView): model = Document fields = ['file', 'is_public'] def form_valid(self, form): … -
static files not detected Django 1.10
Problem: javascript and css files doesn't load. I am using Django 1.10, my settings.py file looks like this: STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, "static_root") I have my static files in the static folder and also have a static root, still the js, css not workingWhy? -
Django REST Framework prevent multiple validation queries in batch create
When trying to do bulk inserts using Django/Django Rest Framework 3, the validation step is causing n * related_model_fields queries, which is causing a lot of unnecessary latency. In the example below, Thing has two related fields, one being user (added in the view), and the other being the pk of another model in a foreign key related field. Each item in the batch is individually being validated, and that validation includes look ups on the User model, and the other related model, resulting in 2 queries per item in the batch just for validation. Is there any way to override this behavior to do a "batch" validation of the data? Or can I override the validation behavior to validate against a pre-queried set of values to prevent multiple database round-trips? class ThingView(APIView): def post(self, request): # Add user to each record user_id = self.request.user.id map(lambda rec: rec.update(user=user_id), request.data) serializer = ThingSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ThingListSerializer(serializers.ListSerializer): def create(self, validated_data): details = [Thing(**item) for item in validated_data] return Thing.objects.bulk_create(details) class ThingSerializer(serializers.ModelSerializer): class Meta: model = Thing list_serializer_class = ThingListSerializer -
Is there a command for creating an app using cookiecutter-django?
Once a Django project has been created using cookiecutter-django, is there a command like python manage.py startapp <app_name> to run instead of writing the new app from scratch? -
Django - Problems with get_or_create()
I'm facing problems using get_or_create() in my view. What I want to do is have the User get or create an instance of the Keyword model whenever he wants to add a keyword. I have a Keyword model that looks like this: class Keyword(models.Model): word = models.CharField(max_length=30, unique=True, default=None) members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, default=None) def __str__(self): return self.keywords I have a form to create the keyword: class KeywordForm(forms.ModelForm): keywords = forms.CharField(max_length=30) def __init__(self, *args, **kwargs): super(KeywordForm, self).__init__(*args, **kwargs) self.fields["keywords"].unique = False class Meta: fields = ("keywords",) model = models.Keyword I've tried different things in the view and here is my current version, without the use of get_or_create. It only creates the keyword: class KeywordCreationView(LoginRequiredMixin, generic.CreateView): form_class = forms.KeywordForm model = models.Keyword page_title = 'Add a new keyword' success_url = reverse_lazy("home") template_name = "accounts/add_keyword.html" def form_valid(self, form): var = super(KeywordCreationView, self).form_valid(form) self.object.user = self.request.user self.object.save() self.object.members.add(self.object.user) return var How should my view look in order to get the keyword if it exists and if it does, add the User as 'member'. If it doesn't, create the Keyword. Thanks for your help! -
Ckeditor is showing a richtextfield in admin ?
I am trying to put a html rich text in django admin. I followed the instructions to the tee. however for some reason it is not picking up ? What am I missing? Here is the settings.py - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'skoolprofile', 'django.contrib.sites', 'disqus', 'django.contrib.sitemaps', 'easy_maps', 'hitcount', 'accounts', 'localflavor', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'autoslug', 'storages', 'compressor', 'activities', 'tastypie', 'ckeditor', ] AWS_QUERYSTRING_AUTH = False CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'Basic', }, } CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' here is models.py - from ckeditor.fields import RichTextField class adalerts(models.Model): headline = models.CharField(max_length =200, null =True, blank=True) description = RichTextField(config_name='awesome_ckeditor', null = True, blank=True) schoolid = models.CharField(max_length = 100, null = True, blank=True) schoolname = models.CharField(max_length = 100, null = True, blank=True) city = models.CharField(max_length = 100, null = True, blank=True) location = models.CharField(max_length = 100, null = True, blank=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): # __unicode__ on Python 2 return "%s - %s - %s" % (unicode(self.schoolid) , unicode(self.city), (unicode(self.schoolname))) here is admin - admin.site.register(adalerts) I did python manage.py collectstatic. I did makemigrations and migrate. yet no luck in admin for field richtextField "description". I still see a textfield. -
Django + Backbone: underscore template for login / logout
I am building a SPA using Django and Backbone. Until now most of my templates have been on the Django side, but I'm now moving to templating with Backbone/Underscore. The only thing I'm unsure about is how to manage page reload with respect to authentication. I do not have a separate login page, but rather a dropdown login form on the app's menu bar (a Bootstrap navbar), which makes Ajax requests for login/out actions. I want to keep the app interface publicly available, and only render certain components (load, save, export buttons) when a user is logged in, hiding them when logged out. A page reload obviously has to be aware of whether the user is logged in or not. This is how I'm managing it in my Django template: <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Menu left --> <ul class="nav navbar-nav"> <!-- li components... --> </ul> <!-- Menu right --> <ul class="nav navbar-nav pull-right" id="navbar-right"> {% if user.is_authenticated %} <!-- If user is logged in render 'My Account' and 'Logout' components --> <li id='menu-account'><a href='#'>My Account</a></li> <li id='menu-logout'><a href='#'>Logout</a></li> {% else %} <!-- If logged out render the login form --> <li id="menu-register"><a href="#">Register</a></li> <li class="dropdown" id="menu-login"> <a … -
Django (1.9) Watson index Django Tagging TagField
How can I index a field that is managed by the Django Tagging (v0.4.5) TagField manager? The tags are all working correctly and Watson (v1.2.1) is indexing the models and returning results from searching the char and text fields as it should but not if the search term is a tag. The registering is done in an AppConfig as documented: from __future__ import unicode_literals from django.apps import AppConfig from watson import search as watson class TeamConfig(AppConfig): name = 'team' def ready(self): Team = self.get_model("Team") watson.register(Team, fields=("title_text", "tagline", "description", "tags")) Member = self.get_model("Member") watson.register(Member) and the Team model that has the tag TagField field is all good: import blahs ... from watson import search as watson from tagging.fields import TagField ... class Team(models.Model): pub_date = models.DateField('date published', auto_now_add=True) title_text = models.CharField('Name', max_length=200, blank=False, ... tags = TagField() is_active = models.BooleanField('Active?', default=True) Anyone got any idea how to get the field indexing same as a char or text field please? Thanks so much Rich -
for loop django 1.10 fails : Need 2 values to unpack in for loop; got 1
I'm updating from Django 1.8.6 to 1.10.1 and it fails but I don't see why. I pass these values to a template : bicycle = [('type', 1001L), ('status', u'test'), ('orderDate', datetime.datetime(2016, 10, 3, 0, 0)) ] template (simplified): {% for key,value in bicycle %} {{ value }} {% endfor %} In Django 1.10 this doesn't work anymore and I get this error: Need 2 values to unpack in for loop; got 1. What is wrong here? (I also tried removing the datetime field, but that didn't help) -
IT Operations django website
I need to build internal website for our company which will allow our developers to log in and deploy new application in AWS. Developers will have to enter all information and it will generate json file and get merged with master branch and then Jenkins job will kick in to deploy new application Should i be using django for this or another framework? Thanks -
How to detect deadlocks in Django?
How to detect a transaction deadlock in Django? Which exception it raises? It seems for me that it is IntegrityError but this exception is raised also in other situations (not deadlocks). How to check if it is a deadlock? -
Django Model inheritance and access children based on category
I want to get the parent class values with each child values ? How can I identify child objects to fetch ? I have the django model structure like this. class Category(models.Model): name = models.CharField(max_length=80) class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) category = models.ForeignKey('Category') class PizzaRestaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class PastaRestaurant(Place): extra = models.CharField(max_length=80) When we do operation we may save the object like below. And it saved into the db as i expected. two entry in the Place table and each entry in each child object table. a = Category() a.name = "pasta" b = Category() b.name = "pizza" a.save() b.save() x = PastaRestaurant() x.address = "Pasta Address" x.name = "Pastamonia" x.extra = "some extra" x.category = a y = PizzaRestaurant() y.address = "Pizza Address" y.name = "Dominos" y.serves_hot_dogs = 1 y.serves_pizza = 0 y.category = b x.save() y.save() Now I need to access the like this p = Place.objects.get(id=1) How can I know, which objects/attributes belongs to the place objects? So when I fetch the place with common attributes and can get the corresponding child objects values also. Help plz? -
Migrating a Primary Key to another column of another type (when FK constraints exist)
I have inherited a Django application that needs some serious love. We have the need for Generic Foreign Keys to be used for a few object types. However, some developer set up the following, breaking the behavior expected by the ContentTypes framework (Int. PK for each model): class Router(models.Model): part_number = models.CharField(max_length=55, primary_key=True) This model has over 2 dozen FKs pointing to it from different models, each with an FK constraint in Postgres. It must be updated so to use a standard primary key implementation. class Router(models.Model): part_number = models.CharField(max_length=55, unique=True, primary_key=False) In order to use Generic FKs, I the standard primary key in place; i.e. an AutoField w/ incrementing integer PKs. How can I migrate given this issue, change the primary key column on Router, add in integer PK values on that column, update all constraints for FK columns, and update all FKs at the same time?