Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery 4.0.0 + SQS -> "Credential should be scoped to a valid region, not 'queue'."
I am running Celery with SQS in Django application: When I am specifying region in broker settings like: CELERY_BROKER_URL = 'sqs://' CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': 'eu-west-1', 'polling_interval': 3, 'visibility_timeout': 300, 'queue_name_prefix':'dev-celery-', } I can see queues created in Amazon SQS but at the same time I have following error when I try to launch worker. [2016-12-09 16:06:41,206: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... Traceback (most recent call last): File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", line 584, in start c.loop(*c.loop_args()) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/celery/worker/loops.py", line 88, in asynloop next(loop) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/kombu/async/hub.py", line 345, in create_loop cb(*cbargs) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/kombu/async/http/curl.py", line 111, in on_readable return self._on_event(fd, _pycurl.CSELECT_IN) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/kombu/async/http/curl.py", line 124, in _on_event self._process_pending_requests() File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/kombu/async/http/curl.py", line 130, in _process_pending_requests self._process(curl) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/kombu/async/http/curl.py", line 178, in _process buffer=buffer, effective_url=effective_url, error=error, File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/vine/promises.py", line 146, in call svpending(*ca, **ck) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/vine/promises.py", line 139, in call return self.throw() File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/vine/promises.py", line 136, in call retval = fun(*final_args, **final_kwargs) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/vine/funtools.py", line 100, in _transback return callback(ret) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/vine/promises.py", line 139, in call return self.throw() File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/vine/promises.py", line 136, in call retval = fun(*final_args, **final_kwargs) File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/vine/funtools.py", line 98, in _transback callback.throw() File … -
Django Query, filter by user group
The below code returns a list of the users groups admins = User.objects.all() for i in admins: print i.groups.all().values_list('name', flat=True) and i want to get all users that are in the group 'App_Admin', so i need something like the below, but obviously a query that works, the below churns out "invalid syntax" admins = User.objects.filter(groups.all().values_list('name', flat=True)__in='App_Admin') -
First row with two items second one and next with three
I have model (Event) and I want to have template with two ways to display items. First row have to include two items, with special styling Second one and next have to include three, with special styling How can I do this with loop? -
Django : improve performance on multiple uploads
I am working on a API to upload files from client to server. Each file from the client side need to be copied to server side. <input type="file" id="id_docfile" name="docfile" multiple> Is there a better way to upload files so that the uploading time can be reduced ? Can I upload files in parallel ? -
NGINX sometimes has (No such file or directory) error
After sometime my nginx server will have an error regarding static files, I'm using NGINX in one server that serve static files and as proxy for Django app on another server. I copies the static files from the Django server to NGINX server, and run ./manage.py collectstatic command. error.log 2016/12/07 20:36:17 [error] 26548#0: *1359 open() "/home/ws-admin/foo/media/branches/gmap__ndaUhjI.jpg" failed (2: No such file or directory), client: x.x.x.x, server: _, request: "GET /media/branches/gmap__ndaUhjI.jpg HTTP/1.1", host: "www.foo.com", referrer: "http://www.foo.com/" nginx.conf user ws-admin; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } # TCP/UDP proxy and load balancing block # #stream { # Example configuration for TCP load balancing #upstream stream_backend { # zone tcp_servers 64k; # server backend1.example.com:12345; # server backend2.example.com:12345; #} #server { # listen 12345; # status_zone tcp_server; # proxy_pass stream_backend; #} #} sites-enabled/foo upstream app_server { server x.x.x.x:8000 fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your … -
__init__() got an unexpected keyword argument 'use_required_attribute'
I am using django package workflow -status. Have installed it. While Migrate got an error - TypeError at /workflow/workflow/add/ init() got an unexpected keyword argument 'use_required_attribute' -
Django - How should be the customer admin area?
I have some doubts regarding the django adm approach. Assuming I'm building a product sales website for a company, soon I will not be the site administrator, and will probably be someone without Django knowledge. In this case, what is it like to do? Is the admin of the Django adm site with an improved interface delivered to the future administrator, or is an administration page with a great interface created? If the answer is to create a new interface, is there a package that helps us read the DB (as in django admin)? My question is if I would have to create all the querysets to get statistics, list of objects, list of users ... Note: I am admin of a site that a programmer did using PHP, he told me that the interface I use was made using a paid framework that took the DB data and it only had to customize the display. Thank you ! -
Python/ Django- Internal Server Error after performing a soft reset
I recently made some changes to my Python/ Django project, and this caused one of the pages to display a 'Bad Gateway' message in the browser. I was unable to resolve this, so tried doing a 'soft reset' to the last working commit I had made. However, I am now getting an Internal Server Error when trying to view the website on the live server. The error message doesn't give any more information than this... but when I view my project locally in the browser, it works as expected. I've tried committing my local version, pushing it to the server, and then pulling it on the server again, but on the master branch on my local machine and on the server, I get a message telling that there's "nothing to commit, working directory clean". How can I resolve this Internal Server Error to ensure that my site is accessible again? -
Python Django Testing
class ProjectTests(APITestCase): def test_carete_category(self): #Category test case url = reverse('category') data = {'category_name': 'Branch', 'category_id': 1 } response = self.client.post(url, data, format='json') request = self.client.get(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(request.status_code, status.HTTP_200_OK) self.assertEqual(Category.objects.count(), 1) self.assertEqual(Category.objects.get().category_name, 'Branch') category_id = Category.objects.get().id print(response) print (category_id) return category_id def test_carete_sub_category(self): category_id = Category.objects.get().id url = reverse('sub_category') data1 = {'sub_category_name': 'IT', 'category': category_id } response = self.client.post(url, data1, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED ) self.assertEqual(Sub_category.objects.count(), 1) self.assertEqual(Sub_category.objects.get().sub_category_name, 'IT') print("Sub_categoryTests2") print(response) when I run this testcase it showing me error. DoesNotExist: Sub_category matching query does not exist. How can I pass my Category_id to sub_category. Please help me asap -
Mezzanine base urls.py location?
I'm a Django newbie and looking at Mezzanine CMS and looked at all URLs, can somebody point where http://127.0.0.1:8000/about/ is defined, what urls.py, I'm guessing it is urlpatterns = [ url("^(?P<slug>.*)%s$" % ("/" if settings.APPEND_SLASH else ""), views.page, name="page"), ] is that correct? -
Asp.NET Core Content Type Table like in Django Admin for Permission handling
I am building a we application and i need something similar to the Content type table in django to deal with permissions in ASP.net core. What i want to do is to track the controllers and actions in my code and link permissions to them. I need this to be dynamic since i intend to abstract this function in a way to let admins of the application assign (action-like) permissions to user. Like in django admin Admins Users will be able to specify what users or groups can do (which will translate to what actions they can access). This is how i intend to use ASP.NET's Claims bases authorization in custom policies. I am I wrong in my approach...is there something am missing? -
ForeignKey or ManyToMany - When to use? Which version is better?
ForeignKey or ManyToMany - When to use? I wonder which version is better. REJECTED = 1 SUBMITTED = 2 APPROVED = 3 HISTORY_CHOICES = ( REJECTED, "Rejected", SUBMITTED, "Submitted", APPROVED, "Approved", ) class InvoiceHistory(TimeStampedModel) user = models.ForeignKey(settings.AUTH_USER_MODEL) action = models.IntegerField(choices=HISTORY_CHOICES) class Invoice(models.Model): number = models.CharField(...) history = models.ManyToManyField(InvoiceHistory) or version with ForeignKey: class Invoice(models.Model): number = models.CharField(...) class InvoiceHistory(TimeStampedModel) user = models.ForeignKey(settings.AUTH_USER_MODEL) action = models.IntegerField(choices=HISTORY_CHOICES) invoice = models.ForeignKey(Invoice) -
Django Query using contains with a list as a source?
I have a list of postcodes for example:- postcodes = ['LDN 4DN','MAN 4RF'] Im using site = SiteData.objects.filter(address__icontains=postcodes[0])) In a loop to get each site, but that seems a bit lengthy, is it possible to do contains in? __icontains__in=postcodes? -
Django CMS user can't have permissions to add plugins
I've got a Django-CMS site where I created a Articles model to add news, events and other material. This model has a content field which is a PlaceholderField so users can add the plugins they want to each article. The problem is that I created a user without superuser status but give him all the permissions that appear when I create/edit users. But this user can't add plugins to this model. He can add plugins to cms pages, but not to this model. Do I need to create some kind of permission for this case? How do I do it? My model: class Articles(models.Model): objects = ArticlesManager() id = models.AutoField(db_column='ID', primary_key=True) sites = models.ManyToManyField(Site, verbose_name=_(u'Show in Sites'), related_name='articles_to_show') type = models.ForeignKey('Types', db_column='TYPE_ID', related_name='type', verbose_name=_(u'Type')) content = PlaceholderField('ipp_article_content', related_name='IPP_ARTICLE_CONTENT') class Meta: app_label = 'cms_ipportalegre' db_table = 'ipp_articles' verbose_name = _(u'Article') verbose_name_plural = _(u'Articles') permissions = ( ("view_articles", _(u"Can view Articles")), ) And in my template: <p>{% render_placeholder object.content language placeholder_language %}</p> -
Making call to django web server causes Error 500
I am having an iPad application that does calls to a django server to get data. On the production server calls work just fine, but when I move app to make calls to development server I get an 500 server error(since iPad app works while making calls to production server, I suspect that the problem is on the development server). Since I'm very new in this technology(Djnago) I don't know what code/logs should I provide or what should I do. Any clue on how can I debug that would be welcomed(also, I can provide anything that might help). -
D3 not loading JSON from API
I'm having a problem loading JSON from an internal API. I'm using D3, Django and Tastypie to build the API. This is the code I'm using in javascript: var data; d3.json("/api/order", function(error, json) { data = json; console.log(error); }); The strange thing is that this doesn't work when loading the page, but if I run the code in the console, it does return the right data. -
How to protect python app distributing using docker containers? [duplicate]
This question already has an answer here: How do I protect Python code? 23 answers We are developing application using Python/Django and going to distribute it with Docker. Some percent of clients want to have "local" version deployed on theirs own servers. We understand that python is not compiled programming language and it is impossible to protect absolutely anything. But we want to save our code from getting broken and stolen by middle-level system administratrator. Also we want to control number of paid user accounts in application. How to protect application from creating user account without paying in this situation? How to make changing and stealing our code as difficult as possible? Can you give us some helpfull advice? -
manage.py check fails upon connecting to local mysql database
I have a brand new Django project. It only contains the bare minimum after a "django-admin startproject" call. Everything is fine, but the moment I add my database settings to it, "python manage.py check" starts failing. To be more precised, it fails on "python manage.py check --tag models" Here are my settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myschema', 'USER': 'root', 'PASSWORD': 'mysqlroot', 'HOST': '127.0.0.1', 'PORT': '33060', } } I get the following error: Process finished with exit code -1073741819 (0xC0000005) Please note that it seems that the issue only happens if the connection to the database is successful. If I put wrong information in the settings or if the server is not running, I will have the usual django error message. Any idea? Ever saw something similar? -
Show items in one template with different styling in django
I have problem with template in my django app (1.8). I want to display item with video, on first place - that is ok, than I want to have small box - I thnik this is also ok. Here starts a problem I want to have bottom container (<div class="grid-module three-cols">) with rest of the item, but one of them is simialr to secound one (<div class="worldwide small">). I do not how use the loop to solve this porblem. Below is my html code: {% if article_list %} {% for i in article_list %} {% if i.is_video_online %} <div class="grid-module"> <div class="grid-worldwide"> <div class="worldwide large"> <a href="{{ i.get_absolute_url }}" class="link-box"> <img src="{{ i.image.url }}" alt="" /> <div class="text-box"> <div class="row collapse"> <div class="large-12 columns"> <p class="sub-head">Live from{{ i.livestream_from|date:'d.m.Y' }}</p> <h3>{{ i.title }}</h3> <p class="sup-head">{{ i.short_text|truncatewords:30 }}</p> </div> </div> </div> </a> </div> {% elif i.livestream_from %} <div class="worldwide small"> <a href="{{ i.get_absolute_url }}" class="link-box"> <img src="{{ i.image.url }}" alt="" /> <div class="text-box"> <p class="sub-head">Live from {{ i.livestream_from|date:'d.m.Y' }}</p> <h3>{{ i.title }}</h3> </div> </a> </div> </div> </div> <div class="grid-module three-cols"> <div class="grid"> {% elif i.livestream_from %} <div class="worldwide small other"> <a href="{{ i.get_absolute_url }}" class="link-box"> <img src="{{ i.image.url }}" alt="" /> <div … -
Django foreign key model with nested many-to-many with through class
In my app, I would need to have: 1 quote can be associated to one product (foreign key) 1 product can be associated with many parameters (many to many) The parameters of each product need to be given a value for each quote, so I used a 'through' relationship in the many to many declaration by adding a text field to get a default value However, it's not what I want to do, as I need to set the 'value' for each parameter of the product in the quote (and overriding the default value defined in the product). My question is: How do I need to adapt the models and/or relationships so I can add the value of the parameter directly in the quote ? And once it's done, how can I reflect this in the admin ? Here are concerned code parts of the models: class Quote(models.Model): product= models.ForeignKey("Product") class Product(models.Model): params = models.ManyToManyField(ProductParameter, related_name='productparams', through='ProductParameterInProduct') class ProductParameterInProduct(models.Model): product = models.ForeignKey(Product) productparam = models.ForeignKey(ProductParameter) defaultvalue = models.CharField("Default Value", max_length=250, blank=True, null=True) Thanks a lot for your help ! -
How to optimize this specific Queryset?
In a Django application, I have a set of companies with a history of actions that have been performed in the past. I retrieve those transactions with the following, scandalously expensive Queryset: class Company(AbstractBaseUser, PermissionsMixin): ... @property def history(self): return Transaction.objects.filter(sponsorship__campaign__shop__company=self) Obviously, this leads to a lot of JOIN instructions from the ORM and since the number of Transactions can increase rapidly, the throughput on the db is also exploding because of this Queryset. Assuming there is no shortcut between Transaction and Company other than chaining through Sponsorship, Campaign and Shop as exposed above, how would you optimize the Queryset without touching at the database schema? -
Git pull not possible because of unmerged files
I have just tried replacing the master branch on my server with another branch, as the master was broken, and I couldn't seem to resolve the error... The branch that I replaced it with is the last working version I had. I did this by running the following commands from my local machine: git checkout lastWorkingBranch git merge -s ours master git checkout master git merge lastWorkingBranch master git push origin master Then, on the server, I ran git pull origin master However, this gave the following output: Pull is not possible because you have unmerged files. Please, fix them up in the work tree, and then use 'git add/rm <file>' as appropriate to mark resolution, or use 'git commit -a'. root@moon:/code/moon# git stash costing/views.py: needs merge tools.py: needs merge costing/views.py: needs merge tools.py: needs merge costing/views.py: unmerged (395725168ffab1962655116880b74158de3e1e56) costing/views.py: unmerged (95ff89d4160135c2ebefd67a0fc1af2f2a0abc74) costing/views.py: unmerged (902f9ff57c808cefd074f3ea07fb252f9eedb4e2) tools.py: unmerged (6832dd3197f838a52396381c30ef55069e24411b) tools.py: unmerged (24e8179f7689ffacdd50407259f3a12b3d3f609a) tools.py: unmerged (93b3d0baa5f1b75c85120cc2e7cab7dcd949b9a5) fatal: git-write-tree: error building trees Cannot save the current index state I tried committing & pushing again on my local machine, and then ran a pull again on the server, and now get the following message: U costing/views.py U tools.py Pull is not possible because you … -
Django ORM annotation on prefetch_related
How can I annotate a related model during prefetch_related query? I have two models: class Foo(models.Model): ... class Bar(models.Model): foos = models.ManyToManyField(Foo, related_name="bars") I want to retrieve in a single query Foo objects, the Bar objects related to each one and number of Foos each Bar object has. I am trying to accomplish it with the following query: Foo.objects.all().prefetch_related( Prefetch("bars", queryset=Bar.objects.all().annotate(bars_count=Count("bar"))) ) But I get an SQL error: OperationalError at /concerts/coldplay-en-madrid/ (1055, "Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'bar.foo_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by") -
CSS DJANGO and extended templates
I've loaded bootstrap into my base.html template which extends all my other templates <!DOCTYPE HTML> {% load staticfiles %} {% load render_table from django_tables2 %} <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/portal.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'django_tables2/themes/paleblue/css/screen.css' %}" /> <html> <title> {% block title %}Test Portal{% endblock %} </title> <head> <div class="page-header"> <img src="{% static 'images/gd_logo_lg.jpg' %}" alt="GDLOGO" style="width:245;height:125px;"/> <div id="righty"> <h1><a href="/home/">GD Portal</a></h1> </div> </div> </head> <body> <div class="content container"> {% block content %} {% endblock %} </div> </body> </html> only some css works from my css file, css/portal.css, I've tried looking online but everything I've tried doesn't work. .page-header { background-size: cover; background-repeat: no-repeat; background-color: #932D42; margin-top: 0; padding: 10px 40px 20px 40px; } .page-header img { position:absolute; top:0px; left:0px; } .righty { float:right: } .page-header h1, .page-header h1 a, .page-header h1 a:visited, .page-header h1 a:active { color: #ffffff; font-size: 32pt; font-family: "Courier New", monospace; font-weight: bold; text-decoration: none; h1, h2, h3, h4 { font-family: 'Impact', Sans-serif; } for instance, page-header works fine I can change that and do what I want, but righty doesn't have any affect what so ever. Any css I try in my extended templates also doesn't work. … -
Dockerized Django with webpackDevServer
I need some help with a Docker configuration to make Django work with webpack dev server in development mode. I want django docker container to get access to the webpack generated bundle. I'm struggling to understand how containers share files with volumes in docker-compose. Until now I only managed to have a working django dockerized app and then I run npm install && node server.js locally. Dockerfile # use base python image with python 2.7 FROM python:2.7 ENV PYTHONUNBUFFERED 1 # set working directory to /code/ RUN mkdir /code WORKDIR /code # add requirements.txt to the image ADD requirements.txt /code/ # install python dependencies RUN pip install -r requirements.txt ADD . /code/ # Port to expose EXPOSE 8000 docker-compose.yml version: '2' services: db: image: postgres redis: image: redis rabbitmq: image: rabbitmq:3-management ports: - "5672:5672" # we forward this port because it's useful for debugging - "15672:15672" # here, we can access rabbitmq management plugin worker: build: . command: celery worker -A example -l info volumes: - .:/code links: - db - rabbitmq - redis web: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code - ./assets/bundles:/webpack (here I'm trying in some way to address webpack files …