Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IndentationError: expected an indented block (Django and Python)
I'm currently working with Django on a proyect, when I'm about to import the models en the file models.py into the database this error shows up: File "/home/hansen/Escritorio/SIDECO/sideco/models.py", line 31 class Empresa(models.Model): ^ IndentationError: expected an indented block* The code is the following: from django.db import models class Sistema(models.Model): def lista_empresa(): pass def lista_desempleado(): pass def dar_de_alta_desempleado(): pass def dar_de_alta_empresa(): pass def enviar_informacion_desempleado(): pass def listado_desempleado(): pass def almacenamiento_historico(): pass class Persona(models.Model): DNI = models.CharField(max_length=10) tipo_de_trabajo = models.TextField() fecha_de_nacimiento = models.TextField() class Empleado('Persona'): empresa = models.ForeignKey('Empresa') class Desempleado('Persona'): class Empresa(models.Model): cuil = models.CharField(max_length=12) razon_social = models.TextField() rubro = models.TextField() def contratar_desempleado(): pass class OfertaLaboral(models.Model): empresa = models.ForeignKey('Empresa') tipo_de_trabajo_solicitado = models.TextField() -
VueJS props are undefined in component
I am trying to integrate VueJS with my frontend for my Django applications. I have the following Vue code in a javascript file: window.onload = function() { Vue.component('discuss-post', { props: ['post'], template: `<div class="card"> <div class="grid-x margin-x"> <div class="cell small-4"> <img class="avatar-img" :src="post.by.profile.img_url"> <p style="font-family: Abel;font-size: 24px">{{ post.by }}</p> </<div> </div> <div class="grid-x margin-x"> <div class="cell small-4"> <p style="font-family: Abel;font-size: 18px">{{ post.content }}</p> </div> </div> </div>` }) var postDiv = new Vue({ el: "#post-div" }) } And the following code in an HTML file: <div class="card-section"> {% for feed in feeds %} {% for post in feed %} <div id="post-div"> <discuss-post post="{{ post }}"></discuss-post> </div> {% endfor %} {% endfor %} </div> However, when I load my page I get these errors in my console: What in my code could be causing these errors to be raised? -
Why does opening the Chrome Console solve long wait issue?
My colleagues & I are building an Angular 4 app with a Django back-end. Periodically we have to wait a long time for a request to go out from the UI to the web-server. Yet if one opens up the Chrome Console then this seems to effect the request to immediately go out and provide the desired response. We're trying to get a handle on what's going on. Any ideas? Robert -
Django/Postgres - No function matches the given name and argument types
I'm trying to create a search system in my Django and Postgresql project but I keep running into an error when I try to make a query. Whenever I try these commands in the shell: vector = SearchVector('title','tags') query = SearchQuery('book') | SearchQuery('harry') My_Library.objects.annotate(similarity=TrigramSimilarity(vector,test),).filter(similarity__gt=0.3).order_by('-similarity') I get the error: "No function matches the given name and argument types. You might need to add explicit type casts." I've been testing other options for a while, and the only way I can successfully pass a search query without an error is by using two strings in the place of query and vector. My_Library.objects.annotate(similarity=TrigramSimilarity('title','my search query'),).filter(similarity__gt=0.3).order_by('-similarity') This will successfully pass my search with no error. Why am I getting this error, and how can I fix it? I've been basing my code off of this Full Text Search documentation -
how to save JQuery sortable() into MySQL via python?
I built an application using Python/Django/MySQL with Javascript. I am now learning jQuery and implementing it in my app. I am using the sortable() function to sort the rows on my HTML table. Now, the rows on the HMTL table is being rendered from database-> views.py -> HTML using a for loop. Let’s say I have a table with columns: first name, last name, priority. 'ORDER BY priority.’ With the help of jQuery, I am able to drag and drop the rows accordingly using the sortable(). I have added a button that should help me save the new priority of the orders according to my selection. Each person gets a unique priority number. Since most of the answers I see online are PHP/MySQL, it's hard to find answer to my question. Can someone please help me on how to save the new order into my database? What happens if the order of priority are non-consecutive numbers? How will they be save? This is the only Jquery code I have and it is sorting my rows accordingly $(document).ready(function(){ $( "#sortable" ).sortable(); $( "#sortable" ).disableSelection(); }); Thanks a lot for the help! -
How can I Customize Django Admin?
I'm a php developer, now I'm learning python and building web site with Django the biggest question for me is that i want customize the admin template at all,is there any way?,or is it right to oweride it with custom app?. What you can suggest?,please answer asap -
Python Django ValueError: source code string cannot contain null bytes
I have put down a Django project I was working on for a couple months, when I attempted to re run the server I got this error: ValueError: source code string cannot contain null bytes The Traceback is: C:\Users\Broja\Desktop\mynewenv\computersite>manage.py runserver Traceback (most recent call last): File "C:\Users\Broja\Desktop\mynewenv\computersite\manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "C:\Users\Broja\AppData\Local\Programs\Python\Python35\lib\site- packages\django\__init__.py", line 3, in <module> from django.utils.version import get_version ValueError: source code string cannot contain null bytes I am not too familiar with the Django Framework so this error confuses me, any help would go a long way. Thanks. -
django_rq jobs are not added to the queue
I am using: django-rq: 0.9.6 rq_scheduler: 0.6.1 I am fairly new to docker and django_rq. The issue that I am having is, my jobs are not executing or getting in the queue. docker-compose.yml redis: container_name: projapi-redis restart: always image: redis:latest ports: - '6379:6379' rq: container_name: projapi-rq build: . command: python manage.py rqworker default volumes: - .:/src links: - redis rqscheduler: container_name: projapi-rqscheduler build: . command: python manage.py rqscheduler volumes: - .:/src links: - redis settings.py RQ_QUEUES = { 'default': { 'URL': 'redis://redis/0', } } In the python shell, I ran :do_task.delay() and the RQ Queues' finished jobs jumps up in number by a large amount. When I run: scheduler.schedule(datetime.utcnow(), 'do_task', interval=20), I don't get any response. tasks.py from django_rq import job, get_scheduler from datetime import datetime scheduler = get_scheduler() @job def do_delay_task(): return 'do_delay_task' @job def do_task(): return 'do a task' do_delay_task.delay() scheduler.schedule(datetime.utcnow(), 'do_task', interval=2000) -
Django Admin: Dynamically remove inline fields
I'm trying to dynamically remove an inline if the user doesn't have the specified permission to edit that data. However, the inline only shows up when I'm logged in as a super user. How would I fix this? Currently I'm doing: class ClientAdmin(NestedModelAdmin): """ Admin for Clients. adp_id is only editable if the user has the permission. """ fieldsets = [ (None, {'fields': [('user', 'company', 'external_id',)]}), ] inlines = [EventInline] def get_form(self, request, obj=None, **kwargs): """ Removes the EventInline if user doesn't have the edit_event permission. """ if not request.user.has_perm('app.edit_event'): self.inlines = [] return super(ClientAdmin, self).get_form(request, obj, **kwargs) class EventInline(NestedStackedInline): model = Event fk_name = 'client' ordering = ['completion_time'] fieldsets = [ (None, {'fields': [('training', 'status', 'due_date'), ('authorized_by', 'completion_time'), 'comments']}) ] extra = 0 I want to remove the EventInline from inlines or make all the fields in the EventInline read only. Does anybody have any ideas? -
Why simple Django iterate table has memory leak
I have a simple table in Django project. If doing: for item in mytable.objects.all(): print item It has memory leak like followings: Warning: 64 bytes lost at 0x6421460, allocated by T@0 at @ 0x7f5f0327d075 my_malloc @ 0x7f5f0325ff68 my_multi_malloc @ 0x7f5f0321fe3b mysql_options4 @ 0x7f5f0321e04e set_connect_attributes @ 0x7f5f0321c1df mysql_real_connect @ 0x7f5f192f281b _mysql_ConnectionObject_Initialize @ 0x49ccdf wrap_init Warning: 160 bytes lost at 0x65bc980, allocated by T@0 at @ 0x7f5f0327d075 my_malloc @ 0x7f5f0321a95e mysql_options @ 0x7f5f0321dfa5 set_connect_attributes @ 0x7f5f0321c1df mysql_real_connect @ 0x7f5f192f281b _mysql_ConnectionObject_Initialize @ 0x49ccdf wrap_init Memory lost: 17536 bytes in 15 chunks How to avoid it? -
What are the disadvantages of using AWS ELB directly with Gunicorn (no nginx)?
Typical setups I've found on Google to run a django application on AWS all suggest a setup like ELB -> nginx -> gunicorn -> django I was wondering why the nginx part is really needed here? Isn't ELB sufficient as proxy? In our case, we are running multiple Gunicorn/django instances in individual docker containers on ECS. -
Running makemigrations when using multiple databases
I've set up my Django project to use two databases. One is read-only and other is the "default" django database for the rest of the project. Here are the settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sipf', 'USER': 'myusername', 'PASSWORD': 'secret', 'HOST': '127.0.0.1', 'PORT': '5432', } , 'my_read_only_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_read_only_db', 'USER': 'myusername', 'PASSWORD': 'mypassword', 'HOST': 'remote.host.edu', } } Here is router.py for the read-only DB: class MyReadOnlyDBRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'my_read_only_db': return 'my_read_only_db' return None and for the default DB: class PrimaryRouter(object): def db_for_read(self, model, **hints): return 'default' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): db_list = 'default' if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): return True And finally the routing in settings: DATABASE_ROUTERS = ['my_read_only_db.router.MyReadOnlyDBRouter', 'common.router.PrimaryRouter'] I understand that when running migrate one needs to specify which database to run against like so: $ ./manage.py migrate --database=default However, before even getting that far one needs to run makemigrations. Here, it is clearly attempting to create tables in the read-only database and I'm getting: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to … -
Django: Mark as Read "Notifications"
I'm working on a school project. Right now any user can ask a question. In order to notify all the users when any users asks a question I've created a new app & notifying them through the simple 'view' whenever a question is asked. But it's just plain notifications yet. How can I mark them read once a user opens the Notification tab? Just like on social networks! -
Turning a Page Object Into Its Page Derived Object
I am new to wagtail but I keep running into something that I am sure there is a better solution for than what I am currently doing. Lets say I have a Wagtail Page called ProductPage. Lets say this page has a field that is another ProductPage called related_product. When I try to access this page in my templates or context by the following code, self.related_product it returns a Page object instead of a ProductPage object. Because of this, I cannot get to the fields that I actually want to without transforming it into a ProductPage object by way of, ProductPage.objects.get(page_ptr_id=self.related_product.id) There has to be a way to transform this without this above query. -
Can someone link me to an example site that uses django-filter?
I have found the docs, which are very helpful, but I want to see how it looks in practice. Does anyone know of a tutorial where it is used, or an active site? Thanks! -
Returning Related (1:M) Django Objects with many as a List
I'm new to Django and I'm building a Document Visibility/Status application. Each document, called an "Indent", has some "Attributes", and these attributes have multiple "Status". On the dashboard of the application, I need to dynamically render the attributes as columns, and the statuses as choices in a dropdown list. I'm thinking that I'll need to return a dictionary as follows - but if you have a better suggestion, please let me know. { 1 : ['status1','status2', 'status3'], 2 : ['status1','status2', 'status3'], ... } Where the number is the attribute ID. Here are my models: class Indent(models.Model): dateCreated = models.DateTimeField(auto_now=True) indentNumber = models.CharField(max_length=75) creator = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return '%s' % (self.indentNumber) class Meta: verbose_name = 'Indents' verbose_name_plural = "Indents" class Files(models.Model): fileLink = models.FileField(upload_to='indents/', null=True) #Add 'indents/userID' indent = models.ForeignKey(Indent, on_delete=models.CASCADE) def __str__(self): return '%s' % (self.indent) class Meta: verbose_name = 'Files' verbose_name_plural = "Files" """ TO-DO REMOVE NULL CONSTRAINT """ class Attribute(models.Model): name = models.CharField(max_length=75) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True) def __str__(self): return '%s' % (self.name) class Meta: verbose_name = 'Attributes' verbose_name_plural = "Attributes" """ TO-DO For the names of Status objects, it needs to be more descriptive and accurate """ class Status(models.Model): name = models.CharField(max_length=255) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) … -
Exception Value: no such table: example_post
I have a little issue of trying the exemple file from https://github.com/zhebrak/django-statsy OperationalError at / no such table: example_post Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.11.5 Exception Type: OperationalError Exception Value: no such table: example_post Exception Location: /home/jeremie/.virtualenvs/statsy/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py in execute_sql, line 894 Python Executable: /home/jeremie/.virtualenvs/statsy/bin/python Python Version: 2.7.12 Python Path: ['/home/jeremie/django-statsy', '/home/jeremie/.virtualenvs/statsy/lib/python2.7', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/plat-x86_64-linux-gnu', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/lib-tk', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/lib-old', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/jeremie/.virtualenvs/statsy/local/lib/python2.7/site-packages', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/site-packages', '/home/jeremie/django-statsy'] Server time: Fri, 15 Sep 2017 15:13:34 -0500 Here is what I have done so far : git clone https://github.com/zhebrak/django-statsy.git mkvirtualenv statsy cd django-statsy workon statsy pip install -r requirements.txt python manage.py makemigrations python manage.py migrate python manage.py runserver I just want to enter inside the example to see what type of result and test out the app itself. Why do I have the problem? Do you recommend this app if I am working in a project using Django 1.10 and python 2.7? -
Django get latest "multiple" elements
I have these two models: class SeoKeys(models.Model): keyword = models.TextField(blank=True, null=True) key_nbr = models.IntegerField(blank=True, null=True) status = models.TextField(default='example_keyword', blank=True, null=True) class SeoMetrics(models.Model): parent_key = models.ForeignKey('SeoKeys', on_delete=models.CASCADE) seo_url = models.TextField(blank=True, null=True) url_found = models.TextField(blank=True, null=True) position = models.IntegerField(blank=True, null=True) date = models.DateField(auto_now=True, blank=False, null=False) Now I'm trying to get the latest metrics for each SeoKey, however a SeoKey could have multiple seo_url for each day. In other words I need to get for each SeoKey, the latest SeoUrl(s). The closer I get is with this code: key_status = ['example_keyword', 'deactivated', 'demo'] all_keywords = SeoKeys.objects.all().exclude(status__in = key_status) for key in all_keywords: #print(key.status, key.email) all_metrics = key.seometrics_set.filter(parent_key=key).order_by('parent_key', '-date').distinct('parent_key') for metrics in all_metrics: print('Sending {} for date {} with parent: {}'.format(metrics.seo_url, metrics.date, metrics.parent_key.id)) But it does not include the case that a user has multiple seo_urls. How can I manage to get the latest for a group? -
How customize inline in django admin to show unique entry in the OneToOne field drop down.
class Question(models.Model): question_name = models.TextField(max_length=200) positive_answer = models.PositiveIntegerField(default=2) negative_answer = models.PositiveIntegerField(default=1) added_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) def __unicode__(self): return u'%s' % self.question_name class Task(models.Model): task_name = models.CharField(max_length=100) description = models.TextField(max_length=2000) added_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) def __unicode__(self): return self.task_name class TaskAssignment(models.Model): answer_choice = models.CharField(max_length=5, choices=ANSWER_CHOICES, null=True) question = models.ForeignKey(Question, related_name='%(class)s_requests_created') task = models.OneToOneField(Task, related_name='%(class)s_requests_created') I have these three models. First clients added some task on task admin. After that he is creating questions at the time of question creation he wants to assign some tasks for that question. For this am adding "TaskAssignmnet" model as inline in questions admin. But problem is that with this "task" field shows all tasks in drop downs but my I wants to show only those tasks which are not assigned to question. -
Iterate through JSON data in Django template
I am having trouble iterating through some JSON data that I managed to import into my Django Wagtail project. I want to list travel advisories on a website that are pulled in from here: http://data.international.gc.ca/travel-voyage/index-updated.json I was able to do this in my model like so: import requests def get_context(self, request): response = requests.get('http://data.international.gc.ca/travel-voyage/index-updated.json') json_response = response.json() data = json_response['data'] context = super(TravelAdvisoriesPage, self).get_context(request) context['data'] = data return context I am now unsure of how to get the data into my template. I am able to pull in all of the data using {{ data }}. But how do I pull out specific items from that JSON data? I want to grab both the English and French name, url-slug, advisory-text, etc. And all of those are nested within data > country code > language > item within the JSON structure. I have tried something like: {% for country in data %} {{ data[country].eng.name }}<br /> {% endfor %} This is giving me errors like Could not parse the remainder: '[country].eng.name' from 'data[country].eng.name'. How do you grab these in the template? -
Django page update no ajax or comet
I'm making a small app for internal use between 3 people. the idea is to have a page where user can upload files and data ( more specifically images.) to the database and a second page where the information the user uploaded in the first page will be visible without having to manually refresh the page. I have read about comet and ajax and I think having a function check the Db every certain time is not what I'm looking for. Since there will be almost no updates in the DB. maybe every 3 to 4 months the user might update a new image. -
Include values of different table in django models
I'm trying to check if files reported in one system exist in a different system. The models belong to different tables in different databases. They have no relationship other than the name in common. I'm using django rest framework to serialize the values of one table and I'd like to include the values of the other table in one efficient way. The way I'm currently doing, makes too many queries! My question is: Is there a way to improve this performance issue? Here is an example of what I have //model1 class Product(models.Model): name = models.CharField(max_length=50) //model2 (different database) class Files(models.Model): name = models.CharField(max_length=50) filename = models.CharField(max_length=50) And my view set is class ProductViewSet(viewsets.ModelViewSet): queryset = Inventory.objects.all() serializer_class = ProductSerializer I managed to get the result as I said (not efficiently, though) in two different ways: 1) Including the fields in the serializer class ProductSerializer(serializers.ModelSerializer): has_png = serializers.SerializerMethodField('has_png') has_jpg = serializers.SerializerMethodField('has_jpg') def has_png(self, product): // I wish I could avoid this code duplication too... // I'm basically using the same code in two functions files = Files.objects.filter(name=product.name) filtered_files = files.filter(file_format__startswith='png') return filtered_files.exists() def has_bam(self, product): files = Files.objects.filter(name=product.name) filtered_files = files.filter(file_format__istartswith='jpg') return filtered_files.exists() Meta: model = Product 2) Including properties … -
django-bootstrap3-datetimepicker and Dango 1.11
Nkunihiko django-bootstrap3-datetimepicker looks abandoned and doesn't support for Django 1.11 I see a lot of pull requests to Nkunihiko repo, but they doesn't help. Is where an actual fork or some another django package for bootstrap-datetimepicker? -
Is there any way to build an interactive terminal using Django Channels with it's current limitations?
It seems with Django Channels each time anything happens on the websocket there is no persistent state. Even within the same websocket connection, you can not preserve anything between each call to receive() on a class based consumer. If it can't be serialized into the channel_session, it can't be stored. I assumed that the class based consumer would be persisted for the duration of the web socket connection. What I'm trying to build is a simple terminal emulator, where a shell session would be created when the websocket connects. Read data would be passed as input to the shell and the shell's output would be passed out the websocket. I can not find a way to persist anything between calls to receive(). It seems like they took all the bad things about HTTP and brought them over to websockets. With each call to conenct(), recieve(), and disconnect() the whole Consumer class is reinstantiated. So am I missing something obvious. Can I make another thread and have it read from a Group? -
"Upload" file from disk in Django
I generate a file in python, and want to "upload" that file to the django database. This way it is automatically put inside the media folder, and organized neatly with all other files of my application. Now here is what I tried: # forms.py class UploadForm(forms.ModelForm): class Meta: model = UploadedFile fields = ('document',) # models.py class UploadedFile(models.Model): # mimetype is generated by filename on save mimetype = models.CharField(max_length=255) document = models.FileField(upload_to=get_upload_path) # ... additional fields # views.py, file_out has been generated with open(file_out, 'rb') as local_file: from django.core.files import File form = UploadForm(dict(), {'document': File(local_file)}) print(form.errors) if form.is_valid(): file = form.save(commit=False) # ... set additional fields file.save() form.save_m2m() return file Now this is not the only thing I've tried. First I've gone with setting the FileField directly, but that resulted in the save() to fail, while the mimetype field is set. Because the original file sits outside the media folder, and thus a suspicious file action is triggered. Also, the form gives some feedback about the "upload", through the form.errors. Depending on my approach, either the save() fails as mentioned above -- meaning the "uploading" does not actually copy the file in the media folder -- or the form …