Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF: Cant see login option
I cant see login option in this I have the below REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.TokenAuthentication", "rest_framework.authentication.SessionAuthentication", ), } -
Sorting by user upvotes and downvotes not working properly
I currently have a model as such class IpAddress(models.Model): creado = models.DateTimeField(auto_now_add=True) ip_address = models.GenericIPAddressField(unique=True) class Palabra(models.Model): nombre = models.CharField(max_length=250) definicion = models.CharField(max_length=1000, unique=True) ejemplo = models.CharField(max_length=250) creado = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) anonimo = models.BooleanField(default=True) aprobada = models.BooleanField(default=False) userUpVotes = models.ManyToManyField(IpAddress, blank=True, related_name='threadUpVotes') userDownVotes = models.ManyToManyField(IpAddress, blank=True, related_name='threadDownVotes') gramatica = models.CharField(max_length=250, null=True, blank=True) pais = models.CharField(max_length=250, null=True, blank=True) And my ranking functions is as such defeniciones = Palabra.objects.prefetch_related( 'tag_set' ).filter( nombre__iexact=palabra, aprobada=True ).annotate( total_votes=Count('userUpVotes') / NullIf((Count('userUpVotes') + Count('userDownVotes')), 0)).order_by('-total_votes') I have a situation where a word has two upvotes and no downvotes. But a word with no upvotes or downvotes, ranks higher. I'm using NullIf due to postgres. -
django-pwa and ajax calls
I have a django applications, and there are some ajax' GET and POST request. I followed https://pypi.org/project/django-pwa/ and https://www.geeksforgeeks.org/make-pwa-of-a-django-project/. When I followed the blog from geeksforgeeks, my serviceworker would show, so I just followed django-pwa documentation. Now, my problem is that for my ajax GET/POST request, they are not working. Is this a related issue? Everything else works, but that. -
Django, DRF: When there are many m2m through tables, annotate() and count() are slow
I'm using postgres and have about 300,000 rows in Video, 2,000 in Tag, and these through tables have about 1.4 million rows. It may be because of the large number of through tables, but it takes a very long time to issue a query when calculating or filtering models with reference relationships. I've spent quite a bit of time on this and still haven't found a solution. How can I improve it? If there is any other information you need, please let me know. # models.py class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, max_length=100) is_actress = models.BooleanField(default=False, db_index=True) created_at = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-is_actress"] def __str__(self): return self.name class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000) preview_url = models.URLField(max_length=1000, blank=True, null=True) embed_url = models.URLField(max_length=1000) embed_source = models.ForeignKey(EmbedSource, on_delete=models.CASCADE) duration = models.CharField(max_length=8) tags = models.ManyToManyField(Tag, blank=True, db_index=True) views = models.PositiveIntegerField(default=0, db_index=True) is_public = models.BooleanField(default=True) published_at = models.DateTimeField(default=timezone.now, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ["-published_at"] def __str__(self): return self.title # serializers.py class TagSerializer(serializers.ModelSerializer): count = serializers.IntegerField() class Meta: model = Tag fields = ("pk", "name", "is_actress", "count") # views.py class TagListPagination(PageNumberPagination): page_size = 100 class TagListView(generics.ListAPIView): serializer_class … -
Unable to add Items to cart
I'm using django and react to build a simple checkout system, and want some help to fix this error. I'm not sure whether my function for the onclick event is accurate in the programme below. I'm finding great difficulty trying to figure out why I'm not able to add Items to the cart by clicking on the cart button using onClick event. The error I'm getting on js console on browser is page not found, and the url on the console is pointing to the actual url containing the id of the element I'm trying to add. Whenever I click on the add to cart button that 404 page not found` error appears both in js console on the browser and in the django server on the terminal. The react component const ProductDetails = (props) => { const [product, setProduct] = useState({}); useEffect(() => { const id = props.match.params.id; const fetchData = async () => { try { const res = await axios.get(`${ProductDetailURL}/product/${id}`); setProduct(res.data); console.log(res.data) } catch (err) { } }; fetchData(); }, [props.match.params.id]); const handleAddToCartURL = (id) =>{ const fetchData = async () => { try { const res = await axios.post(`${AddToCartURL}/add-to-cart/${id}`); setProduct(res.data); console.log(res.data) } catch (err) { } … -
How to save data from input fields in Django?
I want to save the date that the user will select from the datetimepicker and at the same time, it will auto calculate the age using the onchange event. Here is the code from my template. <div class="form-row"> <div class="form-group col-md-2"> <label><b>Birthday: </b></label> <input class="form-control" type="date" id='birthday' onchange="ageCount()" value="{{form.c_birthday}}"> </div> </div> and here is my function ageCount() function ageCount() { var now =new Date(); var currentY= now.getFullYear(); var currentM= now.getMonth(); var dobget =document.getElementById("birthday").value; var dob= new Date(dobget); var prevY= dob.getFullYear(); var prevM= dob.getMonth(); var ageY =currentY - prevY; var ageM =Math.abs(currentM- prevM); document.getElementById('demo').value = ageY; } Everytime I use add this code, value="{{form.c_birthday}}" it saves the date that user will select, but it displays "> and I do not know how to remove that. -
Is there an alternative to using a serializer for drf-spectacular's extend_schema request param?
I'm using drf-spectacular to generate swagger/redoc API documentation. One of the most useful features is the ability to test requests via the generated swagger html page, but I'd like to enforce the application/x-www-form-urlencoded content-type so that when the request is received by my Django endpoints, the request.data has the encoded data instead of it ending up as part of a query string. drf-spectacular always seems to default to query strings e.g. /objects/action/?key=value The only way I've figured out how to do this is to use a serializer in conjunction with the request content-type e.g. @extend_schema( request={'application/x-www-form-urlencoded': DoTheActionInputsSerializer}, responses={200: DoTheActionOutputsSerializer}, methods=["POST"] ) @action(methods=['post'], detail=False) def do_the_action(self, request, *args, **kwargs): ... This works great, but it does require a lot of small serializers that may only have one or two attributes. Is there an alternative way of achieving this inside the extend_schema decorator? I was hoping something like the following would work, but doesn't request={'application/x-www-form-urlencoded': {'schema': {'foo_id': OpenApiTypes.INT}}}, -
How to properly save instance of FileField in Django
Im hoping someone can tell me what I am doing wrong and point me in the right direction. So, I am creating an array of Model objects and then doing a bulk_create at the end to save them to the database. The one thing I am having an issue with is after I added the the FileField I cannot exactly how I need to associate data with that field. The files don't end up in the upload_to folder set nor do they end up being associated with the record itself. Id also add that I am using PyPDf2 to create the PDF files before trying to associate them to an instance of my model. So to give you an idea on what I am trying to do. I am running this code to create the PDFs initially. if pdf_file_name is not None: num_pages_current_doc = page['pageRange'][-1] input_pdf = PdfFileReader(open(pdf_file_name, 'rb')) output_pdf = PdfFileWriter() for _ in range(num_pages_current_doc): output_pdf.addPage(input_pdf.getPage(page_counter)) page_counter += 1 with open(str(uuid.uuid4())+'.pdf', 'wb') as output: output_pdf.write(output) logging.info(f'Wrote filename: { output.name }') The saved file I then want to associated with a model instance below this, the code looks something like this: document = document( location=location, Field2=Field2, etc etc ..... pdf … -
Extending the _range lookup in Django, with a custom lookup
I'd like to extend the functionality of the _range lookup, so that None values are considered infinity. Rather than only being able to do: .filter(created_at_range=[start, end]) I want to be able to do also .filter(created_at_nullablerange=[None, end]), .filter(created_at_nullablerange=[start, None]) and .filter(created_at_nullablerange=[None, None]) I understand it is possible to specify custom lookups in Django: from django.db.models import Lookup class Nullablerange(Lookup): lookup_name = 'nullablerange' def as_sql(self, qn, connection): # Actual SQL text must be returned here Datetime.register_lookup(Nullablerange) However, I'd like to do this by inheriting from the already existing _range filter, as I'd like to write as less custom SQL as possible. Is this possible? Do I have better alternatives (custom managers are inappropriate, as I want this to be available for all my models with datetime fields)? In which .py file should I register my custom lookups so that they're always included? -
Why am I receiving a ValueError in my django application?
I was following this tutorial to build a simple polling application using Django and I ran into the following error: ValueError: source code cannot contain null bytes Which appears in line 3 of the following code block: urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] I have determined that this error exclusively occurs when utilizing the include() function. Below is the stack trace that I'm getting, but aside from that I am clueless as to where to go from here. -
trying to build new Dockerfile in django app and it keeps throwing "bash: docker: command not found" error when trying to run "docker build ."
so im doing a django/DRF tutorial on udemy and were setting up a Dockerfile for the app and im not sure whats happening here but every time i try to run build dockerfile command in the terminal it doesnt seem to recognize the "docker build ." command. i cd'd into this app's filepath and the dockerfile is there so im not seeing why this is happening. im doing it exactly like the guy in the tutorial is doing so not sure why my terminal doesn't recognize this command. (yes im sure this is a stupid question lol but im a noob so bear with me) this is the error im seeing in the terminal -
Django DRF: ModelMixin Viewset: How to create a viewset to get user details and edit user details without passing id in url
Suppose my user is logged in and he want to see the user details I want to create an api end point like /userdetails/ Based on the user who logged in it should return back the details. This is my serializer class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "id", "email", "first_name", "last_name", "is_staff", "is_active", "date_joined", "last_login", "modified_date", "creation_date", ] read_only_fields = [ "email", "is_staff", "is_active", "is_superuser", "date_joined", "last_login", ] Now I want to create a viewset for read and edit I want something like this class UserDetailsViewSet( mixins.UpdateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = User.objects.all() serializer_class = UserDetailsSerializer and router.register(r"userdetail",UserDetailsViewSet ) But the problem with the above is I dont want urls like /userdetail/<pk> instead only /userdetail. Because the <pk> can be obtained from the request.user -
Postgresql not working with django on Macos: El Capitan
I installed Postgresql from the official site (version 4.0), I created a database with "pgAdmin 4", and tried to connect my django project to it. But an error prevented me from the running the django server, the error says: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> import psycopg2 as Database File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): Symbol not found: ____chkstk_darwin Referenced from: /Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/psycopg2/.dylibs/libcrypto.1.1.dylib Expected in: /usr/lib/libSystem.B.dylib in /Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/psycopg2/.dylibs/libcrypto.1.1.dylib During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen … -
How to Deploy Django project in Cpanel that shows neither setup python app nor terminal?
I have finished creating a Django app and i want to deploy it in webserver Cpanel, it is my first time, but it seems my client has a cheap hosting plan that has Cpanel without setup python app nor terminal so i have found no way to install python and python app. Is there a way i can get these things in the Cpanel software section or install python and Deploy Django app. I have been searching for some days but there seem to be no relevant answer according to the problem i face. The Cpanel shows a softaculous as a way to install softwares in the server. -
How out from nested JSON in JSON, get this date and do serialization for API in Django RestFramework
Hi I'm new in DRF and need a help . I write API.Then user ,for example, put in url http://api.result/82467/pulse , then he get information for result whith number 82467 and measurement of pulse (must to get only this data): { "code": "1120", "norm": null, "value": "1", }, { "code": "1121", "norm": null, "value": "2", } and if http://api.result/82467/termom then he get information for result whith number 82467 and measurement of termom (must to get only this data): { "code": "1118", "norm": "35.9 - 37.0", "value": "36.5", } I get this data from db and give information for user, that`s why I must serialize this data. field "type" is dynamic.Field "exams" is JSONField() in model Result and "code","value" and "norm" - BaseData objects .My problem is in point, when I must get fields from "review"("code","value" and "norm") in views.py for serialization , because it is json and I don't know how I must work with it , how get this data and how do serialization . Maybe json.dump() but then I got str and can't convert in dict . Maybe someone give me some advice, please. { "id": 56, "number": "82467", "date": "2021-08-19", "exams": [ { "type": "termom", "stamp": "2021-08-19R17:00:17", … -
Django/React/Postgres One-to-Many wont update hero_id column to user_id
I am trying to store the UsersHeroes to the UserAccount database by doing a one-to-many relational database. It seems to work fine when I manually set the UserHero from the Admin site to relate to a user but when it comes to trying to submit it on the front end, it just defaults it to 1 since I set it up that way in the model. If I am logged in as user id = 2 and create a hero with that user logged in, it will only save it to user id = 1. This is how my models is set up: class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): #allows you to create user if not email: raise ValueError("Adventurers must have an email address or you shall not pass.") email = self.normalize_email(email) #normalize is a built in function to normalize email user = self.model(email = email, name = name) #normalizes capital to lowercase user.set_password(password) #hashes password for security and sets database # if hacker hacks database you see it user.save() #saves the user return user def create_superuser(self, email, name, password=None ): u = self.create_user(email, name, password) u.is_staff = True u.is_active = True u.is_superuser = True u.save(using=self._db) return u class … -
iterating with django customized filters
SO i'm trying to use symbols on my textarea to edit the users input when it's been displayed on the website, but my problem is after getting all the text within the symbols i.e ( __ myText __ ), The output isn't what it's meant to be, this is the output 👆👆 and this is the input 👆👆👆, python isn't iterating through the article completely as the code above tells it to but instead it just stops at the first text in-between the double-underscore(_). I would appreciate as you help me out :) -
Can't show progress bar in PyTube
I'm wrote a video downloader in Python Django and I'm using PyTube. There is an extra function from PyTube which allows you to show an progress bar. I wrote some lines from the bar but this erorr appears: TypeError: progress_function() missing 1 required positional argument: 'bytes_remaining' I'm sure my code isn't complete yet but I cant figure out what to change that everything works. This is my code: views.py def converter(request): download_begins = True if request.method == 'POST': link = request.POST['link'] video = YouTube(link) format = request.POST['format'] uuid = shortuuid.ShortUUID().random(length=4) if format == "3": with OpenKey(HKEY_CURRENT_USER, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') as key: downloads = QueryValueEx(key, '{374DE290-123F-4565-9164-39C4925E467B}')[0] yt = YouTube(link, on_progress_callback=progress_function) audio_file = yt.streams.filter(only_audio=True).first().download(downloads) base, ext = os.path.splitext(audio_file) new_file = base + uuid + '.mp3' os.rename(audio_file, new_file) elif format == "4": with OpenKey(HKEY_CURRENT_USER, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') as key: downloads = QueryValueEx(key, '{374DE290-123F-4565-9164-39C4925E467B}')[0] yt = YouTube(link, on_progress_callback=progress_function) ys = yt.streams.filter(res="1080p").first().download(downloads) base, ext = os.path.splitext(ys) new_file = base + uuid + '.mp4' os.rename(ys, new_file) context = {'format': format, 'begins': download_begins} return render(request, 'home/videoconverter.html', context) return render(request, 'home/videoconverter.html') def percent(tem, total): perc = (float(tem) / float(total)) * float(100) return perc def progress_function(stream, chunk, file_handle, bytes_remaining): size = stream.filesize p = 0 while p <= 100: progress = … -
django select_for_update acquires relation lock
I have this code sample that should take row (tuple) lock in postgres, however it seems to take table (relation) lock instead: with transaction.Atomic(savepoint=True, durable=False): record = MyModel.objects.select_for_update().filter(pk='1234') record.delete() time.sleep(5) raise Exception By looking at the pg_locks during the time of the transaction I can see: select locktype, database, relation::regclass, pid, mode, granted from pg_locks where pid <> pg_backend_pid(); For my knowledge, I should have seen "tuple" in the locktype since I'm only locking specific row/s and not the entire table -
Filter by fields from foreignKey relationships
I got a bunch of models and some of them are connected (by foreign-key relationships) and I wrote a serializer which allows me to print out all of the connected fields that I want, and leave out what I do not want to see. Great. Now I also have a basic filter, which uses the model (PmP) which contains all the foreignkeys, but now I want to add another filter for a field (field name e from PmPr Model) from a different Model, one that is read in via foreignkey connection (pr in Model PmP). But I dont know how to do that and as far as I can see, I cant set two filter_classes inside my view (PmPLListView)?! And I dont know how to access the field via the foreignkey relation. So how do I go about this? If I can access the e field from PmPr Model via my existing filter - than that is also fine with me, I dont necessary want two filter classes (if even possible). It was just me first thought. (btw. sorry about the strange names, but unfortunately I'm not allowed to write the real names) these are my models (at least the … -
Unable to fetch data from mysql using django
I am not getting the data into the table. I assure you that I didn't get any errors while running python manage.py runserver and my database connection with Django is working perfectly. I also assure you that the table in my database has adequate data and there is no issue in the database. From views.py: from django.shortcuts import render, HttpResponse from anapp.models import Tblchkone # Create your views here. def main(request): return render(request, 'main.html') def getTblchkone(request): allcategories = Tblchkone.objects.all() context = {'allcategories' : allcategories} return render(request, 'main.html', context) From models.py: from django.db import models from django.db.models.base import Model # Create your models here. class Tblchkone(models.Model): categoryId = models.BigAutoField(primary_key=True, editable=False) categoryName = models.CharField(max_length=14, unique=True) From main.html: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>MAIN</title> </head> <body> <table class="table"> <thead> <tr> <th scope="col">Category_Id</th> <th scope="col">Catefory_Name</th> </tr> </thead> <tbody> {% for x in getTblchkone %} <tr> <td>{{x.categoryId}}</td> <td>{{x.categoryName}}</td> </tr> {% endfor %} </tbody> </table> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> -
Is settings CORS_ALLOW_ALL_ORIGINS in production ever okay?
I have a project where many different domains will be making requests to my django API, these domains will frequently change and I will not know what these domains will be, so have no way of whitelisting them. Is it okay to set CORS_ALLOW_ALL_ORIGIN to True, and if not, what security risks do I face, and is there an alternative method I can approach this with if so? -
Extract JSON content in Metabase SQL query
Using: Django==2.2.24, Python=3.6, PostgreSQL is underlying DB Working with Django ORM, I can easily make all sort of queries, but I started using Metabase, and my SQL might be a bit rusty. The problem: I am trying to get a count of the items in a list, under a key in a dictionary, stored as a JSONField: from django.db import models from jsonfield import JSONField class MyTable(models.Model): data_field = JSONField(blank=True, default=dict) Example of the dictionary stored in data_field: {..., "my_list": [{}, {}, ...], ...} Under "my_list" key, the value stored is a list, which contains a number of other dictionaries. In Metabase, I am trying to get a count for the number of dictionaries in the list, but even more basic things, none of which work. Some stuff I tried: Attempt: SELECT COUNT(elem->'my_list') as my_list_count FROM my_table, json_object_keys(data_field:json) AS elem Error: ERROR: syntax error at or near ":" Position: 226 Attempt: SELECT ARRAY_LENGTH(elem->'my_list') as my_list_count FROM my_table, JSON_OBJECT_KEYS(data_field:json) AS elem Error: ERROR: syntax error at or near ":" Position: 233 Attempt: SELECT JSON_ARRAY_LENGTH(data_field->'my_list'::json) FROM my_table Error: ERROR: invalid input syntax for type json Detail: Token "my_list" is invalid. Position: 162 Where: JSON data, line 1: my_list Attempt: SELECT ARRAY_LENGTH(JSON_QUERY_ARRAY(data_field, '$.my_list')) … -
How to implement custom django filter for aggregated data from related model
models.py ... class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Hike(models.Model): hiker = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='hikes') hike_date = models.DateField(max_length=100, blank=False) distance_mi = models.FloatField(blank=False) views.py ... class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer serializers.py class PersonSerializer(serializers.ModelSerializer): hikes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) all_hikes = Hike.objects.all() def total_mi(self, obj): result = self.all_hikes.filter(hiker__id=obj.id).aggregate(Sum('distance_mi')) try: return round(result['distance_mi__sum'], 2) ... total_miles = serializers.SerializerMethodField('total_mi') ... class Meta: model = Person fields = ('id','first_name','last_name','total_miles') filters.py class HikerFilter(django_filters.FilterSet): hiker = django_filters.ModelChoiceFilter(field_name="hiker", queryset=Person.objects.all()) class Meta: model = Hike fields = { 'hiker': ['exact'], 'hike_date': ['gte', 'lte', 'exact', 'gt', 'lt'], 'distance_mi': ['gte', 'lte', 'exact', 'gt', 'lt'], } *simplified data +---------+------------+-------------+ | hike_id | hike_date | distance_mi | +---------+------------+-------------+ | 2 | 2020-11-02 | 4.5 mi | | 3 | 2021-03-16 | 3.3 mi | | 5 | 2021-08-11 | 5.3 mi | | 7 | 2021-10-29 | 4.3 mi | +---------+------------+-------------+ The Person view includes "total_miles" stat added via the Serializer (total_mi). Person endpoint http://localhost:8000/persons/2/ { "id": 2, "first_name": "Miles", "last_name": "Marmot", "hikes": [ 2, 3, 5, 7 ], "total_miles": 17.4, }, Currently, the "total_miles" is for all years. My QUESTION: how can I filter "total_miles" in the Person view by a specific year? e.g. http://localhost:8000/persons/2/?year=2020 > "total_miles": 4.5, e.g. … -
How to redirect back two pages Django?
I have a book page. On this page is the button "In favorite". If the user clicks on the button and is authenticated, it will use addBookmark view to add a new object into the database(and just reload the book page). However, if the user isn't authenticated, it'll redirect to the login page firstly. @login_required def addBookmark(request, slug): book = Book.objects.get(slug=slug) if BookMark.objects.filter(user=request.user, book=book).exists(): bookMark = BookMark.objects.get(user=request.user, book=book) bookMark.delete() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) newBookMark = BookMark.objects.create(user=request.user, book=book) newBookMark.save() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) The problem: When a user is redirected to the login page, the next URL will just add a new object in db and reload the page, but this is the login page. How can I redirect users back to the book page if the user isn't authenticated firstly?