Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Build the same image multiple times with different entrypoints in Docker
I have a Django app and use Celery for background tasks. For deploying, I use Docker with Kubernetes. Deployment is automatized with Jenkins. All is good, however I feel like this can be drastically optimized. The problem is that Jenkins builds almost the same images for a django app and 5 celery workers. The only difference they have is the entry point. Django app image starts gunicorn, celery container starts, well, celery. What is the best practice to build almost the same images? I would optimally like to build the same image several times and indicate the entrypoint during the build process. Thank you for any help. -
Celery Async Tasks and Periodic Tasks together
Unable to run periodic tasks along with asynchronous tasks together. Although, if I comment out the periodic task, asynchronous tasks are executed fine, else asynchronous tasks are stuck. Running: celery==4.0.2, Django==2.0, django-celery-beat==1.1.0, django-celery-results==1.0.1 Referred: https://github.com/celery/celery/issues/4184 to choose celery==4.0.2 version, as it seems to work. Seems to be a known issue https://github.com/celery/django-celery-beat/issues/27 I've also done some digging the ONLY way I've found to get it back to normal is to remove all periodic tasks and restart celery beat. ~ rh0dium celery.py import django import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bid.settings') # Setup django project django.setup() app = Celery('bid') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() settings.py INSTALLED_APPS = ( ... 'django_celery_results', 'django_celery_beat', ) # Celery related settings CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 43200, } CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_CONTENT_ENCODING = 'utf-8' CELERY_ENABLE_REMOTE_CONTROL = False CELERY_SEND_EVENTS = False CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULER … -
Custom QuerySet for related model
My Group class has a many-to-many relationship with User: group.user_set.all() Users can be active or inactive, and often I need to filter these in a group: group.user_set.filter(active=True) group.user_set.filter(active=False) It would be handy to have something like: group.user_set.active.all() group.user_set.inactive.all() I have tried setting up a Manager but I am not sure whether I should place it in Group or in User. The docs make it clear when it comes to defining a manager for a given class to tailor custom querysets for your model, but it is not so clear when you need to use custom querysets for related models. How can I do this? -
Display different edit profile forms for 2 user types in Django
I have 2 user types, teacher and student. I have built the view to be able to edit a student profile. But I also needed a different one for teacher. I didn't want 2 views, because that would be pointless. Now, for teacher it works as intended, but for some reason for student, the same form as for teacher is displaye... a student has different attributes so it has a different form I need to show. @login_required def profile_edit(request): user = request.user student = request.user.student teacher = request.user.teacher if user == teacher.user: if request.method != 'POST': form = TeacherEditForm(instance=teacher) else: form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') elif user == student.user: if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') context = { "form": form, } return render(request, "registration/profile_edit.html", context) I'm sure mistake is somewhere in this view. -
How to add data from junction table to many to many field with DRF serializer?
I have models like the following and I need to serialize the magazine model with the DjangoRestFramework serializer: class Publication(models.Model): ... class MagazinePublication(models.Model): publication_date = models.DateField() class Magazine(models.Model): ... publications = models.ManyToManyField(Publication, through=MagazinePublication) I want to serialize a magazine instance like this so that publications contain their publication dates from the junction (through) table: magazine = { id: ..., publications = [ {id: ..., publication_date: ...} ] } is there a way to do this with DjangoRestFramework serializer? A link to the docs would be appreciated too. -
Django: postgresql full text search: search lookup: Some terms not searching
I am using Django 2.0 and postgres (PostgreSQL) 9.6.1 I am having the below model with headline and body_text: class Entry(models.Model): headline = models.CharField(max_length=255) body_text = models.TextField() def __str__(self): return self.headline The below is my content headline: cheese making body_text: The simplest way to use full text search is to search a single term against a single column in the database. For example: >>> Entry.objects.filter(body_text__search='Cheese') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]. This creates a to_tsvector in the database from the body_text field and a plainto_tsquery ... The following the search results using the the search lookup. I have added 'django.contrib.postgres' in INSTALLED_APPS. Case 1: Works In [1]: Entry.objects.filter(body_text__search='Cheese') Out[1]: <QuerySet [<Entry: cheese making>]> Case 2: Not working In [2]: Entry.objects.filter(body_text__search='Pizza') Out[2]: <QuerySet []> (the word Pizza is there in the body_text still is not searching) Case 3: Not working In [3]: Entry.objects.filter(body_text__search='vector') Out[3]: <QuerySet []> (the word vector is there in to_tsvector Case 4: Not working In [9]: Entry.objects.filter(body_text__search='Entry') Out[9]: <QuerySet []> Case 5: Not working In [10]: Entry.objects.filter(body_text__search='data') Out[10]: <QuerySet []> How to search for the terms which are not working. -
Django recommend pages based on visited
I'm building a blog using django 1.11.7, and I'm looking for a way to list recommended posts based on the posts they have already viewed on the site. I have searched and been unable to find any convenient way to do this and hope that someone here might have a solution. -
Django: Group By between two range of Dates that are not present in Database
I am currently making an API in Django Rest Framework and in that I am filtering the dates which was given by the user(coming from frontend) and after then I am grouping it in months. The problem I am facing is what if the start date is lesser than min(createddate), then the data I am getting is filtered but instead of that I need the grouped time from start date to the end date(grouped in a range), if there is no data for some months then the database should return 0. I know SQL(I am using SQL as my DB) evaluates first where clause and after group by, is there a way to group the data first and then we could apply where clause. For example: Body - I am passing to the API { "StartDate":"2017-06-01", "EndDate":"2017-08-08" } Current Response - I am getting from my API "data": [ { "key": "Count", "bar": true, "values": [ [ "2017-08-01T00:00:00", 1501545600000, 1 ] ] } ] Correct Response - I wanted from data "data": [ { "key": "Count", "bar": true, "values": [ [ "2017-06-01T00:00:00", 1496255400000, 0 ], [ "2017-07-01T00:00:00", 1498847400000, 0 ], [ "2017-08-01T00:00:00", 1501545600000, 1 ] ] } ] -
Django Count how many manytomany relation ships in an attribute
This is my model: class Set(models.Model): name = CharField(max_length = 25) teacher = ForeignKey(get_user_model(), null = False, on_delete = models.CASCADE) students = ManyToManyField(get_user_model(), related_name= 'set_students') and I want to know how many students are in the manytomanyfield. Ive tried this set_ = Set.objects.get(pk=id_) students = len(set_.students) But that hasn't worked. Thanks for any help! -
Upload file to Django with Javascript
I have simple fetch function and I want to upload an base64 image. The function is as follows: function upload_to_server(canvasData){ console.log(canvasData); // that is data:image/png;base64,iVBORw0KGgoAAAANSUh....... return fetch(api_url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: {photo: canvasData} }).then(function (value) { if(value.ok){ return value.json().then(function (response) { debugger; }) } }).catch(function (reason) { debugger; }) } And I have simple django view: def upload_image(request): print(request.POST) pdb.set_trace() It goes successful to that view when function upload_to_server gets called, but request.POST is empty. It shouldn't be empty, it should have key photo with that base64 value. Any idea what I do wrong? -
Is django a restful api?
I am confused. Some say it is a Restful API and some say it is not. How do we define a RESTful API? GET,PUT,POST and DELETE commands ? Can I call any web application which is built using django Web framework a Restful API? -
pycharm does not recognise rest framework
I want to use rest_framework in my tutorial django project. I follow instruction steps and add 'rest_framework' in to settings.py as shown below. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig', 'rest_framework' ] However pycharm does not recognise the 'rest_framework' and give an error when I try to run server. Failed to get real commands on module "DjangoProject": python process died with code 1: Traceback (most recent call last): File "E:\PyCharm 2017.3.3\helpers\pycharm_jb_manage_tasks_provider.py", line 25, in django.setup() File "D:\DjangoProject\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\DjangoProject\venv\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "D:\DjangoProject\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "D:\DjangoProject\venv\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' What would be the reason ? Thanks for your interest. -
The data is not showing in fields when i update data in updateview
The data is not showing in fields when i update data in updateview def dis_update(request, pk, template_name='sales/distributor_form.html'): alldistributor = get_object_or_404(Distributor, pk=pk) if request.method=='POST': form = DistributorForm(request.POST, instance=alldistributor) if form.is_valid(): form.save() return redirect('index.html') else: form=DistributorForm() return render(request, template_name, {'form':form}) -
How to display the contents of several records into one?
how to display the contents of several records into one ??? I have to do something like that enter image description here -
Django Cloudinary Storage 'TypeError: invalid file: None' on python3 manage.py collectstatic
I've installed django-cloudinary-storage to store my static and media files on Cloudinary for my django project. I followed the instructions given here - https://github.com/klis87/django-cloudinary-storage My settings.py is as follows: DEBUG = False # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] #Media files (User uploaded Images, Videos) MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get('CLOUDINARY_CLOUD_NAME'), 'API_KEY': os.environ.get('CLOUDINARY_API_KEY'), 'API_SECRET': os.environ.get('CLOUDINARY_API_SECRET'), 'INVALID_VIDEO_ERROR_MESSAGE': 'Please upload a valid video file.', 'EXCLUDE_DELETE_ORPHANED_MEDIA_PATHS': (), 'STATIC_IMAGES_EXTENSIONS': ['jpg', 'jpe', 'jpeg', 'jpc', 'jp2', 'j2k', 'wdp', 'jxr', 'hdp', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'ico'], 'STATIC_VIDEOS_EXTENSIONS': ['mp4', 'webm', 'flv', 'mov', 'ogv' ,'3gp' ,'3g2' ,'wmv' , 'mpeg' ,'flv' ,'mkv' ,'avi'] } At the moment I have just one static file at the path given below: BASE_DIR/static/css/fonts.css I'm trying to upload the file to Cloudinary by performing collectstatic, but it throws this error everytime - Traceback(most recent call last): File "manage.py", line 15, in < module > execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 288, in run_from_argv self.execute( * args, ** cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 335, in execute output = self.handle( * args, ** options) File "/usr/local/lib/python3.5/dist-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle … -
django filtering based on foreign key
I need to get all the orders except orders with order_type =14 (order table has a foreign key reference to order_type and batch tables) when i am calling the url. Please help me to know the solution. #models.py class Batch(models.Model): batchnum = models.TextField(null=True, blank=True) otp= models.TextField(null=True, blank=True) class Order(models.Model): reqnum = models.TextField(null=True, blank=True) order_date = models.DateField(auto_now_add=True, null=True, blank=True) batch= models.ForeignKey(Batch, db_index=True,related_name='results', on_delete=models.PROTECT,null=True, blank=True) order_status = models.ForeignKey('DotOrderStatus', on_delete=models.SET_NULL, null=True,related_name='dot_order_status',default=1) order_type = models.ForeignKey('DotOrderType', on_delete=models.SET_NULL, null=True,related_name='dot_order_type',default=10) slno = models.TextField(null=True, blank=True) customer_name = models.TextField(null=True, blank=True) contact = models.BigIntegerField( null=True, blank=True) url:localhost:8000/api/v1/batch/id where '/id' is batch id Please help me to know the solution. Thanks in advance. -
Python ContentFile
I'm trying to save a ContentFile on the hard disk, but I can't! Tried to make a file object using ContentFile() and write on it using ".write" method, then I wanna know how to save it on hard disk with ".Save" method or sth like this. f1 = ContentFile("") Thank you in advance. -
Fetch next set of queries from Django database for async loading
If for instance, my Django table has hundreds of rows and initially, in a view, I fetch first 10 records in the following format to be displayed on a webpage. def fetchtExperts(request): if request.method == "GET": experts = Experts.objects.exclude(client_assigned=None).values('id', 'name', 'age').order_by('qualification')[:10] return render(request, 'index.html', {'experts': experts}) If these 10 records are displayed on page 1, I want the next 10 records to be displayed when the user clicks on page 2. How do I fetch the next 10 records starting from the record succeeding the last fetched record? Do I send page 1's last record's ID to the view so that I could fetch the next 10 records accordingly or is there some better approach to achieve this? -
implicit grant type with django oauth-toolkit
After reading about authentication flows for different clients, the suggested grant type for single-page application should be implicit. However, there is no good documentation for using implicit grant types in Django OAuth-toolkit. Here is how thought it works: 1. register the client as public, authorization grant type implicit and specify a redirect uri 2. 'curl -X POST -d "grant_type:implicit&username:&password:" -u "" http://localhost:8000/o/token/' 3. recieve the access token at the redirect uri Maybe someone could clearify how implicit grant types should be handled. -
Exact filtering on QuerySets
There is ManyToMany field in Entry model called tags. How do I filter Entries, which contain exact set of selected tags? E.g. get all entries, that have tags with ids 1,2,3 and not 1,2,3,4 or 1,2 Something like this: selected_tags = Tag.objects.filter(id__in=[id1,id2,id3]) entries = Entry.objects.filter(tags=selected_tags) Thanks! -
Gunicorn error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I'm running an Ubuntu 16.04 Digital Ocean server for my Django website, with Nginx & Gunicorn. When I perform sudo systemctl status gunicorn, I get on my server: And I can't pinpoint what the problem is. Any suggestions? -
Python 3 Django - middleware for some request
I created a middleware which contain lot of functions to check something before getting the view. And i added the middleware to the setting.py, but it is for all requests. So, how can i make the middleware work for some requests, not all? -
How to show the same content on every page in Django?
I'm coding a blog website with Django and everything's looking good until now but I remember something about Django: DRY (Don't repeat yourself) but in my case, it's exactly what I'm doing. For example, I have a widget to show the recent posts for my blog. This widget appears on every single or index page of my blog and I couldn't do this with include because when I include something, it can't detect the block tags or its content. So I'm writing a code block for this in every another page like category-index, blog-single-page, etc. And the more important one is that I'm adding the database codes to pull data from database and every view def contains this code to show the widget's data so it's against to DRY principle. Any good way to do this or this is the normal way? Thanks! Here is the view to give you an idea: def category_detail(request, category_slug): posts = Post.objects # FOR BLOG POSTS WIDGET categories = Category.objects.all() # FOR CATEGORIES WIDGET category = get_object_or_404(Category, slug=category_slug) category_posts = category.post_set.all() paginator = Paginator(category_posts, 10) page = request.GET.get('page') cat_posts = paginator.get_page(page) context = { 'posts': posts.order_by('is_pinned', '-published')[:20], 'popular_posts': posts.order_by('is_pinned','-views')[:15], 'categories': categories, 'category': category, 'category_posts': … -
How to fix "NoReverseMatch at /polls/" with "'polls' is not a registered namespace" error?
My mysite/urls.py is this from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And, my polls/urls.py is from .import views from django.conf.urls import url from django.contrib.auth.views import login urlpatterns= [ url(r'^$',views.index, name= "index"), #127.0.0.1/polls url(r'^(?P<question_id>[0-9]+)/$', views.detail, name= "detail"), #127.0.0.1/polls/1 url(r'^(?P<question_id>[0-9]+)/results$', views.results, name="results"), #127.0.0.1/polls/1/results url(r'^(?P<question_id>[0-9]+)/vote$', views.vote, name="vote"), #127.0.0.1/polls/1/vote url(r'^login/$', login, {'template_name': 'polls/login.html'}) ] The error I am getting is there is no registered namespace as polls. Do help. -
Is there an efficient way to get the count of object occurrence in another object list ? Django
In my Django app, I have a few models including, but not limited to: Vehicle, Vehicle Make, and Dealership. I create a list comprehension that creates JSON objects with the vehicle make, count of occurrences for that make in the Dealerships inventory, e.g. 6 Toyotas in their inventory, and the id of that make in my Postgres DB. The problem is I have to use .count on all the vehicles in the database that are of that make, and belong to that dealership, which takes a huge toll on the database. Is there any way to speed this up, or optimize this. I've been looking through the web for potential solutions, but am coming up dry. view function try: dealer = Dealer.objects.get(id=1) except Exception as e: logging.error(e) makes_map = [{ 'name': make.name, 'count': Vehicle.objects.filter(vehicle_make=make, dealer=dealer).count(), 'id': make.id } for make in VehicleMake.objects.filter( name__in=Vehicle.objects.filter(dealer=dealer).values_list('vehicle_make__name', flat=True)) ]