Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'load_strategy'
I am setting up a django rest api and need to integrate social login feature.I followed the following link Social Auth with Django REST Framework After setting up when try to run server getting following error from social.apps.django_app import load_strategy ImportError: cannot import name 'load_strategy' Is there any package i missed? i cant figure out the error. -
Extend djoser login method to get user roles
Djoser login api returns the user token, I also want to return user roles. How to implement such a case? Here is the method of logging on: def login_user(request, user): token, _ = settings.TOKEN_MODEL.objects.get_or_create(user=user) if settings.CREATE_SESSION_ON_LOGIN: login(request, user) user_logged_in.send(sender=user.__class__, request=request, user=user) return token My goal is to achieve something like: def login_user(request, user): token, new_user = settings.TOKEN_MODEL.objects.get_or_create(user=user) if not new_user: token_and_roles = { token: token, roles: [for group.lower() in User.objects.get(user).groups] } return token_and_roles if settings.CREATE_SESSION_ON_LOGIN: login(request, user) user_logged_in.send(sender=user.__class__, request=request, user=user) return token How to overwrite djoser api login method? -
Complex prefetch_related
There is a request which returns a list of several Lists with their movies. I want to use prefetch to Lists to optimize db calls. I have several models: class List(models.Model): name = models.CharField() class ListMovie(models.Model): list = models.ForeignKey(List) movie = models.ForeignKey(Movie) class Movie(models.Model): title = models.CharField() Is there a way to prefetch movies from List object with prefetch_related? -
permission_classes doesn't work whats going wrong?
I made acustom permission which make only advertise creator can delete or edit it ,though permissions have no effect and alraedy deleted another user advertise what;s going wrong here? views.py: from rest_framework import permissions,generics from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from .permissions import IsOwnerOrReadOnly from advertise.serializers import AdSerializer class AdListGeneric(generics.ListCreateAPIView): permission_classes([permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly],) queryset=Advertise.objects.all() serializer_class=AdSerializer # @permission_classes([permissions.IsAuthenticatedOrReadOnly],[IsOwnerOrReadOnly]) class AdDetailgeneric(generics.RetrieveUpdateDestroyAPIView): permission_classes([permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly],) queryset=Advertise.objects.all() serializer_class=AdSerializer ,,, permissions.py: from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ create custom permission allow only owner to edit it """ def has_object_permission(self, request,view, obj): #read allowd to all users #so we always allow GET, HEAD, OPTioNS if request.method in permissions.SAFE_METHODS: return True #write permissions only for allwed users: return obj.publisher == request.user ,, , -
Django PostgresqlJSONField custom decoder
Providing a custom encoder is easy, as we can give set the encoder parameter, but using a custom decoder seems not possible. How would I go about using a custom decoder for Django PostgresqlField? -
How to make a range from textarea in django
I create a simple website that allow user to place their favorite word and search for a capital and one by one processing it at the backend. for example: <form method="POST" action="/search> {% csrf_token %} <textarea></textarea> <button type="submit">Submit</button> </form> Now I want to submit a text for example Python Django Flask I want to manually split that text and one by one process it (FOR EXAMPLE CODE) {% for x in textarea_tag %} {{ validate_function() }} {% endfor %} Sorry for any wrong format, if there is. -
How to reassign a model to a different app for display only purposes in Django Admin
I know I can change the display title for a model in Django Admin using class Meta: verbose_name='Custom Model Name Here' However, is there a way to display which app heading a model is displayed under? For example, if I create a custom user model Users in a new app also called users then the default user model goes from Authentication and Authorization > Users to Users > Users. I would like to retain it under the original heading Authentication and Authorization > Users. I have read this answer which suggests changes the app verbose_name, however it only changes the verbose name of the app associated with the model. I want to show the model in a different group on the admin panel. You can see the issue that approach takes here: -
Reverse accessor clashes in Django when adding custom user. Adding AUTH_USER_MODEL in settings.py doesn't work either
I got reverse accessor clashes error when trying to use a custom user model. I added AUTH_USER_MODEL in settings.py but still get the same error. I am writing a Django project (Django version 2.2.2) when at a point I want to change to use the custom user model. There are already a couple of models, but it's fine to clear the database to start over at this stage, so I have deleted the sqlite3.db and all the migrations. So to have a custom user model as per django documentation, I added: in models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass ... # other models in settings.py: AUTH_USER_MODEL = 'polls.User' After that, python .\manage.py makemigrations should just work. But it doesn't. It showed the same message as if I didn't add AUTH_USER_MODEL in settings.py at all: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. polls.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: … -
How to change app a model is displayed under in Django Admin interface
I know I can change the display title for a model in Django Admin using class Meta: verbose_name='Custom Model Name Here' However, is there a way to display which app heading a model is displayed under? For example, if I create a custom user model Users in a new app also called users then the default user model goes from Authentication and Authorization > Users to Users > Users. I would like to retain it under the original heading Authentication and Authorization > Users. -
Bring machine learning to live production with AWS Lambda Function
I am currently working on implementing Facebook Prophet for a live production environment. I haven't done that before so I wanted to present you my plan here and hope you can give me some feedback whether that's an okay solution or if you have any suggestions. Within Django, I create a .csv export of relevant data which I need for my predictions. These .csv exports will be uploaded to an AWS S3 bucket. From there I can access this S3 bucket with an AWS Lambda Function where the "heavy" calculations are happening. Once done, I take the forecasts from 2. and save them again in a forcast.csv export Now my Django application can access the forecast.csv on S3 and get the respective predictions. I am especially curious if AWS Lambda Function is the right tool in that case. Exports could probably also saved in DynamoDB (?), but I try to keep my v1 simple, therefore .csv. There is still some effort to install the right layers/packages for AWS Lambda. So I want to make sure I am walking in the right direction before diving deep in its documentation. -
Django admin panel Datepicker not working
I am using daterangefilter to filter result according to dates but my datepicker is not working.Its showing datepicker icon but not working. I tried to reinstall daterangefilter as well as django-suite(seen somewhere while searching for the solution) to identify the problem but it is in same state. list_filter = ['company', 'status', 'published', 'dont_publish',('created_at', DateRangeFilter)] -
How can in filter by more than one value of same field at django admin using list_filter?
i have field "car" that contains values "Benz, Nissan, Kia" using ==> list_filter ["car"] how can i filter by Both values like "Nissan" and "Kia" . Both not one of them Car objects -
SSO with Django and Active Directory
I have a web application developed using Django. It's hosted remotely on AWS but deployed to clients using their local networks. At the moment users just sign in using the standard django authentication approach. They each have their own usernames, passwords specific to the app, etc. I would like to be able to provide single sign on, so users who are already authenticated by active directory will be logged directly to the site. Is this possible with an app hosted on AWS? I assume there would have to be some kind of hook into AD? I have read this answer and this answer, but they appear to work for intranet apps only. -
Problem with running Django with nginx and uwsgi
I'm trying to install a new server, and I can't run Django with nginx and uwsgi. I receive an error "502 Bad Gateway" and there are messages on the error log which I don't understand: 2019/07/20 10:50:44 [error] 2590#2590: *1 upstream prematurely closed connection while reading response header from upstream, client: 79.183.208.33, server: *.speedy.net.3.speedy-technologies.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/app/speedy_net/socket:", host: "3.speedy-technologies.com" I have 4 websites and here is the main (default) configuration file: server { listen [::]:80 default_server; listen 80 default_server; server_name *.speedy.net.3.speedy-technologies.com speedy.net.3.speedy-technologies.com; access_log /var/log/nginx/speedy-net.access.log; error_log /var/log/nginx/speedy-net.error.log; client_max_body_size 50M; root /home/ubuntu/speedy-net/speedy/net/static_serve/root; try_files $uri @uwsgi; location @uwsgi { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/app/speedy_net/socket; } location /admin/ { auth_basic "admin site"; auth_basic_user_file /etc/nginx/htpasswd_admin; include uwsgi_params; uwsgi_pass unix:/run/uwsgi/app/speedy_net/socket; } location /static { alias /home/ubuntu/speedy-net/speedy/net/static_serve; access_log off; # expires max; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml application/rss+xml font/truetype application/x-font-ttf font/opentype application/vnd.ms-fontobject image/svg+xml; gzip_vary on; gzip_comp_level 6; } } And: [uwsgi] project = net chdir = /home/ubuntu/speedy-net home = %(chdir)/env module = speedy.%(project).wsgi:application plugins = python3 master = true processes = 4 chmod-socket = 666 vacuum = true uid = ubuntu gid = ubuntu touch-reload = /run/uwsgi/app/speedy_%(project)/reload I tried to test with sudo … -
How to access files that are outside of a django project from a template
I am working on a python project where my raspberry pi sends frames from a camera to my server. The server displays these frames as a video and when movement gets detected it saves the video as '/mnt/cameras/"year-month-day"/"hour-min-sec".webm. This all works fine, but I can't get these saved video's to work on my web-page since they are not inside of my project. I know for sure that I can play these video's because when I put them in my 'media' folder it does work. In my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(REPOSITORY_ROOT, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(REPOSITORY_ROOT, 'media/') CAMERAS_URL = '/cams/' CAMERAS_ROOT = '/mnt/cameras/' In my urls.py: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.camerapage, name="cameraspage"), path('camera<cam_number>',views.livefe, name='camera'), path('browse/',views.browsepage, name='browse'), ]+static(settings.CAMERAS_URL, document_root=settings.CAMERAS_ROOT) In my views.py: videos_path = "/mnt/cameras" def browsepage(request): class Video: path = '' title = '' def __init__(self,path,title): self.path = path self.title = title def __str__(self): return self.title class Date: date = '' path = '' videos = [] def __init__(self,path,date): self.path = path self.date = date def __str__(self): return self.date dates = [] for dir_or_file in os.listdir(videos_path): date_folder_path = os.path.join(videos_path,dir_or_file) if … -
how to set the order of row by drag and drop in python django with jquery and save that order in the database
want to change the row by drag and drop and also save the order in the database accordingly Name L Group C Group Order Image Source Data Source 'show data od labor in tablerow' {% for labor in labours %} -
django+heroku+S3 storage only content embedded images through ckeditor gets deleted after sometime
i have deployed my django app in heroku, postgresql as db and for storing images i haved used amazon S3 storage, the problem what i am facing is , for creating a blog post i have used ckeditor , so user can input images along with the content text for creating a post. after creating a post it looks like below when right clicked on post image and open link in new tab is selected, below is the url of S3 for the image uploaded after sometime images are deleted, only text content remains i have used S3 for thumbnail of the post which is direct image field , this doesn't get deleted , only problem is the post images which i embedded with content using ckeditor gets deleted after sometime of uploading . any extra information required , i will update it. thanks in advance ! -
Django Pattern: Celery + Async + Model Writing
I need to access multiple websites at once and save their data. I'm aware that Django isn't async and that models can't be accessed asynchronously. So what's an architecture I can use to achieve this? I'm using await asyncio.gather() to make the queries but I'm not sure how to get to writing this to the database synchronously. Send it to another task queue? Move it into an array and pop them out one at a time to write synchronously? -
Django ImageField GET api UnicodeDecodeError
I am getting a UnicodeDecodeError when I call the GET API for my model. The error is as follows: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte My models.py class RestaurantImage(CreateUpdateModel): image_type = models.CharField(verbose_name=_('Image Type'), choices=IMAGE_TYPES, max_length=255, default=RESTAURANT) restaurant = models.ForeignKey(verbose_name=_('Restaurant'), on_delete=models.PROTECT, to=Restaurant) image = models.ImageField(verbose_name=_('Select Image'), upload_to='media/') def __str__(self): return self.restaurant.name class Meta: verbose_name = 'Restaurant Image' verbose_name_plural = 'Restaurant Images' My serializers.py class RestaurantImageSerializer(serializers.ModelSerializer): restaurant = RestaurantSerializer(many=False, read_only=True) class Meta: from .models import RestaurantImage model = RestaurantImage fields = ('id', 'image_type', 'restaurant', 'image') My views.py class RestaurantImageListView(ListCreateAPIView): from rest_framework.permissions import AllowAny from rest_framework.filters import SearchFilter from .serializers import RestaurantImageSerializer from .models import RestaurantImage permission_classes = (AllowAny, ) serializer_class = RestaurantImageSerializer queryset = RestaurantImage.objects.all() filter_backends = (SearchFilter, ) search_fields = ('id', 'name') My post api works well, but the get api throws the error. I have also added the following MEDIA configuration to settings.py, MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and to the main urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Please help me in solving this error, thank you. -
how to make the form to show using django anad ajax
i have a django website that include a form where it appear once the user click the submit button using ajax and using the crispy forms library until now i am able to do the function call back in the ajax and i get back the requested form where it display the result in the concole: "GET /books/create2/ HTTP/1.1" 200 3734 base.html {% load static %}<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bookstore - Simple is Better Than Complex</title> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> {% include 'includes/header.html' %} <div class="container"> {% block content %} {% endblock %} </div> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/plugins.js' %}"></script> {% block javascript %} {% endblock %} </body> </html> urls.py from django.contrib import admin from mysite.books import views from django.urls import path path('admin/', admin.site.urls), path('books/',views.book_list,name = 'book_list'), path('books/create2/',views.book_create2,name = 'book_create2'), views.py def book_create2(request): form = BookForm() context={ 'form':form } html_form = render_to_string('book_create2.html',context,request=request) return JsonResponse({'html_form':html_form}) book_list.html {% extends 'base.html' %} {% load static %} {% block javascript %} <!--<script src="{% static 'books/js/books.js' %}"></script>--> <script src="{% static 'js/plugins.js' %}"></script> {% … -
Asynchronous Python: Reading multiple urls from a synchronous library
I'm using python-twitter which isn't an asynchronous library and writing these to Django models. What I need to do for the sake of speed is read n batches of 100 user_ids at once. So: [[1234, 4352, 12542, ...], [2342, 124124, 235235, 1249, ...], ...] Each of these has to hit something like api.twitter.com/users/lookup.json. I've tried to use something like this, but it seems to run synchronously: await asyncio.gather(*[sync_users(user, api, batch) for batch in batches], return_exceptions=False) I've also tried wrapping the synchronous library calls, but that also seems to run synchronously. How can I send out all of the username lookup requests at once? loop = asyncio.get_event_loop() executor = ThreadPoolExecutor(max_workers=5) results = await loop.run_in_executor(executor, api.UsersLookup(user_id=batch, include_entities=True)) -
How do I append data to a many-to-many field using Ajax?
I'm trying to update user fields using ajax. I created an APIView for user model using rest-framework. User model includes a many-to-many field named "favorite_entries", with the code below I need to get all the field data beforehand in JS and append new data and call a put request, which seems wrong to me. views.py: class CurrentAuthorView(APIView): permission_classes = (permissions.IsAuthenticated, ) http_method_names = ['get', 'put'] def put(self, request): serializer = AuthorSerializer(request.user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): serializer = AuthorSerializer(request.user) return Response(serializer.data) javascript: $("#favorite_entry-btn").on("click", function () { let entry_id = $(this).attr("data-entry-id"); $.ajax({ url: '/api/v1/author/', type: 'PUT', data: "favorite_entries=3", success: function (data) { alert('success'); }, error: function (err) { console.log(err); } }); }); I expect the entry with primary key "3" appended to the field, but it erases all the previous data. -
why swagger raises unclear error - Django
I have a django rest Backend app, and i use swagger to look and document my apis to the FE. This worked fine, but I made some changes and now I get this error: Internal Server Error: / Traceback (most recent call last): File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 494, in dispatch response = handler(request, *args, **kwargs) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework_swagger/views.py", line 32, in get schema = generator.get_schema(request=request) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/schemas/coreapi.py", line 153, in get_schema links = self.get_links(None if public else request) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/schemas/coreapi.py", line 140, in get_links link = view.schema.get_link(path, method, base_url=self.url) AttributeError: 'AutoSchema' object has no attribute 'get_link' HTTP GET / 500 [0.15, 127.0.0.1:44214] /home/notsoshabby/Desktop/panda_pitch/django_project/settings.py This error is not very clear as the AutoSchema is not a part of my code and the traceback is not showing me where in My … -
Convert whole Pycharm Project File (Contains GUI) into application
I was actually thinking if the whole Pycharm Project folder (which mainly contains GUI) can actually be converted into an application which in turn can be opened from any Unix server? This means to say that, whenever this application is launch, an automatic GUI will be created (let's say, on Chrome) if python manage.py runserver is commanded onto the same Unix server? Any comment and solution will be a great help, thank you. -
How to view advertises published by auser in his User serializer
I have user serializer in which i need to show in every user detail advertises which he published models.py: class Advertise(models.Model): title = models.CharField(max_length=120) publisher = models.ForeignKey(User, related_name='publisher',null=True, blank=True, on_delete=models.CASCADE) category = models.CharField(choices=CATEGORIES, max_length=120) description = models.TextField(max_length= 200, null=True, blank=True) image = models.ImageField(upload_to='project_static/Advertise/img', null=True, blank=False) price = models.DecimalField(decimal_places=2, max_digits=20) timestamp = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) location = models.CharField(max_length=120 , null=True, blank=True) contact = models.CharField(max_length=120,null=True, blank=True) def __str__(self): """show ad name in admin page""" return self.title def get_absolute_url(self): return reverse("advertise:advertise-detail", kwargs={"pk":self.pk}) serilaizers.py: class AdSerializer(serializers.HyperlinkedModelSerializer): publisher = serializers.ReadOnlyField(source='publisher.username') url = serializers.CharField(source='get_absolute_url') class Meta: model = Advertise fields = ('url','id','title','publisher','category','description','price','timestamp','approved','location','contact') class UserSerializer(serializers.HyperlinkedModelSerializer): publisher = AdSerializer(source='publisher_set', many=True) class Meta: model = User fields = ['id', 'username','publisher'] error: Got AttributeError when attempting to get a value for field publisher on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'publisher_set'.