Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I keep getting 403 respose error. I'm using django restframework with customized authentication method
Inspecting the header from postman i notice, the allowed method does not include the POST. I'm unable to make request for unauthenticated routes, i get 403. serializer_class = LoginSerializer permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: user = User.objects.get(email=request.data['email']) if user.check_password(request.data['password']): serialized_user = UserSerializer(user).data access_token = generate_access_token(user) return Response(data={'access_token': access_token, 'user': serialized_user}, status=status.HTTP_200_OK) else: return Response({'errors': 'Invalid credentials'}) except User.DoesNotExist: return Response({'errors': 'No user with such email!'})``` Here is a screenshot showing the postman header response. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/jEf0E.png -
How can I convert Inner Join and Group By to Django ORM?
I want to change this raw SQL to Django ORM but I couldn't manage to convert. most_read_students = LendedBook.objects.raw('SELECT student_id as id, name, surname, COUNT(*) as count FROM "Book_lendedbook" INNER JOIN User_student on Book_lendedbook.student_id=User_student.id where did_read=1 group by student_id order by count DESC LIMIT 5')` I tried this and I get close result.But unfortunately, I couldn't do what I want. Because I want to join this table with another table. most_read_students = LendedBook.objects.values('student_id').filter(did_read=True, return_date__month=(datetime.datetime.now().month)).annotate(count=Count('student_id')) When I use select_related with "User_student" table like this; most_read_students = LendedBook.objects.select_related('User_student').values('student_id', 'name', 'surname').filter(did_read=True, return_date__month=(datetime.datetime.now().month)).annotate(count=Count('student_id')) It throws an error like Cannot resolve keyword 'name' into field. Choices are: book, book_id, did_read, id, is_returned, lend_date, return_date, student, student_id But I should be able to get student properties like name and surname when I join "User_student" table. Thank you for your help! -
Is there a simple way to know if login has failed Django?
I am currently using Django built-in login feature. I only made my own form as you can see on this image: Login page It is really basic. Only two inputs and some formatting: <form action="#" class="login-form" method="post"> <input type="text" class="form-control input-field" placeholder="Username" name="username" required> <input type="password" class="form-control input-field" name="password" placeholder="Password" required> </form> When I enter a correct username and password, everything works and I am redirected on the correct page, but when I enter a wrong password, the login page is just reloaded, and nothing tells me the password/username was incorrect. I understand that, no matter if the password is correct or incorrect, I am redirected on the main page, but when I am not logged in (so when the password is wrong), this main page redirects me on the login page (because it is on login required). Do you know if there is a simple way to detect if a login failed and display it ? -
overwrite a model in Django
I want to overwrite the tik_id by using the function randomId so that I can generate random unique id, how can i do this?? class Tickets(models.Model): category = models.CharField(max_length=20) price=models.IntegerField() tik_id = models.CharField(max_length=20, blank=True) qr_code = models.ImageField(upload_to='qrcodes', blank=True) def __str__(self): return str(self.tik_id) def randomId(self, *args, **kwargs): tikIdCode= ''.join(random.choice(string.ascii_letters+string.digits) for i in range(8)) -
Why the fields are not getting poped in django
I have created two(ModelA, ModelB) models in models.py. I want to pop the field poster_img from ModelB for ModelC in serializer.py. I have done some part of this. but when I redirected it with http://127.0.0.1:8000/modelposter/ then I am getting JSON output like given in file. But I am not getting poster_img value in JSON file like this. This is my views.py file. There is no error showing while redirecting with http://127.0.0.1:8000/modelposter/ How can I poped the poster_img fields from ModelB? -
Search filter not working in Rest framework
A search filter was working fine in this and there's a need to filter out the list with a user-defined distance and for that, a get function is written. Now, the filter is gone. It is appearing when I comment out the get functions. class ServiceProviderList(generics.ListAPIView): queryset = ProfileCompletion.objects.all() serializer_class=ProfilecompletioneSerializer filterset_class=SnippetFilter filter_backends = [DjangoFilterBackend,SearchFilter] filterset_fields = ['fullname', 'category','departments','services'] search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name'] def get(self,request,*args, **kwargs): pk=self.kwargs.get('pk') customer = CustomerProfile.objects.get(user=pk) Dist = request.GET.get("distance") rad=float(Dist) radius=rad/111 print(radius) query = ProfileCompletion.objects.filter(location__distance_lte=(customer.location,radius)) serializer = ProfilecompletioneSerializer(query,many=True) data = serializer.data return Response({"message":"Listed Successfully.","data":data}) -
Two layer cache implementation in django
My final goal is to have a two-layer cache for every function that I want (probably a self-implemented decorator is needed) I have multiple VMs running the same Django server. The first cache layer is memory, and the second layer is a shared Redis between VMs. The process works as follows, a function is decorated for two-layer caching. In the case of function calls, the server looks for the item inside its in-memory cache. if it couldn't find it, then it will check in the shared Redis. How can I achieve this? I already have this code snippet: from cachetools.func import ttl_cache from cache_memoize import cache_memoize @ttl_cache(maxsize=settings.A_NUMBER, ttl=settings.CACHE_TIMEOUT) @cache_memoize(settings.CACHE_TIMEOUT) def my_fucn(arg1, arg2): some logic here. Django settings: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': env.str('REDIS_MASTER'), } I read this (How to use 2 different cache backends in Django?) but I don't whether it's possible to use them as a decorator. Thanks! -
Query a Barcode in django model
I have created Barcodes in my model using the following format: "YNT" + str(pk).zfill(4) + str(i.item.pk).zfill(4) + str(j + 1).zfill(5) where pk id the GRN ID and it looks like the following example: YNT0103000500055 Now when I am scanning the barcode I want to check if the item actually exists or not for that I have done this: c = request.GET['code'] try: #len(YNT) = 3 #len(grn) = 4 #len(product) = 4 #len(serial) = 5 grn = int(c[3:7]) #103 product = int(c[7:11]) #5 serial = int(c[11:]) #55 print("grn", grn) print("grn", product) print("grn", serial) obj = Grn.objects.filter(pk=grn, items__item=product) print("obj.items.item_quantity", obj.items.item_quantity) if obj.items.item_quantity>serial: res = Product.objects.get(pk=product).description I am able to get the object but how do I check the serial count i.e. serial is less or equal than the quantity of that product in the GRN GRN Model: class GrnItems(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) item_price = models.IntegerField(default=0) label_name = models.CharField(max_length=25, blank=True, null=True) class Grn(models.Model): reference_no = models.CharField(max_length=500, default=0) inward_date = models.DateTimeField(blank=True, null=True) items = models.ManyToManyField(GrnItems) -
UnboundLocalError: local variable 'insert' referenced before assignment on server side
I am new to this StackOverflow, actually, I am built a keyword research application and it is running successfully on a local server but when I deployed it into the Cpanel i.e server side it is throwing me the error like : UnboundLocalError: local variable 'insert' referenced before assignment: def funcurlscrpping(url): urldata = requests.get(url) soup = BeautifulSoup(urldata.content, "html") title = soup.title.string print ('TITLE IS :', title) meta = soup.find_all('meta') for tag in meta: if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['keywords']: insert = tag.attrs['content'] print(insert) data = insert.split(',') return data def funcurlscrppingwithkeyword(ids): for id in ids: videourl= 'https://www.youtube.com/watch?v='+ id urldata = requests.get(videourl) soup = BeautifulSoup(urldata.content, "html") title = soup.title.string print ('TITLE IS :', title) meta = soup.find_all('meta') for tag in meta: if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['keywords']: insert1 = tag.attrs['content'] print(insert1) data1 = insert1.split(',') return data1 def GetTags(request): if request.method == 'GET': url = request.GET['query'] type = request.GET['type'] valid=validators.url(url) if valid==True: obj1=[] obj1 = funcurlscrpping(url) if type == 'YouTube': return JsonResponse({"tags": obj1}, status=200) else: res = ['#' + x for x in obj1] return JsonResponse({"tags": res}, status=200) else: search_url = 'https://www.googleapis.com/youtube/v3/search' params = { 'part': 'snippet', 'q':url, 'key' : settings.YOUTUBE_DATA_API_KEY, 'maxResults' : 2, } video_ids = [] r … -
Instagram follower count.. Why is there no reliable way?
A task I've been wanting to finish for awhile is to have a dashboard where you'll have a little Instagram logo with a number which is your follower count. This means I need the latest follower count everytime the user loads the page. I have had it working before with Beautiful Soup but it was heavy and ended up getting blocked. Why is there no way to simply get the follower count of an Instagram page (not necessarily my own)? Here I have my latest attempt. I did not know you can add /?__a=1 to the url and get JSON data about the account! This works if I request the page in the browser but as soon as I implement it with requests I get a 429 status code (too many requests) import requests response = requests.get('https://www.instagram.com/nike/?__a=1') print(response.status_code) # 429 # print(response.json()) # Expecting value: line 1 column 1 (char 0) -
Heroku django3.2 deployment broken /admin menu, all routes are working for normal users except for /admin, CollectStatic not working for heroku-live
I have seen/debugged/referred multiple blogs and Stackoverflow's answers and tried almost all, but I am not able to see the admin dashboard with proper UI, as static files(CSS here) are not loaded. My Project structure is main project is bookMyTicket and I created model/subapp as bookings. I have a git repository here and the project works fine locally, with Postgres, and even on the live server except for the /admin menu. For users, live app works fine as: Github-link, Running demo Locally I did set up properly static files then checked heroku local first and had same issue. So, I did run python manage.py collect static and it created around 130+ CSS files in staticfiles directory, to make it work locally for /admin, I tried doing same on live using command: heroku run python bookMyTicket/manage.py collectstatic but it gave error as : FileNotFoundError: [Errno 2] No such file or directory: '/app/bookMyTicket/static' I tried adding whitenoise in the middleware list: 'whitenoise.middleware.WhiteNoiseMiddleware' Database config is: DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql", 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '' } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) I have declared static root too and static url. STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, … -
how to properly write urls.py in django 3.2?
I knew there is so many question and solution about how to properly writing urls.py dan views.py But still I can not solve my problem. my django version is 3.2 Here is my project urls.py from django.contrib import admin from django.urls import path, include admin.site.site_header = 'Catat Kolam' admin.site.site_title = 'CatatKolam' urlpatterns = [ path('admin/', admin.site.urls), path('catatkolam', include('catatkolam.urls')), ] Here is my app's urls.py from django.urls import path from . import views urlpatterns = [path('helloworld', views.helloworld , name='helloword')] Here is my views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def helloworld(request): return HttpResponse("Hello world") But still I got Using the URLconf defined in proj.urls, Django tried these URL patterns, in this order: admin/ [name='index'] admin/ login/ [name='login'] admin/ logout/ [name='logout'] admin/ password_change/ [name='password_change'] admin/ password_change/done/ [name='password_change_done'] admin/ autocomplete/ [name='autocomplete'] admin/ jsi18n/ [name='jsi18n'] admin/ r/<int:content_type_id>/<path:object_id>/ [name='view_on_site'] admin/ auth/group/ admin/ auth/user/ admin/ catatkolam/konfig/ admin/ catatkolam/kolam/ admin/ catatkolam/bahandasar/ admin/ catatkolam/bahancampuran/ admin/ catatkolam/tebar/ admin/ catatkolam/monitoring/ admin/ ^(?P<app_label>auth|catatkolam)/$ [name='app_list'] admin/ (?P<url>.*)$ The current path, admin/catatkolam/helloworld, matched the last one. Kindly please give me any clue to fix ths problem Sincerely bino -
I am working with django authentication and got fascinated by the hidden field in login form, can someone explains how the below line of code works?
<form action="{%url 'login'%}" method="POST"> {%csrf_token%} {%bootstrap_form form%} <input type="submit" class="btn btn-success" name="" id=" value="login"> <input type="hidden" name="next" id="" value="{{}}"> </form> I know that the URL contains the next keyword storing our previous path but I am just curious how this form influence it and btw i used loginrequiredmixin for authorization. -
Slicing geometry with geodjango based on another geometry
I have a PostgreSQL database set up and am using Geodjango to interact with the geometry saved in this database. My use case is as follows: In the database I have a complicated, large multi-polygon containing all the parks in the country. This is contained in a single geometry field. I have another record that contains the boundaries of my region. What I want to do is somehow truncate/slice the multi-polygon so that it removes those that are not within the boundaries. Sample code: region = Shapefile.objects.get(pk=1) region_boundaries = region.geometry # this contains the boundaries for the region all_parks_in_country = Shapefile.objects.get(pk=2) parks = all_parks_in_country.geometry # and this one now has all the national parks # .... And here is where I am stuck! I am providing visuals below. First map showing the entire country and in green the national parks. Second map showing in purple outline the boundaries of my region. Third map showing in red those (parts of!) the national parks multi-polygon that should ideally be 'cut out' of the national geometry. -
Django-cms: Cannot delete pages in page-tree
When I open the page tree and try to delete one of the pages, I encountered an error about 'GET actions-menu 500': I wonder if this error is due to 'bundle.admin.pagetree.min.js:1 [Deprecation] document.registerElement is deprecated and will be removed in M73, around March 2019. Please use window.customElements.define instead' in the console. Here is my environment: aldryn-apphooks-config 0.6.0 asgiref 3.3.1 dj-database-url 0.5.0 Django 3.1.7 django-admin-ip-restrictor 2.2.0 django-appdata 0.3.2 django-classy-tags 2.0.0 django-cms 3.8.0 django-filer 2.0.2 django-formtools 2.2 django-ipware 3.0.2 django-js-asset 1.2.2 django-meta 2.0.0 django-mptt 0.11.0 django-parler 2.2 django-polymorphic 3.0.0 django-sekizai 2.0.0 django-sortedm2m 3.0.2 django-taggit 1.3.0 django-taggit-autosuggest 0.3.8 django-taggit-templatetags 0.2.5 django-templatetag-sugar 1.0 django-treebeard 4.4 djangocms-admin-style 2.0.2 djangocms-apphook-setup 0.4.1 djangocms-attributes-field 2.0.0 djangocms-blog 1.2.3 djangocms-bootstrap4 2.0.0 djangocms-file 3.0.0 djangocms-googlemap 2.0.0 djangocms-icon 2.0.0 djangocms-installer 2.0.0 djangocms-link 3.0.0 djangocms-picture 3.0.0 djangocms-snippet 3.0.0 djangocms-style 3.0.0 djangocms-text-ckeditor 4.0.0 djangocms-video 3.0.0 easy-thumbnails 2.7.1 html5lib 1.1 lxml 4.6.2 Pillow 8.1.0 pip 21.0.1 pkg-resources 0.0.0 pytz 2021.1 setuptools 44.0.0 six 1.15.0 sqlparse 0.4.1 tzlocal 2.1 Unidecode 1.1.2 webencodings 0.5.1 Beside this, I have another problem: Djangocms: menu navigation error but it returned normal after zooming in······ Thank you for your help!!!! -
The object with alias 'default' was created in thread id 2281649653888 and this is thread id 2281728636176. Celery problem completing tasks
I am trying to figure out, how to get the created post id, so I could use it later to send an email to subscribers. But the system is giving me an error, that says the following: Traceback (most recent call last): File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\celery\app\trace.py", line 405, in trace_task R = retval = fun(*args, **kwargs) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\celery\app\trace.py", line 697, in __protected_call__ return self.run(*args, **kwargs) File "C:\Users\1224095\skillfactory\Testing2\NewsPaper\News\tasks.py", line 12, in Post_send post = Post.objects.get(id=oid) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\query.py", line 431, in get num = len(clone) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1167, in execute_sql cursor = self.connection.cursor() File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\backends\base\base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\backends\base\base.py", line 227, in _prepare_cursor self.validate_thread_sharing() File "c:\users\1224095\skillfactory\testing2\venv\lib\site-packages\django\db\backends\base\base.py", line 552, in validate_thread_sharing raise DatabaseError( django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 2281649653888 and this is thread id 2281728636176. my views.py … -
How to play an uploaded video in django rest framework
I have a trouble with using django-rest-framework. I uploaded some videos. And I try to play that videos in react. But I faced 404 error. I added static and media root in setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") And in react I tried like this. <ReactPlayer url={`${baseurl}/media/${videoDetaildata.url}`} playing={true} controls={true} playIcon={true}/> This works when the url is Youtube url. Please help me. Thank you in advance. -
Adding an external HTML block inside a Django block
I'm developing a Django webapp, I created the layout.html and extended to all the HTMLs. Now, i need to take a <main> block and put on another file, because the same block is used twice in the project. As far as I know, I can't make a {% load static %} inside an already extended file {% extends 'layouts/layout.html' %} . I tried with the <div data-include="path/file.html"></div> and with the $(document).ready( function() { $("#load_home").on("click", function() { $("#content").load("content.html"); }); }); but nothing. I guess the problem is that I'm using a custom script, and it must necessarily be paired with the HTML block using it. Any other ideas? I can't stand repeating code snippets... -
why permission denied for superuser in drf?
Here I set permission like this for normal users in my views but the permission applied for the superuser also(which i don't want). my superuser doesn't belongs to this query return qs.filter...exists() so I get permission denied. But I didn't get that why it is not granted all the permissions by default for superuser ? Or Am I missing something here ? permissions class MyPermission(BasePermission): def has_permission(self, request, view): qs = myqs if request.method in ['put', 'patch']: return qs.filter(change=True).exists() elif request.method == 'post': return qs.filter(create=True).exists() elif request.method in SAFE_METHODS: return qs.filter(view=True).exists() elif request.method == 'delete': return qs.filter(delete=True).exists() else: return False views class MyView(ListAPIView): serializer_class = MySerializer queryset =qs permission_classes = [MyPermission] settings 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], I solved the issue with this but I think it should not be necessary for superuser. permission_classes = [IsAdminUser | MyPermission] But I didn't get that why it is not granted all the permissions by default for superuser ? Or Am I missing something here ? -
How make a dropdown selects using django rest and jquery?
i need to make a dynamic dropdown selects about the brands and models of the cars. In using Django Rest and Jquery. This is my models.py models.py class Coche(models.Model): matricula = models.CharField(max_length=7,primary_key=True) concesionario = models.ForeignKey('Concesionario', on_delete=models.CASCADE) brand = models.ForeignKey('CocheBrand', on_delete=models.CASCADE) model_name= models.ForeignKey('CocheModel', on_delete=models.CASCADE) class CocheModel(models.Model): model = models.CharField(verbose_name="Modelo", primary_key=True, max_length=30) brand = models.ForeignKey('CocheBrand', on_delete=models.CASCADE) def __str__(self): return self.model class CocheBrand(models.Model): brand = models.CharField(verbose_name="Marca", primary_key=True, max_length=20) def __str__(self): return self.brand serializers.py class CocheSerializers(serializers.ModelSerializer): class Meta: model = Coche fields = ('matricula', 'brand', 'model_name', 'type_car', 'location', 'doors', 'gearshift', 'years', 'precio_final', 'horsepower', 'kilometres') views.py class CocheListing(ListAPIView): pagination_class = StandardResultsSetPagination serializer_class = CocheSerializers def get_queryset(self): queryList = Coche.objects.all() brand = self.request.query_params.get('brand',None) model_name = self.request.query_params.get('model_name',None) if brand: queryList = queryList.filter(brand = brand) if model_name: queryList = queryList.filter(model_name = model_name) def getBrand(request): if request.method == "GET" and request.is_ajax(): brand = Coche.objects.exclude(brand__isnull=True).exclude(brand__exact='').order_by('brand').values_list('brand').distinct() brand = [i[0] for i in list(brand)] data = {'brand':brand,} return JsonResponse(data, status = 200) def getModel(request): if request.method == "GET" and request.is_ajax(): model_name = Coche.objects.exclude(model_name__isnull=True).exclude(model_name__exact='').order_by('model_name').values_list('model_name').distinct() model_name = [i[0] for i in list(model_name)] data = {'model_name':model_name} return JsonResponse(data, status=200) Jquery script $(document).ready(function () { // reset all parameters on page load resetFilters(); // bring all the data without any filters getAPIData(); // get all countries … -
How to show a message on a user's account when his email is listed on database by other user?
I am trying to make a system where one user can send file to other user using django. He have to enter the file, it's description and the receiver's email. Here's my model class data(models.Model): file_id = models.AutoField(primary_key=True) file_desc = models.TextField() file = models.FileField() receiver_email = models.EmailField() When sender fills these fields and submits the form everything gets stored on database. Have a look at my view def send(request): if request.method=="POST": file_desc = request.POST['file_desc'] file = request.FILES['file'] receiver_email = request.POST['receiver_email'] db = data.objects.create(file_desc=file_desc,file=file,receiver_email=receiver_email) db.save() design = data() context={ 'file':design } user = request.user if request.user.is_authenticated: return render(request,'file_sharing.html',context) else: return HttpResponse('Please login to continue') Now i want to show a message on the user's account whose email was provided on receiver_email(above). -
from cassandra db tables to python models to be used in Django based application
I'm developing a web application using Django and Cassandra db. I have to use an external Cassandra db and integrate this legacy database in my application. My idea is to have the inverse of the operation that given some python models gives the corresponding Cassandra tables. The operation that I'd like to invert can be made, for my understanding, in several ways: in Django, after defining your models in the module models.py, running python manage.py sync_cassandra will create from the models the corresponding tables; thus using the API provided by ci sondjango_cassandra_engine; externally with respect to Django, I can use cqlengine and its command sync_table(table_name) to translate the Python classes defining my models into Cassandra tables. What I want is the inverse operation, that I am not able to perform neither using django_cassandra_engine in Django nor cqlengine externally from Django. I've tried to use python manage.py inspectdb --database=cassandra after I gave the connection parameter settings for the Cassandra db in the module setting.py as specified here. Though the output of this command in my case is: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' … -
how to find data between two date range in django rest framework?
Creating a simple view to list three columns in between two date range. On doing some research I found that we have some Django ORM that we can use. Hence I have tried to impletemt it in my views as shown below. from rest_framework.response import Response import django_filters.rest_framework from rest_framework.generics import ListAPIView from .models import Revenue from .serializers import DataListSerializers # Create your views here. class DataListView(ListAPIView): serializer_class = DataListSerializers pagination_class = None queryset = Revenue.objects.all() filter_backends = [django_filters.rest_framework.DjangoFilterBackend, django_filters.OrderingFilter] def get_queryset(self): time_filter = self.queryset.objects.filter(datefield__gte=<some_date>, datefield__lte=<some date>) As you could see that I have written a simple ListAPIView. When we execute the above query in the Django ORM console then we can give some date range. But how to incorporate the above query in the view? What would be the value for datefield__gte, and datefield__lte? -
How is file path security provided in Django?
I have created a system with Django. In this system, users can upload various files (with FileField). These files can be unimportant like profile photos or important like company files. I am afraid that any user can find the files by playing with the paths. Can I keep the user profile photos in a different path and the uploaded files in a different path? And can these uploaded files be a unique, hidden, or inaccessible path? -
Getting actual model instance after aggregating by maximum value (Django)
I have the following models: class Browser(Model): id = UUIDField() class Session(Model): id = UUIDField() browser = ForeignKey(Browser) last_activity = DateTimeField() I want to select the Session object with the latest last_activity for each unique Browser. I've tried Session.objects.values('browser').annotate(Max('last_activity')), but this does not give the actual Session instance. Is this possible in Django? I would like to avoid raw SQL if possible.