Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't seem to troubleshoot this code( python crash course)
I'm very new to Python and Django in particular and I"m working my way through the Python Crash Course(1st ed) book by Eric Matthes. Everything has been running fine up until chapter 19 when I am adding functionality for the user to add entries to topics. Basically its a web app that working kind of like a journal to log things you learn about certain topics. I've thrown in some print statements to try and figure out where the exactly problem lies and from what I can tell it seems to be with the if statement in def new_entry function in views.py. I can't figure out where to really go from here. out of the print statements i have in the current code only the one right below the first if statement executes print("this is requesting a new form") my views.py file with relevant entry def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if request != 'POST': # No data submitted; create blank form form = EntryForm() print("this is requesting a new form") else: print("else statment runs?") # POST data submitted; process data. form = EntryForm(data=request.POST) print("The else statment is running") if form.is_valid(): print("the … -
CORS issue with Django backend and React frontend
I'm getting a CORS issue and this is my first CORS experience (Yay!). I've been researching for over a week and just cannot figure this out. Here is the pre-flight GENERAL Request URL: http://gsndev.com/gsndb/all/uploadcsv/ Request Method: OPTIONS Status Code: 200 OK Remote Address: 104.18.39.141:80 Referrer Policy: no-referrer-when-downgrade RESPONSE HEADER access-control-allow-headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with access-control-allow-methods: DELETE, GET, OPTIONS, PATCH, POST, PUT access-control-allow-origin: * access-control-max-age: 86400 CF-RAY: 4f964ff0deb1c7c1-DEN Connection: keep-alive Content-Encoding: gzip Content-Type: text/html; charset=utf-8 Date: Sat, 20 Jul 2019 16:29:08 GMT Server: cloudflare Transfer-Encoding: chunked vary: Origin x-envoy-upstream-service-time: 4 REQUEST HEADER Provisional headers are shown Access-Control-Request-Headers: authorization Access-Control-Request-Method: POST Origin: http://localhost:3000 Referer: http://localhost:3000/manage-data/upload User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 Here is where the error comes in: GENERAL Request URL: http://gsndev.com/gsndb/all/uploadcsv/ Request Method: POST Status Code: 500 Internal Server Error Remote Address: 104.18.39.141:80 Referrer Policy: no-referrer-when-downgrade RESPONSE HEADER Provisional headers are shown Accept: application/json Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxOCwidXNlcm5hbWUiOiJoYW5uYWgiLCJleHAiOjE1NjM2NDIwOTMsImVtYWlsIjoiIn0.puGSSGtLXOzVjW63OQozv-DDoZcNi_eW5uTT1LKFG50 Content-Type: multipart/form-data Origin: http://localhost:3000 Referer: http://localhost:3000/manage-data/upload User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 REQUEST PAYLOAD [object Object] And I'm getting this error in the console: Access to fetch at 'http://gsndev.com/gsndb/all/uploadcsv/' from origin 'http://localhost:3000' has been blocked … -
WCDN cache policy in the http response header
I deployed a django project on a server, and have some unexpected cache of data on http response. some of my pages should have changed after adding some data in the panel, but it's changing after a while. here is my response header: WCDN-Cache-Policy: SMART WCDN-CacheID: ... I use nginx, gunicorn and supervisor on my server. How can I disable this cache system? -
Storing tenant-specific constants when using Docker to deploy a multi-tenanted Django app
I am using this approach to build a multi-tenanted app in Django and isolate the tenants using Docker. For those not familiar, it essentially redeploys the same code base in a different container for each different customer, allowing them to exist on the same server. I like this as it's the best form of isolation I've seen without spinning up new machines, requires little new code, and I don't mind manual config in Docker to onboard a customer. However, when previously I was building a single-tenant app I saved constants like the customer's name in CUSTOMER_NAME = 'My Customer' in settings.py I can no longer do this, as the code base is shared each time I deploy in Docker. What would be the alternative best practice? Should I create a customer model with one entry to store this data? It feels like I am overlooking something. -
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))