Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to assertRaises(ValidationError) against Django Rest Framework APIView?
eg. I have my view: class MyView(APIView): def post(...): ... raise ValidationError('blah') And to my test def test_myview(...): factory = APIRequestFactory() request = factory.post('/myview', data=...) with self.assertRaises(ValidationError): MyView.as_view()(request) I get AssertionError: ValidationError not raised I tried to call it and print the result of the call: def test_myview(...): factory = APIRequestFactory() request = factory.post('/myview', data=...) resp = MyView.as_view()(request) print(resp) it's <Response status_code=400, "text/html; charset=utf-8">, so it's kind of correct if I want to test the response code etc, but what should I do if I want to assertRaises instead? -
Cannot access my phpMyAdmin DB - neither any related configuration file
I've been using a phpMyAdmin SQL DB in the past two years, which was pretty transparent to me. I inherited it from a guy that set it up for my team, and I actually got nothing but a username, password, and a Django web project that's linked to that database. Until today, any interaction with that DB was either via Django's ORM, or via the web UI of the phpMyAdmin site. Today, suddenly, for the first time, I got the following error: And that's it. I've been googling this error, and read some stack overflow threads, but they all suggest editing some configuration files in /etc, but again, I have no clue what's that about and how or where do I access those file - all I know is my username and password to the website, and my Django project's ORM queries (I know it's sad, but that's the reality). I'm the only one in the team that uses the DB, so nobody touched nothing for sure. What can I do to fix that, or to start understanding what happened here? Thanks in advance! -
nginx throws Bad Request (400)
I get this error when I attempt to access my site at: http://exhibit.technology **The Webconfs header check tool shows the following. HTTP/1.1 400 Bad Request => Server => nginx/1.14.0 (Ubuntu) Date => Sun, 23 Apr 2023 20:24:50 GMT Content-Type => text/html Connection => close X-Content-Type-Options => nosniff Referrer-Policy => same-origin** The IP address of the above URL is 192.81.211.160. When I enter it directly it works. My site loads. http://192.81.211.160 The Webconfs header check tool shows: HTTP/1.1 200 OK => Server => nginx/1.14.0 (Ubuntu) Date => Sun, 23 Apr 2023 20:23:35 GMT Content-Type => text/html; charset=utf-8 Content-Length => 6857 Connection => close X-Frame-Options => DENY Vary => Cookie X-Content-Type-Options => nosniff Referrer-Policy => same-origin The nginx error log (the lines around the report of the HTTP 400 error) is shown below (I can provide more if needed). I do not see why the IP address access works but the name access does not. Also, I do not know how to infer the problem from the log. Any help appreciated. The DNS and hosting is on Digital Ocean. The app. is written in Django and has Debug=False and ALLOWED_HOSTS populated in settings.py nginx log: 023/04/23 20:42:39 [debug] 13352#13352: *2 http upstream … -
Can you help me with connecting database models in django?
I am making a website with Django that is fed by a database that is refreshed every 3 hours, the problem is that when I want to remove a client from the database, mysql workbench does not let me because the client model is related to notes and user. How can I do so that when a client is deleted, its related classes are automatically deleted? I tried adding " on_delete=models.CASCADE" but it didn't work, also removing the foreign keys but I need to create notes from the clients. can you help me please? :c from django.db import models # Create your models here.from django.db import models from django.contrib.auth.models import User from django.utils import timezone SATISFACCION_CHOICES = ( ('<i class="fas fa-smile fa-2x" style="color:green"></i>', 'Satisfecho'), ('<i class="fas fa-meh fa-2x" style="color:rgb(255, 187, 0)"></i>', 'Intermedio/no atendió'), ('<i class="fas fa-frown fa-2x" style="color:red"></i>', 'Insatisfecho'), ) CAMBIOS_CHOICES = ( ('No hubo cambios', 'No hubo cambios'), ('Hubo cambios', 'Hubo cambios'), ) class Cliente(models.Model): fecha = models.DateTimeField(db_column='Fecha') # Field name made lowercase. vencimiento = models.DateTimeField(db_column='Vencimiento') # Field name made lowercase. saldo = models.FloatField(db_column='Saldo') # Field name made lowercase. comprobante = models.TextField(db_column='Comprobante') # Field name made lowercase. corredor = models.TextField(db_column='Corredor') # Field name made lowercase. grupo = models.TextField(db_column='Grupo') # … -
What can i use to embbed video conferencing in my Django website?
How can I add video conferencing and audio calls to my Django website? I have seen a lot of people talking about agora but I don't have tried it.is it better? -
Django form with dynamic number of items depending on other model
I'm trying to generate a dynamic form for the models below (some fields removed for brevity): class BreakfastOption(CreatedUpdatedByMixin, TimeStampedModel): """Option for breakfast, e.g. white bread, brown bread, tea, coffee""" name = models.CharField(max_length=30, unique=True) BREAKFAST_CATEGORY_CHOICE = ( ('food_week', 'Food during week'), ('food_weekend', 'Food during weekend'), ('drinks', 'Drinks'), ) category = models.CharField(max_length=32, choices=BREAKFAST_CATEGORY_CHOICE, ) class BreakfastOptionChoice(CreatedUpdatedByMixin, TimeStampedModel): """Option for breakfast along with its desired quantity, e.g. 2 slices of white bread and one tea""" breakfast_option = models.ForeignKey(BreakfastOption, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() class BreakfastPreference(CreatedUpdatedByMixin, TimeStampedModel): """Person's choice for breakfast, e.g. 2 slices of white bread and 1 tea, along with comments""" person = models.ForeignKey(Person, on_delete=models.CASCADE) start_date = models.DateField(default=datetime.date.today) # Used for tracking changes choices = models.ManyToManyField(BreakfastOptionChoice) comments = models.TextField(blank=True, null=True) What I'd like to have is a form for BreakfastPreference where the user can see the whole list of available BreakfastOptions (which are about 8) and can enter a quantity for those, along with overall comments. Example form: Person: (prefilled through URL) "White bread slices" quantity: 2 "Brown bread slices" quantity: 0 "Tea" quantity: 1 "Coffee" quantity: 0 Comments: person wants breakfast as early as possible In the above example, rows 2 to 5 are dynamically generated (i.e. there could be 4, but … -
How to override id field Django model
I'm looking for way to override id field mb with models.AutoField or something like that But the main problem that i want to have specific id field For example: I want id field for user to start with number 0 and after that it might contains number or specific letters and this id will look like this : 0123456ABC and all of this should be unique How can i do that? Should i override models.AutoField? models.py class User(models.Model): id = models.AutoFields() user/0123456ABC -
Paypal standard checkout and Django/Python
I am trying to integrate paypal standard checkout, i have imported paypalrestsdk, I have my correct paypal client id and secret, but I keep getting an error returned: if order.create(): ^^^^^^^^^^^^^^ TypeError: 'NoneType' object is not callable I have done some debugging and this is what gets returned into console: Transaction: {'amount': {'value': '10.00', 'currency_code': 'USD'}, 'description': 'My awesome product'} Order: {'intent': 'CAPTURE', 'purchase_units': [{'amount': {'currency_code': 'USD', 'value': '10.00'}, 'description': 'My awesome product'}]} Internal Server Error: /create_order/ here are my views and scripts: def create_order(request): # Get the transaction details from the client-side transaction = json.loads(request.body) print('Transaction:', transaction) # Create a new PayPal order order = paypalrestsdk.Order({ "intent": "CAPTURE", "purchase_units": [{ "amount": { "currency_code": transaction['amount']['currency_code'], "value": transaction['amount']['value'] }, "description": transaction['description'] }] }) print('Order:', order) if order.create(): # Return the PayPal order ID to the client-side return JsonResponse({"orderID": order.id}) else: # Return an error message to the client-side error_dict = {"error": str(order.error)} return JsonResponse(error_dict, status=400) def capture_payment(request): # Get the PayPal order ID from the client-side order_id = json.loads(request.body)['orderID'] # Capture the PayPal payment order = paypalrestsdk.Order.find(order_id) if order and order.status == "CREATED": capture = paypalrestsdk.Capture({ "amount": { "currency_code": order.purchase_units[0].amount.currency_code, "value": order.purchase_units[0].amount.value } }) if capture.create(order_id): # Return a success message … -
problem in django render partial, i install render partial but i still have an error message
i have install django-render-partial bay pip, and see the success message, but in the settings.py on INSTALL_APPS, i cant add 'django-render-partial' and i got an error message that is : "ModuleNotFoundError: No module named 'django-render-partial'". how i can fix this problem?enter image description here i want that error message disappear and i can use render partial in the project. plz help me ❤️ -
(Django) How to change admin site filtering panel options?
I'm trying to set a filter on the Seller model's admin page using the rate field, but there's a slight issue. the rate field can have a range of: -1 + (0, 5] I want the filter panel to have 6 values, each corresponding to a rate above or equal to the corresponding number (-1, 1, 2, 3, 4, 5) at the moment it looks like this, How can I achieve my goal? models.py: class Seller(models.Model): """ A model for the sellers of the Product model, connected to which with a ForeignKey """ name = models.CharField(max_length=255, blank=False, unique=True) description = models.TextField(max_length=1275, blank=False) join_date = models.DateTimeField( auto_now_add=True, validators=[validate_date_now]) rate = models.FloatField(default=-1) logo = models.ImageField(upload_to=get_upload_path, blank=False) sale_count = models.IntegerField(default=0) def __str__(self) -> str: return str(self.name) admin.py: class SellerAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ( 'join_date', 'name', 'description', ), }), ('Advanced information', { 'fields': ( 'sale_count', 'rate', 'logo', ) }) ) list_display = ('name', 'join_date', 'sale_count', 'rate') list_filter = ('join_date', 'rate') search_fields = ('name',) readonly_fields = ('join_date', 'rate', 'sale_count') -
"GET /static/admin/css/fonts.css HTTP/1.1" 404 1816 [closed]
my django said I've this error, how can I fix it? (I'm new to this) I search around the web browser can't find the answer -
Django query on a link table generated from a many to many relashionship
Here is an example of a part of a models.py file that manages recipes and ingredients: class Ingredient(models.Model): name = name = models.CharField(max_length=200) class Recipe(models.Model): name = name = models.CharField(max_length=200) ingredients = models.ManyToManyField(Ingredient) I heard that Django will automatically create a link table using the name of the app, then the referencing model and the model being referenced, all in lower case. Let's say that the app in my example is called cookbook then the name of the linked table would be cookbook_recipe_ingredient, am I right so far? So, let's suppose I now want to query this linked table from some sort of script at the bottom of the models.py file, to make automated treatments in the database. In this case, it would be to list all recipes containing peanuts. If it was an SQL database, a simple select distinct recipe from cookbook_recipe_ingredient where ingredient = 'peanut' What would be the Django way of making such a query on such a link table? -
Django Rest Framework, filter by name
I'm trying to create a filter by username, but django nonstop requires id from me. What is repair here? class FavoriteList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsCurrentUserOwnerOrHidden] queryset = Favorite.objects.all() serializer_class = FavoritesSerializer name = 'favorite-list' def perform_create(self, serializer): serializer.save(owner=self.request.user) def filter_queryset(self, queryset): owner_name = self.request.query_params.get('owner', None) if owner_name is not None: queryset = queryset.filter(owner=owner_name) return queryset localhost/favorite?owner=1 is working but loclahost/favorite?owner=admin don't -
Combine several "context"-Blocks in final return-clause of a view
Hiho, i've searched for this and found simliar topics but none of them gave me an answer that seems helpful....or I searched for the wrong terms maybe. Right now I wonder, wether you can optionally combine the context of a "return render...." command in a Django-View. As Django propagates a "Do-Not_Repeat-Yourself" philosophy, I would like to change the following code to shorten it (The several if-clauses have to do with role-rights stuff....): def show(request): now_day = datetime.date.today() current_user = request.user if request.method == 'GET': if view_self(current_user) == True and more_rights(current_user) == False: if Employees.objects.filter(employee_number=current_user).exists(): context = {'names': Employees.objects.filter(employee_number=current_user)} else: context = {'info': "Für sie existiert (noch) kein Datensatz in dieser Datenbank"} else: context = {'names': Employees.objects.all().order_by('last_name').values()} return render(request, 'show.html', context) else: if view_self(current_user) == True and more_rights(current_user) == False: if request.POST['id'] == 'Mitarbeiter auswählen...': context = { 'names': Employees.objects.filter(employee_number=current_user), 'info': "Bitte treffen Sie zuerst eine Auswahl" } else: employee = request.POST['id'] context = { 'names': Employees.objects.filter(employee_number=current_user), 'entries': Employees.objects.filter(id=request.POST['id']), 'work_conditions': Employment.objects.filter(employee_id=request.POST['id']), 'functions': Functions.objects.filter(employee__functions=request.POST['id']).order_by('function'), 'fieldsoa': FieldsOfActivity.objects.filter(employee__fieldsofactivity=request.POST['id']).order_by('field_of_activity'), 'missions': Foreign_Missions.objects.filter(employee_id=request.POST['id']).order_by('-begin'), 'examinations': Examinations.objects.filter(employee_id=request.POST['id']).order_by('-date'), 'total_duration_days': Foreign_Missions.objects.total_duration_days(employee), 'today': now_day, 'special_header': "Datensätze anzeigen" } elif request.POST['id'] == 'Mitarbeiter auswählen...': context = { 'names': Employees.objects.all().order_by('last_name').values(), 'info': "Bitte treffen Sie zuerst eine Auswahl" } elif 'id' in request.POST: employee = … -
Why doesnt switching between templates work in django?
I want to switch between two templates using render in the same function. It worked with one project, but not with this one. I'm going mental. It's about a math quiz, where you can choose between level 1 and level 3. after POST it should render a new html where i can make the layout, but it simply doesnt switch to layout.html index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Math Quiz</title> </head> <body> <p class="title">Math Quiz</p> <div class="box"> <button type="submit" onclick="lvl(1)">Level 1</button><br><br> <button type="submit" onclick="lvl(2)">Level 2</button><br><br> <button type="submit" onclick="lvl(3)">Level 3</button> <script> function lvl(num) { fetch("",{ method: "POST", headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' // Include the CSRF token in the headers }, body: JSON.stringify({ "num": num }) }) }; </script> </div> </body> </html> layout.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Math Quiz</title> </head> <body> <p class="title">Math Quiz2</p> <div class="box"> <form method="POST"> <p>{{ quiz }}</p> </form> </div> </body> </html> views.py from django.shortcuts import render import json import random # Create your views here. … -
how to delete an file after sending it to user as file response
I'm trying to send a file to user as file response to the client. after user downloaded it successfully, I want to delete it from the server. for example i downloaded a video file to server into a temp directory and giving it as response to user . then i wanna delete it .. i used temp file to save video, but the directory is not deleted after using the file but when i try to delete that file using add_post_render_callback() in django and @after_this_request decorator in flask and many more. in every case i get error because either the file will be deleted before repose ( file not found - on file response ) or the file is being used by file response so it cannot be used . i also tried multi threading res =request.POST['res'] video_url=request.POST['link'] # Create a temporary directory within the Flask project root directory temp_dir = tempfile.mkdtemp(dir= BASE_DIR / 'temp') # Fetch the YouTube video using pytube yt = YouTube(video_url) stream = yt.streams.filter(mime_type="video/mp4",resolution=res).first() video_path=stream.download(temp_dir) def callback(): shutil.rmtree(temp_dir) response = FileResponse(open(video_path, 'rb'), as_attachment=True, filename='video.mp4') response.add_post_render_callback(callback) return response -
How to automaticly add slugs to the new db objects?
I am using an external admin panel that is not connected to Django(but connected to the postgresql db), and as a result, when I add a new Work object through the admin, it does not automatically add a slug. Is there a way to automatically check when a new object is created in the database and add a slug to it? Below is the code that I am currently using to add slugs: def save(self, *args, **kwargs): if not self.pk: slug_title = translit(self.ukrainian_title, 'uk', reversed=True) self.slug = slugify(slug_title) while Work.objects.filter(slug=self.slug).exists(): self.slug = f"{slugify(slug_title)}-{get_random_string(length=4)}" super().save(*args, **kwargs) And it's working perfectly, but with django default admin, not with the external one. Would appreciate any help -
Gerador de formulario django [closed]
bom dia! Sou novo em programação e estou estudando Django. Gostaria de montar um projeto que receba campos personalizados pelo usuario no formulario, como o Google forms. Mas nao encontrei nada sobre o assunto. Caso alguém possa me apontar um direcionamento agradeço fiz varias buscas e nao encontrei nada atual ou implementavel -
error while adding data in ManyToManyField model
Here assignment Model has ManyToManyField with Tags but when I try to insert data using serializers I got an empty list [], in tags fields here is my serializers.py: from rest_framework import serializers from assignment.models import ( Assignment, Tag, ) class AssignmentSerializer(serializers.ModelSerializer): """Serializer for Assignment.""" class Meta: model = Assignment fields = ["id", "name", "tags", "last_updated_by", "assignment_data"] read_only_fields = ["id"] def create(self, validated_data): """Create an Assignment.""" tags_data = validated_data.pop("tags", []) instance = Assignment.objects.create(**validated_data) for tag_name in tags_data: created = Tag.objects.get_or_create(name=tag_name) instance.tags = created instance.save() return instance I am sending this value: { "name": "demo assignment", "tags": ["demo"], "last_updated_by": "user1", "assignment_data": { "hello": "Hello world 2" } } please let me know if you require any other information -
Having trouble with bulk_create()-ing models in Django
The first problem is that I have a Question model and a Tags model, which share a ManyToMany relationship and Django doesn't allow direct assignment to them during creation. So the only solution I could find is to create the questions and then manually assign the tags to them, creating hundreds of slow queries. def handle(self, *args, **options): user_profiles = list(Profile.objects.all()) if not user_profiles: print("No users found to create questions") return tags = list(Tag.objects.all()) new_questions = [Question( title=random_sentence(12, 12), content=random_text(12, 12, 12), author=random.choice(user_profiles), ) for _ in range(options['questions_num'][0])] new_questions = Question.objects.bulk_create(new_questions) for question in new_questions: question.tags.set([random.choice(tags) for _ in range(random.randint(1, 4))]) The second problem is about bulk-creating users. I have a Profile model associated with the default Django User model with some additional fields, so I have to create both. But I have to keep in mind the unique constraint of each user and that would mean manually checking if they exist for each of them. Ignoring conflicts during bulk_create means that all the objects won't have primary keys and will be useless to me. def handle(self, *args, **options): username_length = User._meta.get_field('username').max_length password_length = User._meta.get_field('password').max_length email_length = User._meta.get_field('email').max_length - len('@mail.ru') try: users = [User( username=random_word(username_length), password=random_word(password_length), email=f"{random_word(email_length)}@mail.ru", ) for _ … -
Mysql & Django - UniqueConstraint not enforced
I have the following model: class A(models.Model): objects = AQueryManager() //fills the table with values b = models.CharField(max_length=200, blank=False) def __str__(self): return self.name class Meta: db_table = 'maker_A' constraints = [ models.UniqueConstraint( Lower('b'), name='b uniqueness' )] I want to make the column "b" unique with the functionality lower, it works locally with sqllite db but does not work on MySQL, Does anyone have an idea? Thanks a lot! I looked everywhere but couldn't find a reason. It looks like it should work -
How to upload File along with the by default setting "Anyone with the link" in Google Drive using Python?
I am using the following code to upload my file in Google drive using googleapiclient module in Python. from __future__ import print_function from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload from httplib2 import Http from oauth2client import file, client, tools import argparse class Drive: # If modifying these scopes, delete the file token.json. SCOPES = 'https://www.googleapis.com/auth/drive.file' extensions = {"csv":"text/csv","mpeg":"video/mpeg","mpg":"video/mpeg","tiff":"image/tiff","tif":"image/tiff","bmp":"image/bmp","gif":"image/gif","wav":"audio/wav","avi":"video/x-msvideo","bmp":"image/bmp","doc":"application/msword","docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document","jpg":"image/jpeg","jpeg":"image/jpeg","mp4":"video/mp4","mpg":"video/mpeg","pdf":"application/pdf","png":"image/png","ppt":"application/vnd.ms-powerpoint","pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation","rar":"application/octet-stream","tar":"application/x-tar","txt":"text/plain","wmv":"video/x-ms-wmv","xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","zip":"application/x-zip-compressed"} def __init__(self): try: flags = tools.argparser.parse_args([]) except ImportError: flags = None store = file.Storage('token.json') self.creds = store.get() if not self.creds or self.creds.invalid: flow = client.flow_from_clientsecrets(settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES) if flags: self.creds = tools.run_flow(flow, store, flags) self.service = build('drive', 'v3', http=self.creds.authorize(Http())) def create_folder(self,folder_name): folder_id = None query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='" + folder_name + "'" results = self.service.files().list( pageSize=1, q=query, fields="files(id, name)").execute() folders = results.get('files', []) if folders: folder_id = folders[0]['id'] # If folder not found, then create it. else: file_metadata = { 'name': folder_name, 'mimeType': 'application/vnd.google-apps.folder' } folder_file = self.service.files().create(body=file_metadata, fields='id').execute() folder_id = folder_file.get('id') return folder_id def upload_file(self, folder_id, file_name): file_metadata = { 'name': file_name.temporary_file_path(), 'parents': [folder_id] } media = MediaFileUpload(file_name.temporary_file_path(), mimetype= self.extensions[file_name.name.split(".")[1]],resumable=True) print(media) _file = self.service.files().create(body=file_metadata, media_body=media,fields='id').execute() file_id = _file.get('id') return file_id Above code works file but the file which uploads on Google Drive saves with restricted option. What … -
Trouble Generating Avatars from Uploaded Images in OpenAI
I am trying to build an application in OpenAI that allows users to upload their own images and generate avatars based on those images while performing a specific activity that the user inputs. However, I am running into some issues with generating the avatars. Whenever I upload an image and input an activity, the avatar that is generated appears distorted and does not accurately represent the original image or the activity being performed. The colors are off and the details are not crisp. I have tried different image processing techniques such as resizing and cropping the image before generating the avatar, as well as incorporating the user's input activity into the avatar generation process, but none of them seem to improve the quality of the avatar. I suspect that there might be some issue with the way I am generating the avatar or with the code I am using to process the image and activity input. from django.shortcuts import render from django.core.files.storage import default_storage from django.core.files.base import ContentFile import openai import requests from requests.structures import CaseInsensitiveDict from django.conf import settings openai.api_key = settings.OPENAI_API_KEY def generate_images(request): if request.method == "POST": image_file = request.FILES.get('image') activity1 = request.POST.get('activity1') activity2 = request.POST.get('activity2') # Construct … -
Django Cannot keep last 3 row of database
I want to keep latest 3 row of each key and delete oldest row if data of each key more than 3 row. I have sample data like this. id value key created 1 a1 001 2023-04-23 01:01:00 <= delete oldest of key 001 2 a2 001 2023-04-23 01:02:00 3 a3 001 2023-04-23 01:03:00 4 a4 001 2023-04-23 01:04:00 5 a5 002 2023-04-23 01:05:00 <= delete oldest of key 002 6 a6 002 2023-04-23 01:06:00 7 a5 002 2023-04-23 01:07:00 8 a6 002 2023-04-23 01:08:00 I get latest 3 row order by create and delete oldest with this code. if Key.objects.filter(key=key).exists(): objects_to_keep = Data.objects.filter(key=key).order_by('-created').values_list("id", flat=True)[:3] objects_to_keep = list(objects_to_keep) Data.objects.exclude(pk__in=objects_to_keep).delete() If I add new row key=001 it remove all data of key 002 and the same when add new row key=002 it remove all data key 001. The output should be like this. id value key created 2 a2 001 2023-04-23 01:02:00 3 a3 001 2023-04-23 01:03:00 4 a4 001 2023-04-23 01:04:00 6 a6 002 2023-04-23 01:06:00 7 a5 002 2023-04-23 01:07:00 8 a6 002 2023-04-23 01:08:00 How to fix it? -
Django VideoField
I'm want to make a custom FileField that only allows video uploads I'm trying to use pymediainfo to make sure the file uploaded is a video but I keep getting FileNotFoundError here's my code from django.core.exceptions import ValidationError from django.db import models from pymediainfo import MediaInfo from django.db.models.fields.files import FieldFile class VideoField(models.FileField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def validate(self, file : FieldFile, model_instance): super().validate(file, model_instance) media_info = MediaInfo.parse(file.path) if media_info.tracks[0].track_type != 'Video': raise ValidationError('The file must be a video.') and here's the model code def lecture_video_handler(instance, filename): return f"chapters/{instance.chapter_id}/lectures/{instance.id}/{filename}" class Lecture(models.Model): chapter = models.ForeignKey('course.Chapter', models.CASCADE) video = VideoField(upload_to=lecture_video_handler) in settings.py I'm using the default file storage not a custom one MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') what am I doing wrong?