Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom commands, start and stop a python file
I have a Django project which is used to remotely call a python script with predefined arguments (retrieved as a string from database). The python script is designed to loop indefinitely until killed/terminated (and thus I ruled out Popen.communicate() ). I need the script to get called when Django calls the command script, but if it is already running, terminate it and run it again. This is all I have written so far: from django.conf import settings from django.core.management.base import BaseCommand, CommandError import subprocess from LEDs.models import Led mwd="wave" klr="spring" crc=5 p=subprocess.Popen(["python3", "Ledshine.py", mwd,klr,crc]) class Command(BaseCommand): help = 'Executes python script to light up LED' def handle(self, *args, **options): ld = Led.objects.all()[0] mwd= str(ld.mode) klr=str(ld.colour) crc=str(ld.circuit) if p.poll(): p.terminate() #p=subprocess.Popen(["python3", "Ledshine.py", mwd,klr,crc]) -
{"error":"invalid_token","error_description":""} (Podbean api)
I am trying to use Podbean api in my Django application. As per the document provided, I am authenticating my app. I have followed all the steps but when I try to run the following code in terminal I get error: curl -u username:password \ https://api.podbean.com/v1/oauth/debugToken \ -G -d 'access_token=t4dfcgf7eb2ba65a289a6e8a8993cb9785e877y4' Error: {"error":"invalid_token","error_description":""} I have checked all my credentials and they are correct. What is the problem here? -
How to add responsive class dynamically on django-ckeditor using jquery?
hi guys iam making a news website using django and iam having trouble in rendering responsive images which is inserted in django-ckeditor at admin site of django.can any body suggest me what might be the issue,following are my code. template html: <div id="modal1" class="modal bottom-sheet"> <div class="modal-content"> <h4 >{{article.title}}</h4> <div> <img class=" center-align responsive-img" src="{{ article.thumbnail }}"> <p class="articlebody">{{article.body|safe}}</p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat">Agree</a> </div> </div> base.html: $(document).ready(function(){ $('.articlebody img').each(function(){ $(this).addClass('responsive-img'); }); }); </script>> Iam trying to add the materializecss framework "responsive-img" class using jquery.but i dont see the effct on my template.The images inserted in cKeditor is still not responsive.Please help guys.iam new to web development. -
colorful.core.ColorfulError: the color "default" is unknown. Use a color in your color palette (by default: X11 rgb.txt)
I installed the colorful into my django project and I added it to installed_apps in settings.py I added an RGBColorField to my modal. When I do python manage.py makemigrations I get the following error: colorful.core.ColorfulError: the color "default" is unknown. Use a color in your color palette (by default: X11 rgb.txt) my modals.py from __future__ import unicode_literals from colorful.fields import RGBColorField from django.db import models class Party(models.Model): name = models.CharField(max_length=100) color = RGBColorField(default="#0000") I also tried with color = RGBColorField("#0000") and color = RGBColorField() but always the same error -
Connect HTML5 drag and drop with Django view
Hi I'm trying to use HTML5 drag and drop and I'm wondering if there is a way to connect django view with event of object being dropped. Something that would in the end look like this: template.html: {% extends "app/layout.html" %} {% block content %} <div class="row"> <div ondrop="dropa(event)" ondragover="allowDrop(event)" class="col-md-2"> Change category to A </div> <div ondrop="dropb(event)" ondragover="allowDrop(event)" class="col-md-2"> Change category to B </div> </div> <div class="col-md-8"> {% for object in objects %} <div draggable="true" class="row"> {{object.title}} </div> </div> {% endblock %} <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function dropa(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); somehow call object_editA() } function dropb(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); somehow call object_editB() } </script> views.py: def object_editA(request, pk): object= get_object_or_404(Object, pk=pk) object.category = "A" object.save() return redirect('object_list') def object_editB(request, pk): object= get_object_or_404(Object, pk=pk) object.category = "B" object.save() return redirect('object_list') Is something like this possible? I expect that it is needed to change the drag and drop function but I have no idea how or where to find any help/documentation for it. Can anyone help me? Thanks -
Remove object from Django query list in for
I would like to exclude some objects from a query list based on a number of checks - the first a simple for loop that checks if each item has 'expired'. However, when ever I do this, it returns all objects. now = datetime.datetime.now() food = Food.objects.filter(user=self.user, in_cupboard=True) for f in food: if (f.cupboard.close_date + timedelta(days=1)) < now: f.exclude(pk=f.id) What is the correct way to 'filter' objects using a for list? -
Can't connect to local MySQL, issue with socket
I try to make a backup of database with script in my django project. Here is my code: DUMPFILE = os.path.join(settings.BASE_DIR, 'backup', '%s.mysql.gz' % settings.DATABASE_NAME) res = commands.getoutput('mysqldump -p%s %s | gzip > %s' % (settings.DATABASE_PASSWORD, settings.DATABASE_NAME, DUMPFILE)) print res DUMPFILE = os.path.join(settings.BASE_DIR, 'backup', 'project_next.mysql.gz') res = commands.getoutput('mysqldump -p%s project | gzip > %s' % (settings.DATABASE_PASSWORD, DUMPFILE)) print res But I got an error: Got error: 2002: "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2 "No such file or directory")" Please for help with this. -
What's the python file to startup multiple celery worker?
When I am running the following code python manage.py celery -A test worker -l info -Q test -n test.%h It will kick off multiple python process to work as workers, I'd like to check the code how it kick off multiple process and how different process communicate with each other. But I check project of django, celery and django-celery, and don't know which file I should look at. -
not found css when use Django with Apache and mod_wsgi in linux
Here is my Project structure So the project mystie and its two apps blog and polls. The inverment:python2.7+wsgi4.5+django1.11+linux. I was build the Django with Apache and mod_wsgi.It works well in some way except the "not found css" ,and I did some work as follow step 1: I found the file httpd.conf in apache and append "Alias /static/ PATH/mysite/static/". this is base situation and not found css. (1.localhost:port/admin not found) (2.localhost:port/polls not found) (3.localhost:port/blog not found) Step2: rebuild the path like "Alias /static/ PATH/mysite/polls/static/". the polls apps works well.the blog app still bad. (1.localhost:port/admin not found) (2.localhost:port/polls OK) (3.localhost:port/blog not found) step3 ; and I move the admin css from Lib\site-packages\django to polls\static . (localhost:port/admin)works well. So I was wondering how to build multi apps in one project. how to set the static path in case the different apps find their own css. and in my own ways,I have to put the admin css in every apps,should I? any suggestion? -
Displaying foreign model fields in django admin as editable
I have a Django Model with a Foreign key: class Library: name=models.CharField() class Book: title=models.CharField() library=models.ForeignKey(Library) models.py In the admin, I want to display Book and show an editable field for Library.name in the Book view (not the other way around with inlines): > Book * Title: "Foo" * Library Name: "Bar" As readonly, it's easy (just creating a method in Book model returning the library name value) but I cannot make it work for editable fields, I tried using fields=('title','library.name') and fields=('title','library__name') without success -
Send only new values within ajax put request
I want to update a Django model instance using ajax PUT request and a Django REST API . What I want to do is to send only the values that will be updated within the PUT request. I used a Jquery DataForm object. But I get an error saying that there are required fields that can not be empty. Is there a way to indicate that those fields should keep their old values ? Thank you for your help. -
transform a list of similar dictionaries into a list of dictionaries containing lists
I've got this serialized data (django rest framework) as a result from a query i made with django, which i'm using as backend for my project: i_have = [ {'product_name': 'Foo', 'role': 'aRole', 'user_name': 'foobar'}, {'product_name': 'Foo', 'role': 'anotherRole', 'user_name': 'foobar'}, {'product_name': 'Bar', 'role': 'aRole', 'user_name': 'foobar'}, {'product_name': 'Bar', 'role': 'anotherRole', 'user_name': 'foobar'}, ] For my client, written in JavaScript and React i would like to transform the data into: i_want = [ {'product_name': 'Foo', 'roles': ['aRole', 'anotherRole'], 'user_name': 'foobar'}, {'product_name': 'Bar', 'roles': ['aRole', 'anotherRole'], 'user_name': 'foobar'}, ] I'm currently getting the data with a query which looks similar to this (pseudocode) AUserProduct.objects.filter(user_name='foobar').order_by('product_name') while my models basically looks like this (also pseudocode) Product(models.Model): product_name = models.CharField(max_length=255) AUser(models.Model): user_name = models.CharField(max_length=255) AUserProduct(models.Model): product_name = models.ForeignKey('Product') user_name = models.ForeignKey('AUser') role = models.CharField(max_length=255, choices=('aRole', 'anotherRole')) Is there any way of achieving this with a django query? Would it change anything in the result if i put the roles in a seperate table and add a foreign key relationship from AUserProduct to the Role Table? Or do i have to iterate through the data and pick the role and append it to a new dictionary which contains the desired list with roles? And if … -
How can I display the data from a foreign table in a table cell using django-tables2 (custom table)?
The value on the table cell is empty. This column contains the data from foreign table. Here is the snippet of my models. model.py class DailyRecord(models.Model): date_organised = models.DateField('Ogransied Date', help_text=('Enter Date when the program is organised: CCYY-MM-DD')) program_name = models.TextField('program name',) venue = models.CharField('venue', max_length = 255, blank=True) organiser = models.ForeignKey(Organiser, verbose_name = 'Organiser', related_name = 'organisers') objects = models.Manager() public = DailyRecordManager() class Meta: verbose_name = 'dailyrecord' verbose_name_plural = 'dailyrecords' ordering = ['-date_organised'] def __str__(self): return self.program_name.encode('ascii', errors='replace') class Participant(models.Model): participant = models.CharField(max_length= 50) daily_record = models.ForeignKey(DailyRecord, verbose_name = 'program_name', related_name = 'participant_set') class Meta: verbose_name = 'participant' verbose_name_plural = 'participants' def __str__(self): return self.participant.encode('ascii', errors='replace') This is class on table to display custom table. below is the snippet tables.py class DailyRecordTable(tables.Table): date_organised = tables.Column('Date') program_name = tables.Column( 'Program Name') venue = tables.Column('Venue') organiser = tables.Column( 'Organiser') participant = tables.Column(accessor='participant.participant') class Meta: model = DailyRecord This is my Generic Views for displaying table. views.py class DailyActivityPageView(SingleTableView): queryset = DailyRecord.public.prefetch_related('participant_set').all() table = DailyRecordTable(queryset) template_name = 'dailyrecord/daily-activity-record.html' def get(self, request): RequestConfig(request).configure(self.table) return render(request, self.template_name, {'table': self.table, 'ziptable':self.ziptable,'data' : self.data}) data.html <tbody> {% for row in table.page.object.list|default:table.rows %} {# support pagination #} {% block table.tbody.row %} <tr {{ row.attrs.as_html }}> {% … -
python virtualenv not working after setting path
So I installed Python 3.6 and set the environment path to it like: C:\Users\danny\AppData\Local\Programs\Python\Python36-32\ . When I try to create a virtual environment (e.g. virtualenv Venv) it is not working. I get the error: The term 'virtualenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. The path is set correctly, I don't know what is wrong. -
jQuery-Fileupload & Django
tldr: My file upload response is a HTML text, while JSON is expected, which is why I get a parsing error and the upload fails. Where/How does this error occur and how can I fix it? The longer version: I'm trying to integrate the jQuery-Fileupload into an existing Django app, but don't understand much about the automatic form creations by Django nor have I ever worked with jQuery or Ajax before. To see if I could get it running without understanding, first I cloned this git repo (https://github.com/sigurdga/django-jquery-file-upload) and added it as a separate app to my existing Django project. Everything worked fine and I was able to upload files. As for my existing app: I'm using a grid layout - and one of the cells already contains a working form. The others are more or less empty and I want to add the file upload into one of the empty ones. When I copied all the stuff from one app to the other, on loading the html-page everything looks good (no errors on either python nor browser console), I can choose files and display the upload queue. But when I start the upload process I get an error, where … -
Why am I getting NoReverseMatch at /blog/ in Django
I am currently following the book "Django by Example" and at chapter 1: Building a blog application, I am getting the following error when I try to access 127.0.0.1:8000/blog/ NoReverseMatch at /blog/ Reverse for 'post_detail' with arguments '(2017, '08', '03', 'new-title')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/(?P\d{4})/(?P\d{2})/(?P\d{2})/^(?P[-\w]+) /$'] Here is my templates/blog/base.html file {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %} {% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id = "content"> {% block content %} {% endblock %} </div> <div id = "sidebar"> <h2> My Blog</h2> <p> This is my blog </p> </div> </body> </html> and my templates/blog/post/list.html file {% extends "blog/base.html" %} {% block title %}My Blog {% endblock %} {% block content %} <h1> My Blog </h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} I cannot seem to find what is wrong, so I would appreciate your assistance. In case it helps, I am using Django 1.8.6 and Python 3.6.2 with virtualenvwrapper on a Linux system. -
how can i make search algorithem in django it provide user best search results
how can i make proper search algorithem that fullfield user search result and give them most relevent result please i tried object Q() but it's not good enough and also sometime it's slow for search how can i search fast as possible and come with the most perfact result can anyone please help me. -
Django Crispy forms "add new thing" button for field
I'm making a form using crispy forms, and I'm wondering if they is a way of adding an add button next to a field, similar to what django-admin does. I currently have a drop down list which requires something to be in it, and if it is empty, I want to be able to open up another form to add that element. -
Django loop through an object and create another with relationship
Ok. This is quite strange or I am missing something fundamentally important in the looping objects business. I have three objects, let's say they are fruits, basket, and fruit basket. I also would like to record the action of putting or taking fruit from the basket. for models: class BasketFruit(models.Model): """ A fruit within a basket. """ basket = models.ForeignKey(Basket, related_name='fruit_basket') fruit = models.ForeignKey(Fruit) number_owned = models.IntegerField() class Meta: unique_together = (("basket", "fruit"),) class Fruit(models.Model): name = models.CharField(max_length = 250) class Basket(models.Model): name = mdoels.CharField(max_length =250) class Operation(models.Model): expired = models.BooleanField() The goal is to loop through all baskets and take out the a basket fruit and check if it is expired. I have a function to check def expired() which I know it is good. Now I want to record expired into class Operation while looping through each basket. In my views I have this: def record_expiration(): baskets = list(Basket.objects.all()) for basket in baskets: fruits_in_basket = basket.fruist_basket.all() for fruits in fruits_in_basket: numbers = fruits.number_owned if numbers != 0: names.append(fruit.fruit.name) expired = map(lampda name:expired(name), names) for expired in expired: if expired ==True: Operation.objects.create(fruitbasket = fruits, expired = expired) return fruits Strangely only one basket and one basket fruit in it … -
Periodical task Django: Celerity vs Javascript/jQuery
I know that that there are question about "how to make periodical task in Django" like this post. But I'm wondering which would be best option, to use one from the optiones mentioned in that post (Celerity or cron mostly) or dealing the periodical task from the Javascript/jQuery. What I want to accomplish is to simply execute a task every day. To call a function from the "view.py". That function will connect to an URL, download a file and search in that file for information and then store it in the database. After that, refresh the homepage with the new information. Which would be the pros and cons? -
Django FileField unix permissions on uploaded files
I have a django project and users need to upload a file into FileField. Everything works like a charm except the file permission on the unix server side. Newly created files have permission 0600 which makes it impossible to server the files via nginx, as it's running under different user. Django is working via gunicorn: I have 'umask': 022 in gunicorn configuration I have umask 022 set in user profile and active root session from which I start gunicorn I have no code to change file permission from django side If I run it from CLI with ./manage.py runserver it's working correct and sets 644 as expected Did I miss something in django / gunicorn configuration? What else do I have to check? PS. Full gunicorn config: CONFIG = { 'mode': 'wsgi', 'environment': { 'PYTHONPATH': '/home/user/www/project/.env/lib/python2.7/site-packages', }, 'working_dir': '/home/user/www/project', 'user': 'user', 'group': 'user', 'umask': 022, 'args': ( '--bind=127.0.0.1:31337', '--workers=4', '--timeout=60', 'project.wsgi', ), } -
Using django-rest-elasticsearch
Following this documentation, I have managed to get an API endpoint that gets data from elasticsearch. My problem is that the data fetched comes from all the types in an index whereas I would like to get the data from one specific type from the index -
I can not create a post request include crsf in angularjs
I will post data to django app,I use angularjs http to post.when i post data,i get a 403 forbidden.so I change MY angular script to this: var app = angular.module('omCenterLoginApp',['ngCookies']); app.config(['$httpProvider', function ($httpProvider,$cookies) { $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.xsrfCookieName = 'csrftoken'; }]) app.controller('omCenterLoginContr',function($scope,$http){ $scope.login = function(){ var user = $scope.username; var password = $scope.password; $http({ method: 'POST', url:'http://172.100.0.48:8080/api/test/', data:{user:password}, }).then(function successCallback(response){ console.log(response.data) },function errorCallback(response){ console.log(response.data) }) } }); I add $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.xsrfCookieName = 'csrftoken'; but,I when i post ,it still response a 403 error. I check the post http header,There is no X-CSRFToken in it Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate Accept-Language:zh-CN,zh;q=0.8,en;q=0.6 Cache-Control:no-cache Connection:keep-alive Content-Length:2 Content-Type:application/json;charset=UTF-8 Host:172.100.1.8:8080 Origin:http://172.100.1.8 Pragma:no-cache Referer:http://172.100.1.8/login.html? User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 who can help me ? -
Python web app with git
I need to write web app which should communicate with gitlab repo (change files, making new branches ...). What is the best solution: use git API or use a command line with subprocess (I am afraid it could not be possible in web app without building my own command line) or to use the gitPython or similar (some of them are based on subprocess as well). -
How to use bootstrap login form to authenticate django users
I'm building my very first Django web application and there's one issue that I can't seem to find a solution for. My homepage (index.html) is bootstrap-based and it displays some text together with a bootstrap log in form. What is the correct way to allow Django authentication from that bootstrap login form? I've tried solutions based on suggestions found here and there on the internet, but I keep getting errors. Here's my code: Inside index.html <div class="inner cover"> <h1 class="cover-heading">Admin Interface</h1> <p class="lead">Welcome to your dedicated Admin Interface.<br>Log in to access your dashboard and control panel.</p> <form class="form-signin"> <label for="inputEmail" class="sr-only">Email address</label> <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="Password" required> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form> </div> Inside myapp/urls.py from django.conf.urls import include, url from user import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', views.index, name='index'), ] Inside my main urls.py from django.conf.urls import include from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('user.urls')), ] I tried adding form method="post" action="{% url 'django.contrib.auth.views.login' %} but …