Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: Field 'song_id' expected a number but got 'Remove from Favourites '
ValueError: Field 'song_id' expected a number but got 'Remove from Favourites'. Django Music web App: I have added "Add to Favourite" feature, But Can't add "Remove from Favourite" feature Favourite.html <form action="/music/favourites" method="POST">{% csrf_token %} <input type="hidden" name="video_id" value="{{song.song_id}}"> <button type="submit" class="btn btn-outline-danger">Add to Favourite</button> </form> <form method="post"> {% csrf_token %} <input type="submit" class="btn btn-outline-danger" value="Remove from Favourites" name={{song.id}} > </form> #models.py class Song(models.Model): song_id = models.AutoField(primary_key= True) name = models.CharField(max_length= 2000) singer = models.CharField(max_length= 2000) tags = models.CharField(max_length= 100) image = models.ImageField(upload_to = 'docs') song = models.FileField(upload_to= 'docs') movie = models.CharField(max_length = 150, default = "None") def __str__(self): return self.name class Favourites(models.Model): watch_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) video_id = models.CharField(max_length=10000000, default="") #Views.py def favourites(request): if request.method == "POST": user = request.user video_id = request.POST['video_id'] fav = Favourites.objects.filter(user=user) for i in fav: if video_id == i.video_id: message = "Your Video is Already Added" break else: favourites = Favourites(user=user, video_id=video_id) favourites.save() message = "Your Video is Succesfully Added" song = Song.objects.filter(song_id=video_id).first() return render(request, f"music/songpost.html", {'song': song, "message": message}) wl = Favourites.objects.filter(user=request.user) ids = [] for i in wl: ids.append(i.video_id) preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(ids)]) song = Song.objects.filter(song_id__in=ids).order_by(preserved) return render(request, "music/favourite.html", {'song': song}) This function is … -
Bypassing django-rest-framework APIExceptions
I would like to understand the implications of the following design choice for an application built using DRF. Is it okay if I choose to raise exceptions that are not an instance of APIException in conjunction with a custom_exception_handler that can handle all these exceptions? From what I understand, the handler for a specific request is determined within the rest_framework.views.APIView.dispatch method (source) and the handler gets called within the try...catch.. block in this dispatch method (source). So this way any exceptions that are raised during the execution of the handler are caught within the dispatch method are delegated to the exception handler (default or custom). As we can see here the dispatch method catches not an APIException but any and all Exception. So could I simply raise my own CustomException(s) that are sub-classes of Exception through out my application and simply handle all these exceptions the way I want in the custom_exception_handler? I understand that the ValidationError will be an exception to this, as the serializers and in-built validators all raise ValidationError. If I can override the rest_framework.serializers.Serializer.is_valid in MyCustomSerializer I can catch the rest_Framework.serializers.ValidationError and throw MyOwnCustomValidationError which can be handled by the custom_exception_handler. Something like this: def is_valid(self, … -
How to add many filed in Django
i decided to create movies website with Django , i want to add , for example ** season 1 - series 1 , season 1 - series 2, season 2 - series 1 season 2 - series 1 ** what is best way ? i mean when i add TV shows once and how to add then series and seasons ? this is my model.py class Movie(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=100) year_of_production = models.TextField(max_length=10) view_count = models.IntegerField(default=0) link = models.TextField(max_length=70) def get_absolute_url(self): return reverse('post',kwargs={"post_slug":self.slug}) def __str__(self): return "{} -------------- {}".format(self.title,self.status) -
Python/Django Query to check if Dates Overlap
I'm trying to set up a validation on an API built with Python/Django. I'm using a serializer and would like to do a query filter against the post data to make sure 2 date fields do not overlap. For example: My Post contains: "valid_start": "2021-09-01", "valid_end": "2021-09-15" I would like to an object.filter to check if there are any records in my database with overlapping dates: I want to throw a validation error if the query detects any of the following "valid_start": "2021-09-01", "valid_end": "2021-09-15" "valid_start": "2021-09-02", "valid_end": "2021-09-15" "valid_start": "2021-09-03", "valid_end": "2021-09-10" "valid_start": "2021-08-28", "valid_end": "2021-09-20" I've tried the __range function, gte/lte functions, none really do what I'm trying to achieve. Thanks! -
how create simple many-to-many relations with django rest
i am new in django and migrate from symfony. i want to try create simple relation between 2 model in django-rest-framework and get apiview for them. but i can undrestand why serializers not handle relations between this 2 models. my models in models.py from django.contrib.gis.db import models from django.contrib.gis.geos import Point import uuid class RequestLocation(models.Model): gpslocation = models.PointField(srid=4326, geography=True, default=Point(0.0, 0.0)) gpslocationradius = models.IntegerField(default=5) description = models.TextField(default='#') created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] def __str__(self): return self.id class Shops(models.Model): gpslocation = models.PointField(srid=4326, geography=True, default=Point(0.0, 0.0)) created = models.DateTimeField(auto_now_add=True) requestlocations = models.ManyToManyField(RequestLocation, null=True, blank=True) class Meta: ordering = ['created'] def __str__(self): return self.id and my serializers in serializers.py: from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import RequestLocation, Shops class RequestLocationSerializer(GeoFeatureModelSerializer): class Meta: model = RequestLocation geo_field = 'gpslocation' auto_bbox = True id_field = 'id' fields = ['id', 'gpslocation', 'gpslocationradius', 'description'] class ShopsSerializer(GeoFeatureModelSerializer): requestlocations = RequestLocationSerializer(read_only=True) class Meta: model = Shops geo_field = 'gpslocation' auto_bbox = True id_field = 'id' fields = ['id', 'gpslocation', 'requestlocations'] and views.py: # RequestLocation view @api_view(['GET', 'POST']) def rl_list(request, format=None): if request.method == 'GET': rl = RequestLocation.objects.all() serializer = RequestLocationSerializer(rl, many=True) distance_filter_field = 'geometry' filter_backends = (DistanceToPointFilter) bbox_filter_include_overlapping = True return Response(serializer.data) elif request.method == 'POST': … -
Django: The view didn't return an HttpResponse object. It returned None instead. When Override Form_Valid
I overrode the form_valid method on my RobotDetail view but whenever I try to use the view I get the error The view dashboard.views.RobotDetail didn't return an HttpResponse object. It returned None instead. If anybody knows how to fix this it would be super appreciated! VIEW from django.shortcuts import render from django.views.generic import ListView, DetailView, UpdateView from .models import Robot from .forms import RobotUpdateForm import socket import threading HEADER = 64 PORT = 6060 SERVER = socket.gethostbyname(socket.gethostname()) ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" class RobotDetail(UpdateView): model = Robot form_class = RobotUpdateForm template_name = 'dashboard/robotdetail.html' def form_valid(self, form): self.object = form.save() client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) def send(msg): message = msg.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER - len(send_length)) client.send(send_length) client.send(message) send("Hello World!") send("Hello Andrew") send("Hello") send(DISCONNECT_MESSAGE) MODEL class Robot(models.Model): def fetch_choices(): scope = [REDACTED] creds = ServiceAccountCredentials.from_json_keyfile_name("dashboard/Files/creds.json", scope) client = gspread.authorize(creds) sheet = client.open("tutorial").sheet1 path_names = [] path_name_fetch = sheet.col_values(1) for i in path_name_fetch: if (i, i) not in path_names: path_names.append((i, i)) return path_names name = models.CharField(max_length=200) path_options = models.CharField(choices=fetch_choices(), default=fetch_choices(), max_length=100) status_choices = [('waiting', 'waiting'), ('running', 'running'), ('stuck', 'stuck')] current_status = models.CharField(choices=status_choices, default=status_choices[0], max_length=100) def __str__(self): return self.name + … -
Does YugabyteDB support Django even though the SAVEPOINTS feature is not yet supported?
Have a Django app setup to talk to YugabyteDB, but while running migrations we run into the following error: Traceback (most recent call last): File "/opt/env/lib/python3.6/site-packages/django/contrib/contenttypes/models.py", line 54, in get_for_model ct = self.get(app_label=opts.app_label, model=opts.model_name) File "/opt/env/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/env/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/env/lib/python3.6/site-packages/django/db/models/query.py", line 464, in get_or_create return self.get(**lookup), False File "/opt/env/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/opt/env/lib/python3.6/site-packages/django_prometheus/db/common.py", line 63, in execute return super(CursorWrapper, self).execute(*args, **kwargs) psycopg2.errors.FeatureNotSupported: SAVEPOINT <transaction> not supported yet LINE 1: SAVEPOINT "s140500455238528_x1" ^ HINT: See https://github.com/YugaByte/yugabyte-db/issues/1125. Click '+' on the description to raise its priority Since YugabyteDB does not appear to support SAVEPOINTS today, how can we get around this Django error? [DISCLAIMER: This question was first asked by a YugabyteDB user over email] -
how to filtered 2 Q conditions in query django?
so,i have a List of all mobile phones whose brand name is one of the incoming brands. The desired brand names will be entered. The number of entries is unknown and may be empty. If the input is empty, the list of all mobile phones must be returned. model: class Brand(models.Model): name = models.CharField(max_length=32) nationality = models.CharField(max_length=32) def __str__(self): return self.name class Mobile(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model = models.CharField(max_length=32, default='9T Pro', unique=True) price = models.PositiveIntegerField(default=2097152) color = models.CharField(max_length=16, default='Black') display_size = models.SmallIntegerField(default=4) is_available = models.BooleanField(default=True) made_in = models.CharField(max_length=20, default='China') def __str__(self): return '{} {}'.format(self.brand.name, self.model) query: from django.db.models import F, Q def some_brand_mobiles(*brand_names): query = Mobile.objects.filter(Q(brand__name__in=brand_names) | ~Q(brand__name=[])) return query If the input is empty, the list of all mobile phones will be returned, but i cant use *brand_names to return the list. for example query = Mobile.objects.filter(Q(brand_name_in=['Apple', 'Xiaomi'])) return query It works alone, but it does not check both conditions with the function I wrote. how to fix it ? -
Django: Send current logged in user as JSON
I would like to create a GET endpoint that returns the JSONResponse of the current logged-in user. Ideally, it would look like: { "username": "joe", "email": "joe@plainviewhcp.com", "first_name": "", "last_name": "", "last_login": "2021-09-17T17:11:00.039Z", "is_superuser": true, "is_active": true } (Note that I'm using Django 3.2, not Django REST API) This requires serializing the current user object, but serializing a single object is... opaque in the documentation, and many similar questions have responses from 6 or more years/two major versions ago. -
How does Django know if object exists
Let's say I have two models, for example: class Product: product_name = models.CharField(max_length=40) class ProductPrice(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE) product_price = models.FloatField() Please don't bother why someone might want two different models/tables for such data. That's not the main point here. What's interesting is, when I query a Product I will get a python attr productprice along with the object ONLY IF ProductPrice exist associated with that Product. To make this more clear let's create some dummy data: product1 = Product.objects.create(product_name='first product') product2 = Product.objects.create(product_name='second product') product_price = ProductPrice.objects.create(product=product2, price=10.99) Now try this print(hasattr(product1`, "productprice")) # -> false print(hasattr(product2`, "productprice")) # -> true How does django know that a ProductPrice exist in database? In SQL I am not aware of any way to check this without second query. I am very curious how this works. -
What is a better approach to cache data in django app when running on gunicorn
I have a django application that is running on gunicorn app server. Gunicorn running N wokers. We know that each worker is a separate python proccess. In one of my applications services i have a query to a database that takes long time (10-20 sec). Ok i decided to cache the result, so just simply add django.core.cache and call cache.get(key) if result is not None app returned data from cache if not it called service and stored data in cache using cache.set(key, data, time). But if we have a N workers and first query was addressed to worker 0 app stored result of long running service in cache (process memory) of worker 0 but when simillar (request contains paging option, but i store whole RawDataSet in memory, so every page returns fast) request is addressed to worker 1 cache as expected would't work because this is a different process. So obviously i have to use some cache that could be used by all workers. What approach (i.e. use in memory database or something different) is better to use to solve this issue? -
Django cumulative sum or running sum
I am trying to make a party ledger. which details will show by a date search result. I have a column name balance which will display cumulative data by the date search. I want to view cumbalance column in my table depends on balance column. -------------------------------------- amount payment balance CumBalance -------------------------------------- 10 5 5 5 20 5 15 20 10 15 -5 15 My views.py def partyDetails(request,pk): form = DateRangeForm() if request.method == 'POST': form = DateRangeForm(request.POST or None) if form.is_valid(): cumulative_balance = PurchasePayment.objects.all() .filter(vendor=pk,date__range= (form.cleaned_data['start_date'], form.cleaned_data['end_date'])) .annotate(cumbalance =Sum('balance')) else: return redirect('party_ledger') return render(request, 'purchase/party_details.html', {'dateform':form, 'cumbal':cumulative_balance,'name':pk}) I have also tried .aggregate(Sum('balance')) -
How to make new web page for each unique ID with Django
I have a dataset where each unique ID needs its own webpage with a set of visualizations. I want to generate a new webpage iteratively for each unique ID. I am doing this with Django. Is anyone aware of any examples or guidance on how to do this? -
How to "disable" default primary keys in djongo
I'm getting this error after upgrading to djongo 1.3.6 ERRORS: some_app.Some_Class: (models.E026) The model cannot have more than one field with 'primary_key=True'. this is the class giving the error: # some_app/some_class.py from djongo import models class Some_Class(models.Model): _id = models.ObjectIdField() event_id = models.IntegerField(primary_key=True) league = models.CharField(max_length=512) event_date = models.IntegerField() event_text = models.CharField(max_length=512) event_group_id = models.IntegerField() group_name = models.CharField(max_length=512) as you can see I have only one PK defined, but apparently djongo is creating the another one. Any idea on how to disable this djongo behaviour???? -
filter_fields with DjangoFilterBackend
I have a model called Product class Product(models.Model): id name created_at updated_at price and so on.... i want to filter using all of the above attributes, which will be passed in query_params at this moment i am using DjangoFilterBackends with filter_fields but to support all attributes i have to mention all the attributes in filter_fields like below in views filter_fields = ['id', 'name', 'created_at', 'updated_at', 'price'] its working fine, but in actual model the fields are alot, which is causing code quality degradation. is there any way to include all fields in filter_fields ?? i tried filter_fiels = ['all'], but its not working. -
What options need to be specified in the CACHES variable of Django's settings.py file to connect with an azure vm
My goal is to use a Linux (ubuntu 20.04) azure vm to run a caching service for django. I am running memcached on a Linux (ubuntu 20.04) azure vm. I am using django-pymemcache which extends the pymemcache library and is a wrapper around memcached. settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '53.171.42.209', 'OPTIONS': {} } } I've tested it while running the memcached service locally and specifying a location of (127.0.0.1:11211) and it works as expected. I know that the memcached service is listening on port 11211 of the azure vm. I've opened up inbound rules on azure to allow connection. But it refuses my connection, I assume because I haven't specified any sort of credentials to connect to it. I can't figure out how to do that piece, and if it's the only thing that I'm missing. -
Django/Javascript - How to generate link for a protected resource?
I would like to know if it's possible to generate the content of .href=... after the user has clicked the button and not in advance. If I look at my page source code I can see the full link :( <a type="button" class="btn btn-outline-primary" target="_blank" onclick="location.href='{% url 'stream' pk=track.file.pk|safe|cypher_link_stream %}'"><i class="fad fa-play-circle"></i></a> Thanks. -
request.POST.getlist returns a list of strings - how to get integers instead
I have some form fields, say: <input name="item" value="2"> <input name="item" value="3"> <input name="item" value="4"> When I obtain these in my Django view by using getlist, I obtain the following: items = request.POST.getlist("item") # items = ['2', '3', '4'] Is there a way to get these as integers and not strings? Or should I convert these to integers manually (eg through list comprehension)? -
Django or Flask synchronous one-time run and return to subprocess or system call in python and or vim
That's a mouthful of a title and i had a really hard time searching for what I'm trying to do pulling up tons of false hits. Let me explain. Say I am in a python script that requires some input values in real-time. Normally you use input for simple cases. But in my case, I want to synchronously fire up a django (or flask) app view route in a real browser that allows me to create the values I need in real-time on a real live page. These values don't exist so this can NOT be implemented using an API otherwise it would be easy! I want the original python program to block / wait until i fire "submit" on the live django (or flask) page. Then somehow I need the values that were submitted to be routed back to the calling python program that is still blocking / waiting for the values. Obviously I'm trying to make http which is asynchronous somehow act as synchronous. I'm not sure this can even be done but my thought was that if I could: have subprocess block by starting the run of the django dev server itself + open the desired page … -
AttributeError: 'str' object has no attribute 'ValidationError' Django
I am trying to create Views.py method where I check if the email already exists in the database. It worked for username but it is not working for emails or tokens. What would be the way to make that possible? Thank you! @api_view(['POST']) def send_user_details(request): if request.method == "POST": serializer = SignUpDetailsForm(data=request.data) if serializer.is_valid(): email = serializer.validated_data['email'] username = serializer.validated_data['username'] password = serializer.validated_data['password'] if User.objects.filter(email=email).exists(): raise email.ValidationError("Este Email ya está en uso") if User.objects.filter(username=username).exists(): raise username.ValidationError("Este Usuario ya está en uso") It generates AttributeError: 'str' object has no attribute 'ValidationError' -
Return keyword arguments with None values to the views in django 3.2
As per Django 3 change logs (https://docs.djangoproject.com/en/3.2/releases/3.0/#miscellaneous): RegexPattern, used by re_path(), no longer returns keyword arguments with None values to be passed to the view for the optional named groups that are missing. Recently upgraded from django 2.2 to 3.2 after which I'm facing an issue for which I suspect the above mentioned changelog. Issue is I get KeyError while accessing the URL parameters as keyword arguments in the view (using get_context_data(...)) when accessing URLpatterns that are defined using re_path(). FYI, just to verify I rolled back to django 2.2 and checked on the context data from the view and could see that the required Key in the self.kwargs dict was set to None Is there any way to return keyword arguments with None values to the views in django 3.2? -
summation of multiple rows to check if value is less than referenced model in django
I tried to implement this SQL query using Django, where multiple payments under the same fee in possible and I have to get the payments that are lower than the fee amount. I have managed to get total payments under same fee id using Fee.objects.get(pk=self.pk).payment_set.aggregate(Sum('amount')) but cant find a way to compare it with payment_fee.amount SQL I tried to implement: SELECT payment_fee.id, payment_fee.amount , SUM(payment_payment.amount) as `su` FROM payment_payment inner join payment_fee on fee_id = payment_fee.id GROUP By fee_id HAVING (su)<payment_fee.amount django models: class Fee(models.Model): amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) class Payment(models.Model): fee = models.ForeignKey(Fee, on_delete=models.CASCADE, related_name='fee_payment') amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) -
Django process files uploaded by user
I am working on an app where the user uploads a text file which is further processed. All works well on my local environment but on Heroku, the app is unable to find the file in the specified location. User uploads file through form & I save it to a folder in the media root: # views.py myfile = request.FILES['myfile'] fs = FileSystemStorage(location=os.path.join(settings.BASE_DIR, 'media/raw')) filename = fs.save(myfile.name, myfile) I try to open the file and perform some operations on it # another file class Text: def __init__(self, filename): self.filename = filename self.raw_path = os.path.join(settings.MEDIA_ROOT, f'raw/{self.filename}') ... with open(self.raw_path) as file: ... On production, I get an error saying No such file or directory: '/app/media/raw/filename.txt' I know that Django is handling media files a bit differently in production but I haven't been figure out how to solve this issue. In my settings.py I have: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Thanks for any help! -
Using regular expression for a field name in a Django
I have a model in Django that has the fields photo_1, photo_2, photo_3 and many other fields that does not contains the "photo" string on their names. Also, the photo fields can be blank, so I can find some rows with empty photo fields. For the html template, is there a way to go through the fields named "^photo_[0-9]*$" and selecting only those that are not empty ? Here is what I mean: # views.py file def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing } return render(request,"listings/listing.html", context) # listsing.html file <div class="col-md-2"> <a href="{{listing.photo_n.url}}" data-lightbox="home-images"> <img src="{{listing.photo_n.url}}" alt="" class="img-fluid"> </a> </div> I would like to go through the "listing" QuerySet, searching for the fields named "^photo_[0-9]*$" and, if the the value for that field is not empty, pass it to ref="{{}}" and src="{{}}" tks -
Django application not working because of packages in aws
I have tried to install packages into aws but when I connected it to apache. it was producing error then on further checking I discorvered that the packages I installed were not installed into proper directory where it was supposed to be located in so apache was producing error 500. How can I install packages into the directory where apache would be able to use it?