Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Background image not displaying in proxy browsers (opera mini and UC browser)
I have the following in django project .home { height: 100vh; /*background-image: url('../../media/background_for_homepage.jpg');*/ background-repeat: no-repeat; -webkit-background-size: contain; -moz-background-size: contain; -o-background-size: contain; background-size: contain; } <div class="home" style="background-image: url('../..{{background.image.url}}');"> </div> It works well on major browsers and CM Browser(a proxy browser) but not on Opera mini and UC Browser. Please I would like to know what workaround is available to display the background image on such browsers. Thank you PS: the image is dynamically generated -
language file doset load automaticaly in django
Im Using python3 and django1.10 for my application , and kinnda new to django. Im planning to have many languages for django admin panel. as i follow the rules in Django documantion, i find out that i have to use a middleware for localization... here is my setting apps MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'en' ugettext = lambda s: s LANGUAGES = ( ('fa', ugettext('Farsi')), ('en', ugettext('English')), ) When i go to admin mylocal/en/admin or mylocal/fa/admin the application language changed perfectly. But my language file(.po) always looks into LANGUAGE_CODE. when i set LANGUAGE_CODE='fa' it will change to farsi . not automatically Now i just want that my language files load using the urls /en/ or /fa/ . Please help me. -
Django filter out specific ModelChoiceField choices from field
I was wondering how I would filter a queryset so that it includes everything but the ones where the fields are rejected or cancelled. I currently have something like this, but I would like to know if this is the way to do this, or if there is a better way CREATED = 'created' PENDING = 'pending' ACCEPTED = 'accepted' REJECTED = 'rejected' CANCELLED = 'cancelled' STATUS_CHOICES = ( (CREATED, _('created')), (PENDING, _('pending')), (ACCEPTED, _('accepted')), (REJECTED, _('rejected')), (CANCELLED, _('cancelled'))) status = models.CharField(max_length=255, choices=STATUS_CHOICES, default=CREATED) orders = Payment.objects.filter(blabla=something).exclude(status='rejected') .exclude(status='cancelled') So there are obviously more status_choices, but how would I go about filtering these two statuses? -
Project not finding my reusable app's admin template override
I have a reusable app with a directory structure like this: myapp/ myapp/ views.py models.py ...etc templates/ myapp/ template1.html ...etc admin/ index.html test/ ...testing stuff setup.py ...etc I'm overriding the index.html admin template so that I can add some additional links in {% block userlinks %} that will appear in a project's navigation when it uses my app. However, when using my app inside a project, the admin homepage still uses Django's own index.html file. The project itself has a base_site.html that it uses, but the template inheritance diagram (in django-debug-toolbar) looks like this: /path/to/virtualenv/django/contrib/admin/templates/admin/index.html /projectpath/projectname/templates/admin/base_site.html /path/to/virtualenv/django/contrib/admin/templates/admin/base.html ...that first entry should be the index.html file in my app's templates directory! Does anyone know why it's not being found? I can post settings if needed. -
Django: ValueError: Unable to configure handler - [Errno 2]
I am very new to Python and Django and is currently busy learning myself through tutorials on www.djangoproject.com. I am using PyCharm and working on OS X El Capitan. I have imported a project from github and created a virtual environment for the project interpretor based on Python 3.5.1. In the vm I installed django. I then activated the vm. Now.. i started by trying to execute simple commands in the terminal like python manage.py startapp deonapp and python manage.py runserver but each time I get an error which I pasted below.. What did I miss? I cannot seem to find the /log/ directory? Kind Regards Deon Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/config.py", line 731, in configure_handler result = factory(**kwargs) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/__init__.py", line 1008, in __init__ StreamHandler.__init__(self, self._open()) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/__init__.py", line 1037, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: '/Users/deon/Documents/PyCharmProjects/Developments/deonproject/log/debug.log' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/deon/Documents/PyCharmProjects/Developments/deonproject/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/deon/Documents/PyCharmProjects/Developments/deonproject/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Users/deon/Documents/PyCharmProjects/Developments/deonproject/venv/lib/python3.5/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) … -
Create a crossplatform, cloud shared, python script/app
I need to create a Django app that resides on an online shared folder (eg. Dropbox), and that can be used indifferently of the OS (windows or mac), although accessing the same database. I thought of using something like pyinstaller to create the OS specific bundles separately, with a relative path to a common sqlite database (which I understood should have a crossplatform format) which is external to both app. Then I should create a script which activate the localserver when you run the app. Do you think is it possible? is there any possible problem which I should mind? -
TinyMCE image upload with Django
I'm trying to work out how to upload images when using Django and TinyMCE, specifically in the Dajngo Admin section. I'm getting an error that +This field is required in my alert (which comes from the python view). Here's my html/javascript/init for TinyMCE: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script type="text/javascript" src="{% static "tinymce/js/tinymce/tinymce.min.js" %}"></script> <script type="text/javascript"> tinyMCE.init({ selector : "#id_html", menubar : true, plugins: 'code advlist link textcolor colorpicker fullscreen insertdatetime table preview image', toolbar: 'undo redo styleselect bold italic alignleft aligncenter alignright bullist numlist outdent indent code link forecolor backcolor fullscreen insertdatetime table preview image', file_browser_callback: function(field_name, url, type, win) { if(type=='image') $('#my_form input').click(); }, image_upload_url : "{% url 'campaign_image_upload' %}", // Options for where to open links target_list: [ {title: 'None', value: ''}, {title: 'Same page', value: '_self'}, {title: 'New page', value: '_blank'}, {title: 'Lightbox', value: '_lightbox'} ] }); </script> {% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block nav-global %} <form id="my_form" action="{% url 'campaign_image_upload' %}" target="form_target" method="post" enctype="multipart/form-data" style="width:0px;height:0;overflow:hidden"> {% csrf_token %} <input name="data" type="file" onchange="$('#my_form').submit();this.value='';"> </form> {% endblock %} Here's my model: class CampaignImageFile(models.Model): name = models.CharField('Filename', default="unnamed", max_length=30) data = models.FileField('Select File') def save(self, *args, … -
ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory:
I am very new to Python and Django and is currently busy learning myself through tutorials on www.djangoproject.com. I am using PyCharm and working on OS X El Capitan. I have imported a project from github and created a virtual environment for the project interpretor based on Python 3.5.1. In the vm I installed django. I then activated the vm. Now.. i started by trying to execute simple commands in the terminal like python manage.py startapp deonapp and python manage.py runserver but each time I get an error which I pasted below.. What did I miss? I cannot seem to find the /log/ directory? Error start: Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/config.py", line 731, in configure_handler result = factory(**kwargs) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/init.py", line 1008, in init StreamHandler.init(self, self._open()) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/init.py", line 1037, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: '/Users/deon/Documents/PyCharmProjects/Developments/deonproject/log/debug.log' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/Users/deon/Documents/PyCharmProjects/Developments/deonproject/venv/lib/python3.5/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/Users/deon/Documents/PyCharmProjects/Developments/deonproject/venv/lib/python3.5/site-packages/django/core/management/init.py", line 341, in execute django.setup() File "/Users/deon/Documents/PyCharmProjects/Developments/deonproject/venv/lib/python3.5/site-packages/django/init.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/deon/Documents/PyCharmProjects/Developments/deonproject/venv/lib/python3.5/site-packages/django/utils/log.py", … -
Initially populate FileField in Django-Form
I have a model that describes a Webpage. The source_upload field represents a screenshot of the webpage. For adding site-objects to my application, I use a django class-based CreateView. This works really well. Now I'm trying to add a semi-automatic way of adding sites. You can pass an URL to the view and the view fills the form automatically (and makes a screenshot of the webpage). The user should be able to review all the auto-extracted fields - especially the auto generated screenshot image - change them and hit the save button to add the object to the database and the image (if approved) to its final location. I tried to implement this in the get_initial method of the view. This works quite well except for the screenshot-FileField. The path I set in initial['source_upload'] is not shown in the current: <link>part of the FileInput widget of the form. How can I give the filefield an initial value? models.py class Site(models.Model): def get_source_upload_path(instance, filename): now = datetime.datetime.now() return "appname/sites/{}/{}/{}/site_{}_{}".format(now.year, now.month, now.day, instance.pk, filename) creationDate = models.DateTimeField(auto_now_add=True) last_modifiedDate = models.DateTimeField(auto_now=True) creator = models.ForeignKey('auth.User', related_name='siteCreated') last_modifier = models.ForeignKey('auth.User', related_name='siteLast_modified') date = models.DateTimeField(default=datetime.date.today) title = models.CharField(max_length=240, blank=True) body = models.TextField(max_length=3000) source_url = models.URLField(blank=True) source_upload … -
How to use/link remote postgres db with django docker implementation
We have a remote postgres database(an amazon rds db) which we need to access from docker django application, how can we link the same ? How my django-compose.yml should look in that case ? -
Formset for relations within relations django
I have the following model setup Model: Record ... onetoonekey(Family) Model: Family ... address Model: Child name surname foreignkey(Family) Using forms I want to be able to edit a record and within edit the family details including the children. Any idea how to go about doing this in django, the docs aren't clear in this area Thanks! -
Django form philosophy - clean or save or sth else?
I have little problem with philosophy - where should I put additional code (and how to get some values from field. My Model has a ManyToManyField (let's call it 'names') with VERY big list of possibilities (hundreds of thousands). So I can't use forms.ModelMultipleChoiceField() normal. My solution is to add additional fields to form: ModelMultipleChoiceField (names_list) and CharField (names_input) One shows the list of choosen names (connected to instance), second is a place where user can enter code. The idea is that if user wants to add new name from the list, he enters code - if it isn't in the list it raises error, otherwise it adds new item. If user wants to remove name or names from the list he should untick the relevant names from the ModelMultipleChoiceField. It looks quite good and comfortable, so I tried to code it. And there's a problem: I have to add logic to def_clean(): if names_input != '': try: newname = Name.objects.get(code=names_input) self.instance.names.add(newname) except ObjectDoesNotExist: self.add_error('names_input',"Name with this code not found") And there's a problem - if code is ok it adds name to instance, if not it raises error. BUT it adds the name ALWAYS, even if other fields are … -
Best way to pass data from a middleware to views in Django without modifying request object
I am new to Django and I want to send some information to my views function from the Middleware which I have created inside my Project. Is there any way of doing this specific task and if not How can we modify the request object?? Thanks -
XBlock No module named NullHandler
Im new in open edx, and I want create an xblock. When I set the comand: python xblock-sdk/manage.py syncdb, I get this error: `Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management /__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python2.7/logging/config.py", line 777, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python2.7/logging/config.py", line 575, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'null': Cannot resolve 'django.utils.log.NullHandler': No module named NullHandler` Thanks for help. -
view must be a callable or a list/tuple in the case of include()
from django.conf.urls import url from django.contrib import admin from photo.views import single_photo from django.conf.urls import include urlpatterns = [ url(r'^photo/$', 'photo.views.single_photo', name='view_single_photo'), url(r'^admin/', include(admin.site.urls)), ] This is My First Django Studying, and Here is Error The Error is view must be a callable or a list/tuple in the case of include(). And I already included admin.site.urls.. -
Unhashable type: 'list' error when trying to add m2m relationships dynamically using post_save in Django
My Content model has a many-to-many relationship to the Tag model. When I save a Content object, I want to add the relationships dynamically. Im doing this the following way. def tag_content(obj): obj.tags.add([1,2,3]) obj.is_tagged = True obj.save() return obj class Tag(models.Model): name = models.CharField(max_length=255) class Content(models.Model): title = models.CharField(max_length=255) is_tagged = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, blank=True) def save(self, *args, **kwargs): super(Content, self).save(*args, **kwargs) @receiver(post_save, sender = Content) def update_m2m_relationships_on_save(sender, **kwargs): if not kwargs['instance'].is_tagged: tag_content(kwargs['instance']) Basically, when a Content object is saved, the receiver is used to call a post_save method which in turn calls the tag_content method to add the m2m relationships. However, I get this error: TypeError unhashable type: 'list' It specifically references the .add() function. Any idea why I am getting this error? Any help is appreciated. Also, do note that I have Tag objects with ids = 1, 2, and 3 in database. -
Model Mommy: Multiple recipes with foreign key relation to a single recipe
I have had this annoyance with ModelMommy for a while but I can't figure out how to do this properly. Let`s assume a simple relation: class Organization(models.Model): label = models.CharField(unique=True) class Asset(models.Model): organization = models.ForeignKey(Organization) label = models.CharField(unique=True) And recipes: from model_mommy.recipe import Recipe, foreign_key organization_recipe = Recipe(Organization, label='My Organization') asset1_recipe = Recipe(Asset, organization=foreign_key(organization_recipe), label='asset 1') asset2_recipe = Recipe(Asset, organization=foreign_key(organization_recipe), label='asset 2') Now when I make these asset recipes I get an error: >> asset1 = asset1_recipe.make() >> asset2 = asset2_recipe.make() IntegrityError: duplicate key value violates unique constraint "organizations_organization_label_key" DETAIL: Key (label)=(My Organization) already exists. This can be solved by providing asset1's organization as a parameter into asset2's make method: >> asset1 = asset1_recipe.make() >> asset2 = asset2_recipe.make(organization=asset1.organization) But there has to be a simpler, more clean way of doing this. -
Datatime sqlite function with Django
I'd like to develop the same instructions that I've implemented with sqlite in Django, How can I do that? The instructions are: cur.execute("CREATE TABLE IF NOT EXISTS Ranging_Dynamic( ID INTEGER PRIMARY KEY , TimeStamp, Ranging_Data_Meters, sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)" ) cur.execute("INSERT OR REPLACE INTO Ranging_Dynamic VALUES (?, ?, ?, CURRENT_TIMESTAMP) ", (RbPiId_r, timestamp_r, ranging)) cur.execute("DELETE FROM Ranging_Dynamic WHERE sqltime < datetime('now', '-30 seconds')") -
How to keep a copy of template view as it is before updating its field value in django?
I need to keep a copy of rendering all data of a view as it is, i.e. its first view. When updated any value of the fields, its content will be changed. After updating, rendering the same template will give different data than first view. But I need to see the previous view or rendered data. For example: You see in updated view of my sample there is some changes which is indicated as bold and italic. After updating I want to retrieve my original data as it is. Is there any better way to do that? -
Django Rest Framework Without Database
I'm trying to setup a simple API using Django Rest Framework, the problem is that my API does not have any database but the framework won't work without database setting. Here is my Django Rest Framework configuration in settings.py: INSTALLED_APPS = [ 'provider', 'django_nose', 'rest_framework', 'django.contrib.contenttypes', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [], 'DEFAULT_PERMISSION_CLASSES': [], } The error which I got is: ImproperlyConfigured("settings.DATABASES is improperly configured. "django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Is there any minimal settings which does not include django.contrib.contenttypes and django.contrib.auth? -
Django form wizard nested dynamic field creation
I'm building a multi-step form with form wizard where a user enters some data, like so: Step1: User selects category from dropdown, (I assume I'll need to do some kind of ajax call here?), then a subcategory dropdown should appear, where he would choose again, then for step 2 I need to dynamically generate the fields, according to the subcategory. #from models.py class Entity(models.Model): name = models.CharField(max_length=255) value_type = models.CharField(max_length=255, blank=True) parent = models.ForeignKey('self', blank=True, null=True) Model use case example: name value_type parent Vehicles select null Real estate select null ..... Cars select Vehicles Bikes select Vehicles ..... Mercedes select Cars Audi select Cars ......... A4 null Audi A5 null Audi etc. So each of the subcategories has a very specific set of fields, all which are very different, with different pre-populated values and need to be generated one by one, within "Step 2" of the form. Say I choose Vehicles and Cars in step 1, step 2 should give me, say a Model dropdown(Mercedes,Audi...) then another dropdown should appear, depending on what I chose, prepopulated with Mercedes models etc. There are several levels of nested dropdowns like I described here. Been stuck on this for a week, nothing from … -
Deployment on Google App Engine - Django, Vagrant, Ansible
I want to deploy Django project on google app engine Following are the current situations. I have a code on GITHUB Djnago project has setup using Vagrant, Ansible, VirtualBox I am completely new for cloud base deployments. Need help to achieve this. I checked google docs but there are couple of options for django related deployment, I am not sure which to pick for vagrant and ansible. -
How to render tables in django-datatable-view?
I can't figure out how to render an editable table using Django-datatable-view. I want to create a table exactly like this: http://django-datatable-view.appspot.com/x-editable-columns/ from model City for example. I've read the docs and tutorials but still can't figure out how to create the table. This is what I've done so far: {% extends "base.html" %} {% block head %} {% load static %}e <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css"> <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script> <script src="{% static "datatable/js/datatableview.min.js" %}"></script> <script> datatableview.auto_initialize = false; $(function () { var xeditable_options = {}; datatableview.initialize($('.datatable'), { fnRowCallback: datatableview.make_xeditable(xeditable_options), }); }) </script> {% endblock %} {% block content %} {{ datatable }} {{ object_list }} {% endblock %} And my view is: class ZeroConfigurationDatatableView(dtv_views.XEditableDatatableView): model = dolava_models.City datatable_options = { 'columns': [ 'id', ("Name", 'name', dtv_helpers.make_xeditable), ("Country", 'country', dtv_helpers.make_xeditable), ] } Unfortunately my code renders this: -
How to directly call a custom ListFilter in Django
I have written custome filters of the type django.contrib.admin.SimpleListFilter. Because I want to write tests for these filtrers, I need to call them directly. I actually try the very same as described in this question, but the answer does not work for me: Test a custom filter in admin.py The following code shows model, filter and test. At this point I do not assert anything in the test, but just let it print out the filtered queryset. The model: class Event(models.Model) title = models.CharField(u"Titel", max_length=1000) status = models.CharField(u"Status", max_length=30) The Filter: class StatusFilter(SimpleListFilter): title = u'Status' parameter_name = 'status' def lookups(self, request, model_admin): out = [ ('saved', u'Saved'), ('published', u'Published'), ] return out def queryset(self, request, queryset): if self.value(): return queryset.filter(status=self.value()) else: return queryset The Test def test_status_filter(self): event = Event() event.title = 'TestEvent' event.status = 'published' event.save() e_filter = admin_filters.StatusFilter(request=None, params={'status':'saved'}, model=Event, model_admin=admin.EventAdmin) filtered_set = e_filter.queryset(None, Event.objects.all()) print filtered_set It should print out nothing (empty list), but actualy prints [<Event: : TestEvent>] -
How to give a user a single session extra permission in Django
Background We have a service where a django super admin can login and view all the users in a specific org, and this super admin can "log in" in the place of that user. Ie suppose we have super admin = joe users = mike, abe, tony then joe can log into an org, see mike, abe and tony, then joe can login into the system as if they are mike. Everything they see and do will be as if Mike were doing it. So if the super admin has permission to create public events, but mike doesn't, when the super admin logs in as mike, they won't be able to create events either. So far so good. However we realized that in many cases we would like the super admin to login as mike, and still be recognized as a super admin in the system. This is useful for data migration purposes, ie sometimes the super admin should actually do stuff in the name of mike that mike can't do themselves. Problem the idea here is that I would like the system to recognize that super admin is logged in as mike. However all questions I saw online (such …