Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework static file blocked by CORS
Can someone help me, because I can't do anything with CORS. I have DRF server with corsheaders installed. The settings are INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ('Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials', 'Authorization', 'Content-Type', 'Cache-Control', 'X-Requested-With', 'x-csrftoken') What am I trying to achieve is to get an image from server to crop it in React. So I get the name of the image in the server response, I show it on the page with no ploblem, but when I'm trying to get it like this: let img = new Image(); img.crossOrigin = 'Anonymous'; img.src = "http://127.0.0.1:8000/static/images/" + props.image.picname; setImage(img); I'm getting an error that access to the image is blocked. I've tried to run server as python manage.py runserver --nostatic and modify urls.py with those lines: if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() But it didn't help. How should I manage this since I have no request to the image, I just open it. Why showing the image on the page is ok to CORS and trying to get it by JS from the same page is such a big problem? -
django sitemap for static react routes (error : NoReverseMatch at /sitemap.xml/)
i want to implement sitemap for static react routes and I get this error: Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name. I added a list of my react routes REACT-ROUTES in settings.py and append them to urlpatterns in the root urls.py file settings : INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'rest_framework', . . ] SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'ess')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] REACT_ROUTES = [ 'contact', 'politique-de-confidentialite', 'mentions-legales', 'cookies', . . ] STATIC_URL = '/static/' STATIC_ROOT = basepath + '/app/static' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ess', 'static')] urls : from django.conf import settings from django.contrib.sitemaps.views import sitemap from .sitemaps import StaticViewSitemap react_routes = getattr(settings, 'REACT_ROUTES', []) sitemaps = { 'static': StaticViewSitemap } urlpatterns = [ path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), re_path(r'^$', TemplateView.as_view(template_name='index.html')), ] for route in react_routes: urlpatterns += [ re_path('{}'.format(route), TemplateView.as_view(template_name='index.html')) ] sitemaps.py : from django.contrib.sitemaps import Sitemap from django.urls import reverse class StaticViewSitemap(Sitemap): def items(self): return ['contact'] def location(self, item): return reverse(item) I don't know what I am missing, please help -
Im trying to implement a delete button using django and vue js
Im trying to implement a delete button using django and vue js but im running into an error 500 and i cant seem to understand why ? i know it means my call isn't working go from here <button class="button is-success" @click="deleteTest()"> Yes, Delete</button> to here deleteTest() { axios.post('/app/api/testzone_delete/' + this.TestCategory_id + '/') .then((response) => { console.log(response) this.showDialog = false }) .catch((function (error) { console.log(error ) })) } } }) </script> then like its django it goes through url.py path('api/testzone_delete/<int:individualtestzone_id>/', api_delete_test, name='api_delete_test'), and finally in the api.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import TestCategory from django.contrib import messages @csrf_exempt def api_delete_test(request, individualtestzones_id): individualtestzone = request.user.TestCategories.all().get(pk=individualtestzones_id) individualtestzone.delete() return JsonResponse({'success': True}) im pretty new to django and can't seem to see why it does not work -
DRF Model Permission denying access to authenticated user
I'm getting a permission denial error but, if I'm understanding things correctly, the permissions should already have been assigned. class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [DjangoModelPermissions] class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [DjangoModelPermissions] I've tried some different permission classes so far, but except for just bypassing it entirely with AllowAny nothing seems to have worked. -
Choose Front-end and Backend for multipurpose website( Social Network + ecommerce (like facebook has Market)
I have been reviewing the suggestion of using Django for backend(api) and using Reactjs for front-end. These can help the platform run smoothly, fast and secured.However, I would like to know your suggestion of choosing technologies for building that platform (social network and ecommerce at same domain) -
How do i become a forex web application developer [closed]
i am web developer with intermediate knowledge in Python, Django , javascript, Html and css. i will like to start building web applications for forex trading but i dont't have any idea on how to start and i haven't seen any tutorials on it. Any idea will be appreciated thanks. -
Not able to apply redis lock on celery workers
I am trying to replace django memcache’ to redis lock and getting Connection reset error` -
How to filter comparing two informations from the same Django model
I have a MedicalCertificate model like this: class MedicalCertificate(models.Model): needs_leave = models.BooleanField() date = models.DatetimeField() days_off = models.IntegerField() And I need to filter the active medical certificates, which are: date + days_off >= datetime.now() I tried to use F(), but not success. Ex.: from django.db.models import F certificates = { 'needs_leave': True, 'days_off__gte': datetime.datetime.now() - F('externalsystemmedicalcertificates__date') } queryset = MedicalCertificate.objects.filter(**certificates) Any idea how to proceed? -
Python3 import error smart_unicode django
This is my first time ever trying to run a py script I have a script to auto import to android studio some translations. I installed python 3.10.5 and pip and trying to run a script. I have this import from django.utils.encoding import smart_str, smart_unicode When i try to run it, I get the error ImportError: cannot import name 'smart_unicode' from 'django.utils.encoding' (C:\Users\a816353\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\encoding.py) I have tried some suggestions but I cant figure out what to do. -
How to perfom CRUD Operation in Flutter & Postgres
I want to perfom CRUD Operation Postgres but with a flutter app, so that my Django app can share data with Flutter. -
Python Django convert timestamp from UTC to local timezone
Im am working with Django + DRF, to develop a REST API. I have configured the django settings to work with the timezone support on: USE_I18N = True USE_L10N = True USE_TZ = True As previously mentioned, my database is receiving and storing data in UTC. My problem is that for some users (each user has their configuration) I must return responses in their time zone (usually in UTC-3 or UTC-2). I was reading several posts and tried several combinations of: astimezone and normalize without succes. I attach my attempts: timezone_arg = pytz.timezone('America/Buenos_Aires') print(ts_a, ts_b) ts_a = ts_a.astimezone(timezone_arg) ts_b = ts_b.astimezone(timezone_arg) print(ts_a, ts_b) utc = pytz.timezone('UTC') ts_a = timezone_arg.normalize(ts_a.astimezone(utc)) ts_b = timezone_arg.normalize(ts_b.astimezone(utc)) print(ts_a, ts_b) I am getting the following: 2022-06-17 05:39:09 2022-06-17 05:46:49 2022-06-17 05:39:09-03:00 2022-06-17 05:46:49-03:00 2022-06-17 05:39:09-03:00 2022-06-17 05:46:49-03:00 I understand that django is interpreting that what I am telling it is that the timestamps are already in UTC-3... and it is normalizing them to UTC. But what I want is to cast from UTC to UTC-3. My input/output should be: 2022-06-17 05:39:09 2022-06-17 05:46:49 2022-06-17 02:39:09 2022-06-17 02:46:49 Since I don't only work with the time zone of Argentina (UTC-3), I can't compute a timedelta of 3 … -
Plotly in Django should I use Dash?
I am a reasonably experienced amateur python coder. With this site's help I have fought my way through, celery, channels, websockets, NGINX, docker etc etc to produce a website which controls my astronomy dome and some house automation. Part of the astronomy setup is a 3rd party weather station which collects data (temperature, wind speed, humidity, brightness, rain etc) and distributes a json file every 15 secs. I have successfully coded pyhton / Django / Plotly to collect the data and produce one graph (temperature). I have successful embedded this graph in a webpage. The next step is to add a drop down box as a choice mechanism for what data (e.g. temperature or bightness) to show in the graph. I think I can do this with websocket calls. Should I use Dash instead ? I have found plotly relatively easy to use and I am attracted to the idea of using the bootstrap plugin to manage bootstrap in python code as opposed to in an html page. but Problem: installing Django-Plotly-Dash v2.0 downgrades django (v4.0.5 to 3.2.13), daphne (v3.0.2 to 2.5.0) and channels (v3.0.4 to 2.4.0). I'm not sure if that is going to 'break' anything but since everything … -
Store extra data like refresh_token when signing up via access_token
I am trying to signup using access token for google. My frontend is next.js with next-auth.js fetching the access_token, refresh_token, etc. I am using python social auth with Django to persist the user information. I use the access_token provided by next-auth to signup the user in Django. How do I make sure that the other response fields like refresh_token, and expires are saved in the Django DB? I can pass the required fields from next-auth to an API in Django but not sure what the expected format is. https://python-social-auth.readthedocs.io/en/latest/use_cases.html#signup-by-oauth-access-token @psa('social:complete') def register_by_access_token(request, backend): # This view expects an access_token GET parameter, if it's needed, # request.backend and request.strategy will be loaded with the current # backend and strategy. token = request.GET.get('access_token') user = request.backend.do_auth(token) if user: return HttpResponse(json.dumps(get_tokens_for_user(user))) else: return HttpResponse('Unauthorized', status=401) def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) update_last_login(None, user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } -
Pass Django list as argument to Javascript
I have a list passed through the context into the html page of a Django project which I want to read inside of a .js which contains chartjs code. The problem is that .js is reading as string and not as a list/array. views.py def index(request): context = { "data": [1, 2, 3, 4, 5]} return render(request, 'index.html', context) Then, in the html page I have to pass the {{ data|safe }} to a javascript like so: <script src='{% static "js/chart.js/linechart.js" %}' var label = "fakelabel"; var index = {{ data|safe }}; ></script> Inside the .js I'm reading the 'index' input as: document.currentScript.getAttribute("index") How can I fix this? ('label' is read correctly as str indeed). -
Pylance, functions not defined
I have a simple code with 3 functions. the first one get some values from the 2 others to check some conditions, but I get an error from Pylance saying the functions sub1 and sub2 are not defined. any clues? @staticmethod def main_test() var1 = sub1() if not var1: return ('test1 not even') var2 = sub2() if not var2: return ('test2 not even') return True @staticmethod def sub1(): test = random.randint(1, 10) if (test % 2)==0: return True return ( str(test) + 'is Odd') @staticmethod def sub2(): test = random.randint(1, 10) if (test % 2)==0: return True return ( str(test) + 'is Odd') -
Template variables doesn't updates after redirect in Django?
I am building simple django app where I want to do some parsing when user click button on the frontend. I have template variable {{ parsing }} which I am using inside index.html to disable button for parsing when user click on it <div class="btn-group mr-2" role="group" aria-label="Parsing group"> <button class="btn btn-dark btn-lg" id="parseButton" {% if parsing %} disabled {% endif %}> <i class="fa fa-terminal gradient-text"></i> <span class="gradient-text">| Parse</span> </button> </div> Next what I do is JQuery method which sends ajax request to my backend to initialize variables for parsing and method from views.py returns redirect to the same page (index.html). $('#parseButton').click(function () { $.ajax({ type: 'POST', url: 'initialize_parsing/', headers: {"X-CSRFToken": $.cookie("csrftoken")}, data: {} }); Then my views.py: def initialize_before_parsing(request): if request.method == 'POST': frontendTracker = FrontendTracker() frontendTracker.progress = 0 frontendTracker.parsing = True return redirect("index") class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): frontendTracker = FrontendTracker() context = super(IndexView, self).get_context_data(**kwargs) context["showAnnotation"] = frontendTracker.showAnnotationButton context["parsing"] = frontendTracker.parsing context["progress"] = frontendTracker.progress return context and urls.py urlpatterns = [ path('', IndexView.as_view(), name="index"), path("initialize_parsing/", initialize_before_parsing, name="initialize_before_parsing"), ] Finally what is bother me is that when I send that ajax request and everything works fine when my page being redirected {{progres}} template variable isn't changed … -
Python NameError: name '_mysql' is not defined
I am trying to have a working ubuntu server with Python, Django and MySQL. But when I switch from SQLite to MySQL and trying to reach my server I get the following error "NameError: name '_mysql' is not defined". It does work if I run the project in virtual environment mode with the command "python manage.py runserver". The database is also correctly created with the command "python manage.py migrate". This does not work when I try to reach my URL. I think there is an issue with my virtual host file, but I am unable to see it. Any help would be appreciated! Virtual host file: <VirtualHost *:80> ServerName mysite.com ServerAlias www.mysite.com WSGIDaemonProcess myprocess python-path=/var/www/myproject/myname:/var/www/myproject/myname/venv/lib/python3.7/site-packages WSGIProcessGroup myprocess WSGIScriptAlias / /var/www/myproject/myname/myproject/wsgi.py <Location / > Order deny,allow Deny from all # ek Allow from ${IP_USER1} Allow from ${IP_USER2} </Location> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> The error log: mod_wsgi (pid=55852): Failed to exec Python script file '/var/www/myproject/wsgi.py'. mod_wsgi (pid=55852): Exception occurred processing WSGI script '/var/www/myproject/myname/myproject/wsgi.py'. Traceback (most recent call last): File "/var/www/myproject/myname/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: cannot import name '_mysql' from partially initialized module 'MySQLdb' (most likely due to a circular import) (/var/www/myproject/myname/venv/lib/python3.7/site-packages/MySQLdb/__init__.py) During handling of the … -
How to get the Current User IP in Python / Django
I am trying to capture the IP Address and the System Name of the current Login user during the login Process. I Use following code for the same: import socket system = socket.gethostname() IPAddr = socket.gethostbyname(system) It works fine in Local Server but when I push to Server it takes the server name and server IP instead of user IP. -
Django: Can't login with Allauth
I tried all login, signup process with usign allauth in Django. But I have this problem: File "C:\Users\Mircal\Desktop\Project\core\urls.py", line 22, in <module> path('accounts/login/', name='account_login'), TypeError: _path() missing 1 required positional argument: 'view' core/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('accounts/login/', name='account_login'), ] I have got apps/accounts/login.py and templates/accounts/login.html I setup this using https://django-allauth.readthedocs.io/en/latest/overview.html What can I do for solution? -
How to plug a function inside django ImageFiled
I'm trying to upload images from Django admin. the files are bigger most of them more than 5 MB, I want to rescale them so the size should be 1 MB before upload. I have a function that could re-scale the image and is working fine, But I'm not sure how to plug that function into ImageField in Django models. def scaled_image(input_image_path, output_image_path, width=600, height=None): image = Image.open(input_image_path) w, h = image.size if width and height: max_size = (width, height) elif width: max_size = (width, h) elif height: max_size = (w, height) else: # No width or height specified sys.exit("Width or height required!") image.thumbnail(max_size, Image.ANTIALIAS) image.save(output_image_path) scaled_image = Image.open(output_image_path) return scaled_image Now how can I change my ImageField so that should work doucment_image = models.ImageField(upload_to='sellerinfo', null=True, blank=True) Help would be appreciated. Thanks -
TemplateDoesNotExist heroku working fine on local
When Deploying to Heroku throws an error TemplateDoesNotExist but it works fine on local -
Django and Celery logs
We have a Django app (with Celery) that process several tens of thousands of http requests per minute. We are getting a huge volume of logs from Django like ip... - - [date...] "POST /url... HTTP/1.0" 200 311 "-" "libcurl-agent/1.0" and logs from Celery like INFO:celery.worker.strategy:Task backend.tasks.my_task_name[62c288f0-63ad-45b5-8abd-bbfe11a8b612] received INFO:celery.app.trace:Task backend.tasks.my_task_name[c633ad89-9e2c-4622-bf50-077d8dcf61b6] succeeded in 0.008994809817522764s: None How can I limit these logs? From one side I want to know that the app works. On another side, it is too much log data. Can I set something like store no more 5 log lines per second exclude errors? -
Different serializers based on user object rights
I'm looking for a way to use different serializers within a ModelViewSet depending on the request.user properties making the call. Case 1: The request.user is the owner of the profile and must use the serializer called 'UserProfileOwnerSerializer' which allows a partial edit of their properties. Case 2: request.user has full control rights over profiles properties and must therefore use 'UserProfileViewEditSerializer' Case 3: request.user has only read rights on user profiles and must use 'UserProfileViewOnlySerializer' which sets all fields to readonly. I created 3 permission checkers also used to check permissions within 'permissions.BasePermission': def haveProfileOwnerRights(request, obj): if (request.user.userprofile.id == obj.id): return True else: return False def haveProfileViewRights(request): roleRightsProfileView = [ 'MA', 'AM', 'ME', 'VI', ] role = request.user.userprofile.role if (role in roleRightsProfileView): return True else: return False def haveProfileViewEditRights(request): roleRightsProfileViewEdit = [ 'MA', 'AM', 'ME', ] role = request.user.userprofile.role if (role in roleRightsProfileViewEdit): return True else: return False class IsOwnerOrHaveProfileViewEditOrViewRight(permissions.BasePermission): def has_object_permission(self, request, view, obj): if (request.user.is_anonymous): return False if (haveProfileOwnerRights(request, obj)): return True if (haveProfileViewEditRights(request)): return True return False class UserProfileViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated, IsOwnerOrHaveProfileViewEditOrViewRight ] queryset = UserProfile.objects.all() def get_serializer_class(self): if haveProfileViewEditRights(self.request): return UserProfileViewEditSerializer if haveProfileViewRights(self.request): return UserProfileViewOnlySerializer # # MISSING SERIALIZERS FOR 'UserProfileOwnerSerializer' # I need to … -
Django - tensorflow: ModuleNotFoundError: No module named '_ctypes'
I'm using tensorflow in a django project, when I try to use tensorflow I'm getting this error: ModuleNotFoundError: No module named '_ctypes' I'm using ubuntu 22.04 and python 3.10 I already tried : sudo apt install libffi-devel but it doesn't work Thank you -
How can I optimze Django Code to only one query request
I have a simple django project which displays previous reservations dates based on id's. However currently there are 2 requests being made. (N+1 sql requests, where N is the reservation’s count) Do you have any idea how i would be able to optimize this code to only 1 query? This is the model.py file from django.db import models class Rental(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Reservation(models.Model): rental = models.ForeignKey( Rental, on_delete=models.CASCADE, related_name="reservations") checkin = models.DateField() checkout = models.DateField() def get_previous_reservation(self): latest_reservation = Reservation.objects.order_by('-checkout').filter( rental=self.rental, checkout__lt=self.checkout).first() if latest_reservation is not None: return latest_reservation.id return '-' def __str__(self): return f"({self.id}, {self.checkin}, {self.checkout})" This is the view.py file -> Where the queries are being made from django.views.generic import CreateView from .models import Reservation from .forms import ReservationForm class HomeView(CreateView): template_name = "index.html" form_class = ReservationForm success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reservations'] = Reservation.objects.all( ).select_related('rental') return context