Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dropdown model is not showing in html view - Django
I'm new in Django, I researched how to create drop-down. I tried everything, but still, the dropdown is not showing in HTML view. My sample script is this. This is the model.py from django.db import models class samplemodel(models.Model): list = ( ('sample','SAMPLE'), ('sample','SAMPLE'), ) list_choices = models.CharField(max_length=6, choices=list) The forms.py from .models import samplemodel from django.forms import ModelForm class sampleForm(ModelForm): class Meta: model = samplemodel fields = ['list_choices'] This is the views.py from django.shortcuts import render from .models import samplemodel from .forms import sampleForm from django.views.generic import CreateView class sampleView(CreateView): model = samplemodel form_class = sampleForm template_name = 'home/sample.html' This is the home.html {% extends 'base.html' %} {% block head %} <title>Home</title> {% endblock %} {% block body %} <div class="container"> <form class="post"> {% csrf_token %} {{ form.as_p }} </form> </div> {% endblock %} I tried everything that I saw on the internet. But I can't still show the drop-down. I don't know if the imports are the issue or not. -
PDF/Document preview in django template
I'm really quite new with django and was wondering if there is any way I can show a preview of pdfs/documents inside an html template with django and not another page/tab? Would like to ask for any insight. Thanks a lot! -
Django admin update of form fields based on foreign key model selection
In django admin I have Model A with a foreign key association to Model B. Model B's values change based on the value of Model A. When a Model B object is selected for association with a Model A object, I would like to immediately display updated values for Model B based on the current value of Model A. I know that I can override the on_save method in the form to update the values when the user saves the form to the database. However, I would like the admin view to display the values before the user hits save. What do I need to hook into to make this update happen? Thank You -
Django Settings, Git and Amazon AWS
I'm using Django, Git and Amazon's Elastic Beanstalk. With my Django, I don't want to store my settings files on my git. The problem is now I can't use eb deploy since it copies my git code to my AWS without the settings file and then fails. How do I tell it keep the previous settings module? Or should I be storing my settings on git? That seems pretty insecure.. Any thoughts about how this should be handled? Thanks. -
How to make AmChart follow synchronize with video element
I am currently working on a project that uses https://www.amcharts.com and I am trying to synchronize a <video> element's "currentTime" to the chart's cursor. Similar to this example with audio: https://www.amcharts.com/kbase/sync-chart-cursor-html5-audio/ In the example above, the audio emits the currentTime event with the current audio time, then converts the time to a format to an argument in chart.chartCursor.showCursorAt(time) In my example below, once the currentTime emits, the cursor goes all the way to the end of the graph and stays there. How can I make it so the video's "currentTime" hover's over the corresponding time in the chart? <script> $(document).ready(function(){ var chart = AmCharts.makeChart( "chartdiv", { "type": "stock", "theme": "light", "categoryAxesSettings": { "minPeriod": "ss", // set minimum to milliseconds "groupToPeriods": [ 'ss' ] // specify period grouping }, "dataSets": [ {% for l, c in labels %} { "title": "{{ l|safe }}", "color": "{{ c }}", "fieldMappings": [ { "fromField": "prominence", "toField": "prominence" } ], "dataLoader": { "url": "/data/csv/calc/{{ l|quote }}.csv", "format": "csv", "delimiter": ",", "useColumnNames": true, "skip": 1 }, "categoryField": "time" }{% if not loop.last %},{% endif %} {% endfor %} ], "panels": [ { "title": "Prominence", "percentHeight": 70, "stockGraphs": [ { "id": "g1", "valueField": "prominence", "lineThickness": 2, "bullet": … -
How to use --keepdb when run the commond "python manage.py test"?
First seeing this page:https://docs.djangoproject.com/en/1.9/topics/testing/overview/#the-test-database I understand like this: 1 - when I run test commond like python manage.py test --keepdb,the test database would be saved. 2 - But if I use the sqlite ,the test databases would default be maked in memory.It means ,although I used the --keepdb,without setting others,the test databases would not save. 3 - If I use except sqlite, the test databses would happend in the filesystem,which means I can seem the database in a file or by the sql-control-tools. (ps:If I had a wrong though,point it out please~) Then,I try like this: 1 - use sqlite. 2 - make a table. 3 - write a test which save some datas to the table. 4 - try commond with --keepdb The result was predictable:I do not see a file or see the test database or test tables in control-tools. It may be ,test databases or tables build in memory ? So,here comes the questions below: 1 - If I use the sqlite,what should I do or change settings so that I can save the test datas I can see by eyes? Thanks~ -
python3 django-1.11 ImportError: No module named 'MyProject.settings'
django 1.11 python 3.5.2 I've been working on an initial django app and just changed the views, models and forms from individual files to directories. My development machine is a windows box running the latest PyCharm. I then "deployed" the updated files to a linux dev machine. I did makemigrations and migrate and that seemed to work. I then visited the site... Traceback (most recent call last): File "/dh/passenger/helper-scripts/wsgi-loader.py", line 320, in <module> app_module = load_app() File "/dh/passenger/helper-scripts/wsgi-loader.py", line 61, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/home/me/.pyenv/versions/3.5.2/lib/python3.5/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 693, in _load File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "passenger_wsgi.py", line 23, in <module> application = get_wsgi_application() File "/home/me/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/home/me/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/me/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/me/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/me/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/me/.pyenv/versions/3.5.2/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, … -
Django unable to migrate PostgreSQL: constraint X of relation Y does not exist
I'm trying to run a Django 1.11 migration on a PostgreSQL 9.6.5 database, and I'm getting the odd error: Applying myapp.0011_auto_20171130_1807...Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/operations/models.py", line 536, in database_forwards getattr(new_model._meta, self.option_name, set()), File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 349, in alter_unique_together self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 380, in _delete_composed_index self.execute(self._delete_constraint_sql(sql, model, constraint_names[0])) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: constraint "idx_32269_myapp_mymodel_title_333195ae82ac2107_uniq" of relation "myapp_mymodel" does not exist The migration is changing a unique contract from including one column … -
when i use jquery on crispy forms input fields it doesn't work
I'm using crispy forms. when i use qty field's id and price field's id using jquery for some calculations it doesn't work. i want to add their values multiplied for the value field so i used jquery but nothing works here's my code $(document).ready(function(){ $('#qty_id').on('change', function(){ $('#total_id').val($('#qty_id').val()*$('#price_id').val()); }); $('#price_id').on('change', function(){ $('#total_id').val($('#qty_id').val()*$('#price_id').val()); }); }; forms.py class ItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-lg-2' self.helper.form_tag = False self.helper.form_class = 'form-inline' self.helper.layout = Layout( Field('code',), 'description', Field('qty', id="qty_id"), Field('price', id="price_id"), Field('total', id="total_id"), 'employee', ) class Meta: model = Item fields = ('code', 'description', 'qty', 'price', 'total', 'employee',) -
How to call a variable function with parameter in django template?
I want to achieve something like this within a Django template. {{ variable.function(parameter) }} Where variable is a variable passed through a context to a template, in this case, an instance of a model. I have tried different methods, but no one seems to work. -
The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELD S
I got an error,The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.Error says TooManyFieldsSent at /api/upload The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. I wrote in views.py def upload(request): id, array = common(request) if request.FILES: file = request.FILES['req'].temporary_file_path() else: return HttpResponse('<h1>NG</h1>') return HttpResponse('<h1>OK</h1>') def common(request): id = json_body.get("access", "0") if id == "": id = "0" s = [] with open(ID_TXT, 'r') as f: for line in f: s += list(map(int, line.rstrip().split(',')[:-1])) array = [s[i:i + 2] for i in range(0, len(s), 2)] return id, array I post access & req data by using POSTMAN like I think this error is limitation of being able to send file size,so I added a code to settings.py DATA_UPLOAD_MAX_MEMORY_SIZE = 100000000 but error does not solve.I read this page How to avoid "The number of GET/POST parameters exceeded" error? as reference.How should I fix this? -
mutation error, Unknown argument \"barcode\" on field \"createProduct\" of type \"Mutation\" - django
I am doing tutorials online and trying to make mutation works on graphql but I kept on getting errors which I have no idea what where the real error comes from and how to start debugging where I have done wrong. looking at this youtube for mutation https://www.youtube.com/watch?v=aB6c7UUMrPo&t=1962s and the graphene documentation http://docs.graphene-python.org/en/latest/types/mutations/ I noticed that because of different graphene version, that is why I have reading the documentation instead of following exactly as the youtube I got things setup but then couldn't get it to work, when I execute the mutation query I get error. I have a model like this. class Product(models.Model): sku = models.CharField(max_length=13, help_text="Enter Product Stock Keeping Unit", null=True, blank=True) barcode = models.CharField(max_length=13, help_text="Enter Product Barcode (ISBN, UPC ...)", null=True, blank=True) title = models.CharField(max_length=200, help_text="Enter Product Title", null=True, blank=True) description = models.TextField(help_text="Enter Product Description", null=True, blank=True) unitCost = models.FloatField(help_text="Enter Product Unit Cost", null=True, blank=True) unit = models.CharField(max_length=10, help_text="Enter Product Unit ", null=True, blank=True) quantity = models.FloatField(help_text="Enter Product Quantity", null=True, blank=True) minQuantity = models.FloatField(help_text="Enter Product Min Quantity", null=True, blank=True) family = models.ForeignKey('Family', null=True, blank=True) location = models.ForeignKey('Location', null=True, blank=True) def __str__(self): return self.title I have this for my Product schema class ProductType(DjangoObjectType): class Meta: model = Product … -
Python logging writing to multiple separate log files
I have a Django web application that runs a bunch of helper scripts. Each of these scripts writes its own log. I am noticing that the scripts are writing to each others logs. These scripts are launched by separate users/sessions. Whats going on? Here is the implementation of the logger within ScriptA import logging logging.basicConfig(format='%(asctime)s %(message)s',filename='/var/logs/scriptA.log',level=logging.DEBUG) same for scriptB but say someone runs scriptB, it writes to scriptA.log instead of scriptB.log it seems logging is created a shared global module. How can I stop this EDIT: most solutions here are for 2 separate logs within the same class. my issue is separate scripts/classes writing to each others logs -
Facebook Graph API /adaccounts error code 100
I can't seem to get past an error I'm getting while trying to use the Facbook API. My goal: login with my personal account, and ideally FB gets ads or their info from the business account it's tied to. I have a facebook developer's app set up, and I've added a marketing API to it. Here is the error in its entirety: Message: Call was not successful Method: GET Path: https://graph.facebook.com/v2.11/<user_id>/adaccounts Params: {'fields': 'name,id', 'summary': 'true'} Status: 400 Response: { "error": { "message": "Unsupported get request. Object with ID '<user_id>' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api", "type": "GraphMethodException", "code": 100, "error_subcode": 33, "fbtrace_id": "FvOtKRJdDv+" } } By googling the error I've seen that some people run into this problem when they run a page, and the page has user/viewer restriction on country, age, etc. but that doesn't seem to be the case here. The ads belong to a business/ad account on facebook, and I am an 'ad account admin'. Not sure if it's relevant, but I'm using the 'facebookads' pip package in a Django application. Not sure what else to troubleshoot, so … -
Django create user account via URL
I'm currently working with some people to develop an application that will display a "sound library" when the user selects an option on their voip phone. The idea is that the phone system will pass a url with a device id in it, and that will open the django app to the users' library. I was told to remove login/user authentication in order to make the process easier for the user. My question is, is there a way to create a user field and save the model for future retrieval via the url request alone? Do I need to pass the device id to some hidden form first and redirect to the main page, and query the users' objects via the device id? I know there are security concerns but was wondering if it's even possible, any help is appreciated! -
Browser Not Picking Up Changes - Not a Cache Issue
I had a django webpage that worked. Then I started running Chrome audits and consequently added media and defer tags to several of my scripts. I then removed the tags, and now my page is still loading the scripts as if the tags are still in there. It also will not pick up any other changes to the html (i.e. title change). I have tried different browsers. I have tried clearing my cache. I have tried incognito tabs. The request is a 200 request. I am using Atom as my code editor and hosting on IIS. I have checked numerous times to ensure I am working on the correct file - comparing the document tree in IIS to the Windows Explorer document tree. This is the current state of my scripts (what it was before the audits): <link rel="shortcut icon" href="#" /> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4-4.0.0-beta/jq-3.2.1/jszip-2.5.0/dt-1.10.16/b-1.4.2/b-colvis-1.4.2/b-flash-1.4.2/b-html5-1.4.2/b-print-1.4.2/datatables.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/bs4-4.0.0-beta/jq-3.2.1/jszip-2.5.0/dt-1.10.16/b-1.4.2/b-colvis-1.4.2/b-flash-1.4.2/b-html5-1.4.2/b-print-1.4.2/datatables.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script> Why are my changes not being picked up anymore? -
django models date day is filtered to the day before
I have a model with a DateTimeField, and I have set it to Nov 20 2017 In [23]: my_obj.date_field Out[23]: datetime.datetime(2017, 11, 20, 0, 0, 1, tzinfo=datetime.timezone.utc) But when I try to retrieve by selecting the objects with date_field's day = 20, Django does not find the element In [11]: MyObj.objects.filter(date_field__day=20) Out[11]: <QuerySet []> However, if I select the elements with date_field's day = 19, it does find my object. In [12]: Regime.objects.filter(start_date__day=19) Out[12]: <QuerySet [my_obj]> Can someone explain this weird behavior? Is this expected behavior? -
Multiple inheritance from abstract classes with same parent but different child? django
I have read few threads and know that for sure django can have multiple abstract classes. But pretty much all the samples I saw are... class AbsOne(models.Model): pass class AbsTwo(models.Model): pass class AbsThree(AbsOne, AbsTwo): pass but what if I have something like... class AbsOne(models.Model): pass class AbsTwo(AbsOne): // this actually inheritance AbsOne pass class AbsThree(AbsOne): // this inheritance AbsOne pass What if I need to inheritance both AbsTwo, AbsThree but these two are also inheritance to the same parent. class AbsFour(AbsTwo, AbsThree): pass Is this doable without any conflict or extra fields? Thanks in advance. -
Facebook Page Feed Webhook troubleshoot
I have setup the facebook webhook integration, using the facebook developer platform guidelines. I am currently recieving post requests via a django application. Even though at the beginning I would get a post request everytime I posted a new message on my page feed, I eventually stopped getting them. At the moment, the only feed messages that I'm getting via my webhook, are the ones that you can send from the webhook subscription test options. Is there a rate limit as to how many posts facebook will allow to post in an unpublished page? Any and all information will be appreciated. -
How do I add Access-Control-Allow-Origin in NGINX?
I have a project place in root/home/project, and i have video files placed in root/usr/share/nginx/www/videofiles, I am trying to enable ACAO in root/etc/nginx/sites-enabled/default, using the code: location ~* \.(mp4)$ { add_header Access-Control-Allow-Origin *; } , inside of server {}. When i try to access that video in my project it is telling me that there isn't a header assigned. Is this not properly assigning the header? If so, where and what would allow it? Thanks :) -
How to configure mongoengine and django So as to read data from mongo database?
I want to read the data from mongo database using django. But mongoengine and django is not configuren. I want to know how settings.py file should look like for django and mongoengine . -
Django Updating a Value before a Save
I'm trying to update a counter in a model to save database queries. So I have an article model with a picture_count field. Pictures are m2m with the article. When every I add or remove a picture from the article (using Django Admin) I want to update the article picture_count. But it seems that I'm going about it wrong. I thought I could simply override the save method of my article model. But this doesn't work as the def save(self, *args, **kwargs): self.picCount = self.pictures.count() super(Articles, self).save(*args, **kwargs) # Call the "real" save() method. The problem is that the m2m haven't been updated yet. I have tried calling it after (then calling save again) but the object is outdated. Should I refresh the object and save it again or is there a better place to update this count? -
Django: Trying to count number of pokes each user leaves on another user
I am trying to create a program that will allow users to poke each other. It will show/update each time a user has been poked -
Django 'url' template tag incorrectly escapes the question mark
We recently upgraded from Django 1.9 to 1.10, and now the following problem appeared: urls.py: url(r'^search/(?:\?q=(?P<q>[^&]*))?$', views.search, {'q': ''}, name='search'), Template: <a href="{% url 'issues:search' "foobar" %}">Issues</a> With Django 1.9, the result was https://127.0.0.1/issues/search/?q=foobar Since Django 1.10, this results in the following URL: https://127.0.0.1/issues/search/%3Fq=foobar As a result, links that contain query parameters do not work anymore. How can this be made to work with Django 1.10? -
NameError in Django simple search
I have a simple search in my Django project. I want to search through documents using their type and part of factory info in addition to search by name. Here is my models.py: class Docs(models.Model): Date = models.DateField(default=date.today) Name = models.CharField(max_length=50) Type = models.ForeignKey(DocTypes) Part = models.ForeignKey(Parts) Link = models.FileField(upload_to='Docs/%Y/%m/%d') class Parts(models.Model): Name = models.CharField(max_length=50) def __str__(self): return str(self.Name) class DocTypes(models.Model): Type = models.CharField(max_length=50) def __str__(self): return str(self.Type) My forms.py: class DocsSearchForm(ModelForm): class Meta: model = Docs fields = [ 'Name', 'Type', 'Part'] And this is part of my views.py, if no search was done then all documents are given def showdocs(request): if request.method == 'POST': form = DocsSearchForm(request.POST) documents = Docs.objects.filter(Name__contains=request.POST['Name']| Type==request.POST['Type']| Part==request.POST['Part']) else: form = DocsSearchForm() documents = Docs.objects.all() return render( request, 'showdocs.html', {'documents': documents, 'form':form} So, the problem is the following: if I try to use a search then I have NameError at /showdocs name 'Type' is not defined. POST values are:Part '1', Name 'Example', Type '1'. If I delete Type==request.POST['Type']| Part==request.POST['Part'] then search by name works well. So I have a guess that problem is about searching by foreign key values, but have no ideas more. Will appreciate any help.