Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create dynamic slider?
Is there a javascript slider like slick or owl that can handle dynamic content. For example if slider content is added everyday I can show todays slider content click the arrow left will take you to previous day content. The issue is if I have thousandths of previous content then I need to access database and so slider content is accessed on runtime. see https://www.merriam-webster.com/word-of-the-day/qui%20vive-2016-12-16 to see what I mean. I'm using Django Framework. -
Django - confirmation with jquery bootbox
I'm trying to make my confirmation looks better, but when I'm trying to do it it's not working properly. it shows me everything fine but it automatically click "ok" by itself, not letting me if I want to confirm or not. Here's what I got: my template: <td > <a href="{% url 'edit' item.id %}" class="confirm" > <img class="autoResizeImage" src="http://www.free-icons-download.net/images/edit-icon-1901.png"/ > </a> </td> My js: $(document).on('click', '.confirm', function(){ bootbox.confirm("Are you sure?", function(result){ alert('This was logged in the callback: ' + result); }); Note: Only happens if I add my <a href="{% url 'edit' item.id %}"></a> if I have something simple like this <button class="confirm" > click me </button> works great. What am I doing wrong? Basically after I hit "edit" to make my onclick jquery function appears my confirmation but it automatically redirects me to my <a href="{% url 'edit' item.id %}"></a> and I want to redirect me when I hit "ok" button. -
Why app/admin in debug mode false give me Server Error 500
I changed my server settings.py from Debug = True to Debug = False. I can get httpResponses from my other app urls but I can't access the /admin domain specifically, I get the Server Error (500) I tried to change the ALLOWED_HOSTS = ['my-app-name.herokuapp.com'] as other topics of this problem says but it didn't help me in my case. Why does it block me? How can I fix it? thanks. -
Django - detect if user is online / offline
I am using Django 1.10 with Django-REST. I need to know is a user is logged in or not (offline / online) How is it possible to do it ? I am using token base auth. I tried this article but it didtn went well.. it seems to be too old -
How to use just one url patter in django to handle GET, POST and kwargs in HttpResponseRedirect?
I know that after dealing with a post request we should not render the page but should use HttpResponseRedirect. I wanted to send some data back with this redirect. I went through multiple SO but I have few questions. Using message framework. Good until you are just sending text messages. If I want to send objects or dictionaries back to template what should I use? I came to know we can use *args or **kwargs. when I tried to use kwargs in HttpResponseRedirect, it complain about url matching. So does that mean I need to create another URL which accepts kwargs. Lets see one example here:- I am saving some data for which I have this url. url(r'^add-event/$', views.add_event, name='add_event') on GET request of this page, template is loaded which shows form to save the data. On POST request of this page, form data is saved. Now if everything is fine in POST request, I can send success message back with query string or with message framework. But if there is some error while saving data, I want to send whole data back to the template to render it into the form as it is so that user need not … -
boto S3ResponseError: 400 Bad Request
I'm deploying my Django application on Ubuntu of EC2 on AWS. I finished all the jobs needed but connecting to boto. In my settings.py AWS_ACCESS_KEY = 'AWS_ACCESS_KEY' AWS_SECRET_ACCESS_KEY = 'AWS_SECRET_ACCESS_KEY' AWS_STORAGE_BUCKET_NAME = 'BUCKET-s3' AWS_QUERYSTRING_AUTH = False S3_URL = 'https://s3.ap-northeast-2.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME DEFAULT_FILE_STORAGE = 'PROJECT.s3utils.MediaS3BotoStorage' STATICFILES_STORAGE = 'PROJECT.s3utils.StaticRootS3BotoStorage' MEDIA_URL = S3_URL + '/media/' STATIC_URL = S3_URL + '/static/' MEDIA_ROOT = MEDIA_URL STATIC_ROOT = STATIC_URL 'PROJECT.s3utils.py' is below: from storages.backends.s3boto import S3BotoStorage StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static') # s3 directory name class MediaS3BotoStorage(S3BotoStorage): location = 'media' Finally, I need to set up configuration file for connecting boto. Without anything, when I command 'python manage.py collectstatic' , the error shows this message : boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler'] Check your credentials So I did add configuration file at '~/.boto' as below: [Credentials] AWS_ACCESS_KEY_ID=AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY=AWS_SECRET_ACCESS_KEY After creating configuration file ~/.boto, I did command 'python manage.py collectstatic' I got an error : boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request What I do is following the boto document : http://boto.cloudhackers.com/en/latest/getting_started.html Is there anything I am missing now? Please help me -
'Relation does not exist' error after transferring to PostgreSQL
I have transfered my project from MySQL to PostgreSQL and tried to drop the column as result of previous issue, because after I removed the problematic column from models.py and saved. error didn't even disappear. Integer error transferring from MySQL to PostgreSQL ALTER TABLE "UserProfile" DROP COLUMN how_many_new_notifications; Getting the following: ERROR: relation "UserProfile" does not exist Here's a model, if helps: class UserProfile(models.Model): user = models.OneToOneField(User) how_many_new_notifications = models.IntegerField(null=True,default=0) User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) I supposed it might have something to do with mixed-case but I have found no solution through all similar questions. -
Update default on image field for all records in the database in Django
I am working on a Django project and I would like to update the default image for all records in my database, if anyone has any idea on how to do this please let me know, thanks. -
Options for adding push-notifications to Django-driven web sites
I've done a lot of research, and possibly at least some of this question will be stamped as duplicate, and yet I feel like totally lost among all these daunting concepts that I cannot even categorize into comparable groups. So, for the sake of this question. let's assume that my stack is MySQL + Apache + Django without possibility to turn to node.js on backend. My app is a task manager. As user A attaches new task to user B, I would like the user B to get a notification both on the web and on an Android app. Based only on my research, I would go for Tornado + socket.io + MongoDB acchitecture. Now, I have several questions in this respect. In what category do Django channels fall? Can we compare Django channels to Tornado or socket.io, and say that one of them is better than the other in the context of sending new task creation push-notifications ? Where does Redis fall into this discussion? Is Redis comparable to Tornado? -
django-olwidget generating object has no attribute 'get_declared_fields' error
After installing django-olwidget in the virtualenv I set up for my Django project, I get an error referencing get_declared_fields. Here's the traceback: Traceback (most recent call last): File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/olwidget/admin.py", line 34, in <module> from olwidget.forms import apply_maps_to_modelform_fields, fix_initial_data, fix_cleaned_data File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/olwidget/forms.py", line 89, in <module> class MapModelForm(BaseMapModelForm): File "/Users/wmfox3/.virtualenvs/slurp/lib/python2.7/site-packages/olwidget/forms.py", line 57, in __new__ declared_fields = forms.models.get_declared_fields(bases, attrs, False) AttributeError: 'module' object has no attribute 'get_declared_fields' I'm running Django==1.10.4 and django-widget==0.61.0. I've tried various combinations of Django and olwidget without success. I've found references this issue getting patched in olwidget, but since I'm running the latest versions of both Django and django-olwidget, I'm not sure why I'd still be getting this error. -
Apache doesn't start with an error
I'm trying to deploy my django application in AWS with EC2-Instance. Actually, I'm following this tutorial : https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 When I followed all and so command 'sudo service apache2 start' I got an error : Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details. I did check the log with the command 'systemctl status apache2.service' apache2[18041]: * The apache2 configtest failed. apache2[18041]: Output of config test was: apache2[18041]: AH00526: Syntax error on line 30 of /etc/apache2/sites-enabled/000-default.conf: apache2[18041]: Multiple arguments not (yet) supported. apache2[18041]: Action 'configtest' failed. apache2[18041]: The Apache error log may have more information. 'etc/apache2/sites-enabled/000-default.conf' is below </VirtualHost> Alias /static /home/ubuntu/MY_PROJECT/MY_PROJECT/static <Directory /home/ubuntu/MY_PROJECT/MY_PROJECT /static> Require all granted </Directory> <Directory /home/ubuntu/MY_PROJECT/MY_PROJECT/MY_PROJECT> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess MY_PROJECT python-path=/home/ubuntu/MY_PROJECT/MY_PROJECT python-home=/home/ubuntu/MY_PROJECT/sn_venv WSGIProcessGroup MY_PROJECT WSGIScriptAlias / /home/ubuntu/MY_PROJECT/MY_PROJECT/MY_PROJECT/wsgi.py </VirtualHost> Please, help me! -
Django/python : How to assign the ForeignKey field for the child model in Django views?
I have created a Child Model connected to the Parent Model via ForeignKey. When i tried to create a Child instance it returns nothing. I am not sure in my views child.Parent is working properly or not. I would appreciate helping me solve this. Here's my code: models.py: Parent(models.Model): Parent = models.CharField(max_length=30) def __str__(self): return self.id def get_absolute_url(self): return reverse("parents:detail", kwargs={"id": self.id}) Child(models.Model): Parent = models.ForeignKey(Parent, related_name='children') Child = models.CharField(max_length=30) def __str__(self): return self.id forms.py: ChildForm(models.ModelForm): Parent = forms.CharField(widget=forms.HiddenInput) class Meta: model = Child fields = ["Parent", "Child", ] views.py: def child_create(request, id): parent_instance = get_object_or_404(Parent, id=id) form = ChildForm(request.POST or None) if form.is_valid(): child = form.save(commit=False) child.Parent = form.cleaned_data.get('parent_id') child.save() return HttpResponseRedirect(parent_instance.get_absolute_url()) context = { 'form':form, 'parent_instance':parent_instance,} return render(request, "child_create.html", context) templates/child_create.html: {{if parent_instance.id}} <form class="nomargin" method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} {{ form|crispy }} <input type='hidden' name='parent_id' value='{{ parent_instance.id }}' /> <input type='submit' value='Add a Child' class='btn btn-default' /> </form> -
How to separate a function which talks to the API and uses user's input - python
I need to move the part of my function which talks to the API to manage.py file and leave user's input in views.py. Whatever I try doesn't work... Will appreciate your suggestions. My code in views.py: @app.route("/request", methods=["POST"]) #API request def request(): since = request.form['since'] until = request.form['until'] r = requests.get('https://apiurl/?since='+since+'&until='+until+'') json_object = r.json() data = json_object['data'] values = data[0]['values'] gender_brackets = ('Female', 'Male') #Iterate through the response for item in values: date = item['date'] for key in gender_brackets: fm = item['value'].get(key, 0) fm_data = API(date=date, gender=key[0], value=fm) session.add(fm_data) session.commit() return render_template("chart.html") -
Scrapy Get value of javascript attribute
I'm trying to get value of javascript which is you can see below. <script type="text/javascript" src="//media.flixfacts.com/js/loader.js" data-flix-distributor="7148" data-flix-language="tr" data-flix-brand="lg" data-flix-ean="8806087586213" data-flix-sku="1162559" data-flix-inpage="flix-inpage"></script> I Tried this but its not worked. ean = response.xpath('/html/head/script[25]/@data-flix-ean').extract_first() -
django_dynamic_fixture data not available in functions
I'm using django_dynamic_fixture for my tests. For some reason the dummy data I create doesn't seem to be available in functions called. Here's what I mean: from django_dynamic_fixture import G from otherpackage import call_function from django.test.testcases import TestCase class SomeTest(TestCase): def some_test_method(self): G(MyModel) # create dummy object call_function() and then when I try to do MyModel.objects.all() in call_function it seems to be empty []. However calling inside some_test_method shows the are objects created. Thoughts? -
Error on installation of Django based application
I'm trying to install a Django based software: https://github.com/luk156/get2 on ubuntu, 16 but after i follow all the procedures in the install.txt apache2 retrive an 505 error. -
DRF generic relationships and override to_representation()
Following Generic relationships I implemented class GenericMyModelSerializer(serializers.RelatedField): """ """ # SerializerMethodField and related get_visibility don't work # visibility = serializers.SerializerMethodField() def to_representation(self, value): if isinstance(value.content_object, Model1): serializer = Model1Serializer(value.content_object) elif isinstance(value.content_object, Model2): serializer = Model2Serializer(value.content_object) *** *** else: raise Exception('Unexpected type of object') # updating serializer.data (ReturnDict) doesn't work: # serializer.data['visibility'] = value.visibility return serializer.data I need to add e.g. value.visibibility or value.order to the serializer.data (ReturnDict class that extends collections.OrderDict), with version 2.X I was brutally doing: serializer.data.insert(2, 'visibility', value.visibility) serializer.data.insert(3, 'order', value.order) How can I add fields to the serializer.data? Is there any best practise for this scenario (adding SerializerMethodField doesn't work)? Thanks, -
In Djnago, how to last record value based on column if it empty or none get last-1
In Djnago, how to last record value based on column if it empty or none get last-1 element until record column value in not empty or none -
Session state missing in python social auth
I followed this tutorial (https://artandlogic.com/2014/04/tutorial-adding-facebooktwittergoogle-authentication-to-a-django-application/) and I am getting following error. I have hosted my server on a EC2- instance and I have a domain http://(xyz).com. I also saw answer of this question (Session value missing after redirect with django python-social-auth) but I am not getting any help. -
How to fix migration error (NOT NULL constraint failed) in django?
Hello and thank your for your time Situation: I need add one new field in my django model the field status_of_lieman = models.BooleanField(default=False, verbose_name="Course status") Makemigratios goes fine, but when i try to migrate i get error: Running migrations: Applying faceset.0077_course_status_of_lieman...Traceback (most recent call last): File "C:\python35\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\python35\lib\site-packages\django\db\backends\sqlite3\base.py", line 323, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: faceset_course.status_of_lieman The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pycharm\django_manage.py", line 41, in <module> run_module(manage_file, None, '__main__', True) File "C:\python35\lib\runpy.py", line 182, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "C:\python35\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\python35\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "E:/lieman\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\python35\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\python35\lib\site-packages\django\core\management\__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\python35\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "C:\python35\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "C:\python35\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File … -
How 'Happn' like application woks?
I'm wondering how applications like Happn works efficiently, I mean how it is able identify people who have installed the same app in 250-meter range. And How server works in these applications. Actually, I'm trying to build same kind of application that identify people in a certain range, using Django(GeoDjango for Spatial Search) and Android.So can anyone advise me about how frequently I store user's current location for location based search. -
django-sql : sql to query set
puzz_meeting_candidats : - id, canceled, candidat_id, meeting_id puzz_meeting : - id, Client I have a query follow: SELECT U1.`candidat_id` AS Col1 FROM `puzz_meeting_candidats` U1 INNER JOIN `puzz_meeting` U2 ON ( U1.`meeting_id` = U2.`id` ) WHERE U2.`Client` LIKE '%ipsos%' AND U1.`canceled` = False with condition using Q object . I'm so thank for your helping!!! :D -
Multiple ajax requests kill django server
I have a single view which scrolls through user data. There are next and previous buttons to scroll. When user presses next, ajax sends the user id to the django view and displays the data. If user clicks the next button two or three times consecutively (which they usually do), the calls get aborted and server is killed. $("#new").click(function() { $.ajax({ type:'POST', url:'/new/', data:{ csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:searchSuccess, dataType: 'html' }); }); function searchSuccess(data, textStatus, jqXHR) { $('#myForm').html(data); } This is the view. def master_detail_next(request): def decrement_voucher_id(form_id): voucher_id = str(int(form_id) - 1).zfill(4) return voucher_id if request.method == 'POST': form_id = request.POST['voucher_id'] voucher_id = decrement_voucher_id(form_id) voucher_id = get_decremented_voucher_id(voucher_id) else: voucher_id = '' # Inline forms author = TmpPlInvoice.objects.get(voucher_id=voucher_id) author_form = TmpForm(instance=author) BookFormSet = inlineformset_factory(TmpPlInvoice, TmpPlInvoicedet, exclude=('emp_id', 'voucher', 'lineitem', 'id',), form=TmpFormDetForm, ) formset = BookFormSet(instance=author) totalform = TmpFormTotal(instance=author) postform = CheckPostedForm(instance=author, posted=author.posted) return render(request, 'form.html', {'form': author_form, 'formset': formset, 'formtotal': totalform, 'postform': postform}) How can i avoid that? What is that i am doing wrong? -
separate python script cannot find self-defined module inside Django
This is my Django app folder structure |-----tt | |--settings.py | |-----warehouse | |--models.py | |-----dashboard | |--email_excel_reports.py | Inside my email_excel_reports.py # for ORM query from warehouse.models import EntryFormLineItem from django.db.models import Sum from django.db.models.functions import Coalesce from django.utils import timezone line_items = EntryFormLineItem.objects.filter(approved_by__isnull=False, ... I got this error when I run python email_excel_reports.py inside dashboard Traceback (most recent call last): File "/vagrant/dashboard/email_excel_reports.py", line 11, in <module> from warehouse.models import EntryFormLineItem ImportError: No module named 'warehouse' When I run python manage.py shell and then type the same lines of code, there was no problem running the code. How do I get over the error? -
Django 1.8, Unable to run manage.py
A newbie here. I am getting following erorr: python manage.py migrate Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "//anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "//anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "//anaconda/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "//anaconda/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "//anaconda/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "//anaconda/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "//anaconda/lib/python2.7/site-packages/aldryn_newsblog/models.py", line 61, in <module> }[connection.vendor] KeyError: 'unknown'