Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
reverse for url (*) with keyword arguments not found
I am a django rest/django noob. I am trying to reverse url @action(detail=True, methods=['post'], url_path='request-reset-email', url_name='request-reset-email') def request_reset_password_email(self, request, pk): ... uid64 = urlsafe_base64_encode(smart_bytes(user.id)) token = PasswordResetTokenGenerator().make_token(user) relativeLink = reverse('user-password-reset-confirm', kwargs={'uid64' : uid64, 'token': token}) and I have this other custom action @action(detail=False, methods=['get'], url_path='password-reset/<uid64>/<token>/', url_name='password-reset-confirm') def password_reset_confirm(self, request, uid64, token): pass and this is the urls file router = DefaultRouter() router.register('user', UserViewset, basename='user') urlpatterns = [ path('', include(router.urls)), path('<int:id>', include(router.urls)), ] the error NoReverseMatch at /user/2/request-reset-email/ Reverse for 'user-password-reset-confirm' with keyword arguments '{'uid64': 'Mg', 'token': 'az3s71-eae533db00d974ba7d7fc0dfd5e9e060'}' not found. 4 pattern(s) tried: ['(?P<id>[0-9]+)user/password-reset/<uid64>/<token>\\.(?P<format>[a-z0-9]+)/?$', '(?P<id>[0-9]+)user/password-reset/<uid64>/<token>//$', 'user/password-reset/<uid64>/<token>\\.(?P<format>[a-z0-9]+)/?$', 'user/password-reset/<uid64>/<token>//$'] -
Is there a way to seperate progammatic access to a Django Rest API from React access and what are the alternatives?
This is obviously a design question, and probably me overthinking. I was asked once how to generate API Keys and I explained the process of retrieving tokens( DjangoRest -> React) to which I was responded with "Thats for logging in/authentication, how would you implement 'Generate API key'". If my application is DjangoREST + React, this means my entire application is exposed as RESTful. Is there even a way to control the "frontend" access over being programmatically accessible, since "CLI/Scripting" users can just hit the login endpoint programmatically anyway? It seems like the only thing that can be done here with a React Front and DjangoREST backend is to limit the calls to each of the routes, but control "browser-based" requests vs cli-based requests are nearly impossible. (Unless I blacklist/whitelist by user agent but that seems highly unfeasble) What I am concluding is that the only way to "control" programmatic access effectively in Django is not to use a React Frontend, and then create separate URLs for the api. But then in this case, I am confused on the neccesity of client_IDs and client_secrets (as I have seen on other sites that offer an API), because if I simply blacklist a … -
In Django how to process the file inside request.FILES?
for file in request.FILES: print("") video_input_path = file img_output_path = 'output.jpg' subprocess.call(['ffmpeg', '-i', video_input_path, '-ss', '00:00:00.000', '-vframes', '1', img_output_path]) print("") I'm trying to generate a thumbnail for the File (Video) uploaded via Form, this is pure python solution for generating the thumbnail from any video (works for pictures too but there is a better solution with PIL) video_input_path = file How do I access the file itself here? As far as I know my only options are file = request.FILES['filename'] file.name # Gives name file.content_type # Gives Content type text/html etc file.size # Gives file's size in byte file.read() # Reads file -
How to render and navigate django based web pages with a click of button without refreshing the page (Ajax)
am doing a django project and I would like my navigation bar to be AJAX based in the sense that when I click the link of a particular page, the page is rendered without reloading/refreshing the original page. I have tried to use the django redirect function but without success. your help will be appreciated. -
Android Retrofit upload images and text in the same request
I have an Android app that has a form feature where I collect data, that data contains image answers and text answers and each answer has a question id that I need to send also to know which question to save answer to it in the backend API, I tried to send all answers both images and text in the same request using Retrofit but got some errors, so I thought in another solution, but it's not working anymore here is my code Here is my solution and I need to improve it Retrofit code to send a request with data @Multipart @POST(SUBMIT_FORM) suspend fun submitFormAPI( @Header("Authorization") token: String, @Part("questions_answers") questions_answers: List<QuestionAnswer>, @Part answer_image: MultipartBody.Part?, @Part("question_id") question_id: String?, ): Response<FormResponse> and here is the QuestionAnswer Model, I tried to put answer_image inside it but doesn't work data class QuestionAnswer( val question_id: String, val answer_value: String? = null, ) so in this function, after collecting the data I need to loop through questionImagesAnswers and send a request with the image and its question_id every iteration along with other answers in questionAnswers fun onFormSubmit() { val questionAnswers = mutableListOf<QuestionAnswer>() val questionImagesAnswers = mutableListOf<QuestionModel>() questionImagesAnswers.forEach { questionImagesAnswer -> formViewModel.submitFormAPI( token = token, questionAnswers … -
Avoid Booking past dates with django
I have created an appointment booking system however i want to avoid any past dates being booked before it reaches create booking object which is then saved to the database. Here is my views.py class BookingView(View): def get(self, request, *args, **kwargs): return render(request, "availability.html") def post(self, request, *args, **kwargs): form = AvailabilityForm(request.POST) if form.is_valid(): data = form. cleaned_data bookingList = Appointment.objects.filter(start__lt=data['end_time'], end__gt=data['start_time']) if not bookingList: booking = Appointment.objects.create( name=data["name"], email=data["email"], start=data["start_time"], end=data["end_time"] ) booking.save() name_user = data["name"] start_time = data["start_time"] end_time = data["end_time"] email_user = data["email"] send_mail("Virtual PT Session", f"Thanks {name_user} For Booking Your Appointment with us.\n" + f"Please join the following zoom link on {start_time} \n" + " https://us04web.zoom.us/j/8339571591?pwd=dG9MQy9nUWN6a0F2dUo4L04rQkxPQT09", "engage.fitness.training.1@gmail.com", [email_user], fail_silently=True) return render(request, "success.html", { "booking":booking },) else: name = data["name"] return render(request, "booked.html",{ "name":name, },) -
I am developing an blockchain project using Django and can I know how to resolve this error
Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\USER\Desktop\blockchain\wallet\views.py", line 17, in index live_bitcoin_price = live_price[1].getText() Exception Type: IndexError at / Exception Value: list index out of range #code of that function def index(request): if request.method == 'POST': addr = request.POST['addr'] res2 = requests.get('https://cryptowat.ch/') soup2 = bs4.BeautifulSoup(res2.text, 'lxml') live_price = soup2.find_all('span', {'class': 'price'}) live_bitcoin_price = live_price[1].getText() live_bitcoin_price1 = live_price[1].getText() res = requests.get('https://www.blockchain.com/btc/address/'+addr) if res: soup = bs4.BeautifulSoup(res.text, 'lxml') # bal = soup.find_all('span', {'class': 'sc-1ryi78w-0 bFGdFC sc-16b9dsl-1 iIOvXh u3ufsr-0 gXDEBk'}) bal = soup.find_all('span', {'class': 'sc-1ryi78w-0 gCzMgE sc-16b9dsl-1 kUAhZx u3ufsr-0 fGQJzg'}) bal[4].getText() final_bal = bal[4].getText() final_bal1 = final_bal.replace(" ", "").rstrip()[:-3].upper() transactions = bal[1].getText() total_received = bal[2].getText() total_received1 = total_received.replace(" ", "").rstrip()[:-3].upper() total_sent = bal[3].getText() total_sent1 = total_sent.replace(" ", "").rstrip()[:-3].upper() final_bal1_int = float(final_bal1) total_received1_int = float(total_received1) total_sent1_int = float(total_sent1) live_bitcoin_price1_int = float(live_bitcoin_price1) balance_usd = final_bal1_int*live_bitcoin_price1_int total_received_usd = total_received1_int*live_bitcoin_price1_int total_sent_usd = total_sent1_int*live_bitcoin_price1_int else: return redirect('/') -
Referencing foreign key in Django Python
How to assign a product in ProductInStore to an instance of a Product already in store? Basically i have a scrapper and im looping through all the products and i need to first create the Product instance, and then A ProductInStore instance which is connected to Product via foreignKey. And when i try to put in ProductInStore(product=id) thats how i wanted to reference that Product, i get an error ValueError: Cannot assign "11393": "ProductInStore.product" must be a "Product" instance. Do you have any idea how to reference it? class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) product_category = models.ManyToManyField(EcommerceProductCategory) description = RichTextField(max_length=2000, null=True, blank=True) product_producer = models.ForeignKey('ProductProducer', on_delete=models.CASCADE) creator = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, blank=True, related_name='product_creator') points_from_reviews = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Średnia ocena produktu') unique_id = models.CharField(max_length=256, unique=True) type_of_unique_id = models.CharField(max_length=64) class ProductInStore(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) store = models.ForeignKey('Store', on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Cena w sklepie') currency = models.CharField(max_length=4) url = models.CharField(max_length=200) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) # ADD TO DATABASE try: db_product = Product.objects.create(name=name, slug=slug, product_producer_id=3, unique_id=id, description=description) db_product.product_category.set(parsed_categories) except: print('product already in database') ProductInStore.objects.create(product=,store=1,price=price,currency='PLN',url=url) -
How to fix add to cart functionality in django?
I'm building an ecommerce platform and I want to create the add to cart functionality in the website. But for some reason the Product Id is showing null. Here's the codes: models.py class Products(models.Model): seller = models.ForeignKey(SellerProfile, on_delete = models.CASCADE) title = models.CharField(max_length = 255) product_category = models.CharField(choices = CATEGORY_CHOICES, max_length = 100) description = models.TextField() price = models.FloatField(max_length= 5) class Cart(models.Model): buyer = models.ForeignKey(User, on_delete = models.CASCADE) products = models.ForeignKey(Products, on_delete = models.CASCADE) views.py def add_cart(request): product_id = Products.id new_product = Cart.objects.get_or_create(id=product_id, user=request.user) return redirect('/') When I try to click this link it gives me this error: Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x000002468A4F8550>. Any suggestion will be really helpful. Thank you -
Unable to create a container for a Django app
I was trying to make a basic container as a learning project that should download Django from PyPI and run the default server. For that I made 3 files i.e. docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY /requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ requirements.txt Django==4.0 the command that I used in terminal and the output are given below in the terminal snippet: samar@wasseypur:~/Desktop/project2/telusko$ sudo docker-compose run web django-admin startproject mysite . [sudo] password for samar: Creating telusko_web_run ... done Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "django-admin": executable file not found in $PATH: unknown ERROR: 1 -
Sort a displayed column defined by a custom model method in the Django admin interface
I want to be able to sort a table column defined using a custom method in the Django admin. I narrowed down the problem to this simple example in Django: models.py: from django.db import models class MyObject(models.Model): name = models.CharField(_("name"), max_length=255) layers = models.URLField(_("Layers"), blank=True, max_length=1024) choices = models.TextField( verbose_name=_("Choice values"), blank=True, help_text=_("Enter your choice"), ) class Meta: verbose_name = _("Object config") verbose_name_plural = _("Objects config") def __str__(self): # my custom method return self.name and admin.py: from django import forms from django.contrib import admin class MyObjectAdminForm(forms.ModelForm): """Form""" class Meta: model = models.MyObject fields = "__all__" help_texts = { "layers": "URL for the layers", } class MyObjectAdmin(admin.ModelAdmin): form = MyObjectAdminForm list_filter = ["name",] search_fields = ["name",] # I want the first column (__str__) to be sortable in the admin interface: list_display = ["__str__", ...] # the ... represent some other DB fields but for the moment I cannot sort that first column (it is grayed out, I cannot click on its title): So how could I sort the first column in this admin table as defined by the __str__() method of the MyObject model? (please note that I cannot change the model itself. I'm also brand new to Django, so don't … -
Django ORM aggregate over related array field
I have two models class Record(Model): scorable_entry = models.ForeignKey('Entry', null=True, blank=True, on_delete=models.CASCADE) class Entry(Model): scores = ArrayField(models.IntegerField(), null=True) and I need to sort Records based on the sum of scores on a related Entry model. Unfortunately, this naive code throws an error records .annotate(score_rows=Func(F('scorable_entry__scores'), function='unnest')) .aggregate(scores_sum=sum('score_rows')) .order_by('-scores_sum') django.db.utils.NotSupportedError: aggregate function calls cannot contain set-returning function calls I'm using unnest to convert array to rows first (because otherwise sum wouldn't work). Skipping unnesting doesn't work as sum doesn't operate on arrays django.db.utils.ProgrammingError: function sum(integer[]) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts. What is the proper way to order elements by the sum of a related array using ORM? Django 3.1, Postgres 12.9 -
Python: How to call a function with django?
I am new absolutely new to Django and have been stuck on this problem for some time now, for some reason they don't actually explicitly teach it in any tutorial I could find. So what I want is to create a simple button I Django that calls a simple python function that prints "hello" to the terminal? I don't want to change view or anything, just to call the function -
django storages breaks the admin staticfiles
I tried moving from local static files to S3 using django-storages. I followed the documentation carefully but still there is no access to the static files. In the local environment I have: STATIC_URL = '/static/' in the settings.py and everything works fine. when I add all the S3 params as the documentation shows: STATIC_URL = 'https://django-main.s3.amazonaws.com/' ADMIN_MEDIA_PREFIX = 'https://django-main.s3.amazonaws.com/admin/' # tried with this and also without this DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_ACCESS_KEY_ID = '<AWS_ACCESS_KEY_ID>' AWS_SECRET_ACCESS_KEY = '<AWS_SECRET_ACCESS_KEY>' AWS_STORAGE_BUCKET_NAME = 'bucket-name' I ran python manage.py collectstatic which seemed to work fine and uploaded the static files to the bucket. but running the server and going to the admin page it looks like this: which is because it doesn't have access to the static files. No error is thrown/shown Any ideas? -
"self.fields['field_name'].queryset" in Djano, can it be applied to a OneToOne field?
I'm new to Django and have been trying to wrap my head around OneToOne field relationship with _set.all() My models.py class User(AbstractUser): is_admin = models.BooleanField(default=False) is_employee = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) is_assistant = models.BooleanField(default=False) class Profile(models.Model): profile = models.OneToOneField(User, on_delete=models.CASCADE) class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_profile = models.OneToOneField(Profile, on_delete=models.CASCADE) I'm trying to update a Manager instance and not quite sure why self.instance.user.profile_set.all() keeps throwing an "'User' object has no attribute 'profile_set'" AttributeError in this section: forms.py elif self.instance.pk: self.fields['user_profile'].queryset = self.instance.user.profile_set.all() I hope my question is clear, any help would be greatly appreciated! Cheers! -
Django - How to validate uploaded image is of valid extension type and not corrupted
So I have this code below for validating and image file being uploaded. The main issues with the way of validating is that the user can simply change the extension and upload an invalid image, which would cause issues on the front-end, because if it tries to render it, it won't be able to. Is there a way to validate if a valid image file is being uploaded in Django? Or maybe this is just fine and it not rendering on the front-end is expected behavior when the user uploads an improper image file. VALID_IMAGE_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif') upper_image_extensions = tuple([string.upper() for string in VALID_IMAGE_EXTENSIONS]) VALID_IMAGE_EXTENSIONS += upper_image_extensions def validate_image_upload(file): if not isinstance(file, InMemoryUploadedFile): raise ValidationError("Is not InMemoryUploadedFile") if not is_valid_file_of_format(file._name, VALID_IMAGE_EXTENSIONS): raise ValidationError("Image file format is invalid") -
TypeError: string indices must be integers after looping
Hey i have this scraper via WooCommerce Api that looks like this for page in range (0, 100): parameters = {'per_page': 30, 'page': f'{page}', 'stock_status': 'instock', 'status': 'publish'} products = wcapi.get("products", params=parameters).json() for product in products: name = product['name'] slug = product['slug'] description = product['description'] id = product['id'] price = product['price'] for image in product['images']: src = image['src'] #category parser d = store_dict print(product['categories']) parsed_categories = [] for category in product['categories']: parsed_categories.append(store_dict[str(category['id'])]) print(parsed_categories) # ADD TO DATABASE try: db = Product.objects.create(name=name, slug=slug, product_producer_id=3, unique_id=id, description=description) db.product_category.set(parsed_categories) except: print('product already in database') But when i put the 'page': f'{page}' in parameter to search through all pages on a particular store, I get an error File "/Users/x/x/x/x/management/commands/woocommerce.py", line 38, in handle name = product['name'] TypeError: string indices must be integers When i delete the 'page' parameter, it doesn't show that error. But i need to loop through all the pages. Do you have any idea what to do? -
Get output of execute_from_command_line from Django
I am trying to run some code based on the output of execute_from_command_line function from Django. Mainly I am trying to see if there are any unapplied migrations by checking the output of the aformentioned function: execute_from_command_line(["manage.py", "makemigrations", "--dry-run"]) The above prints No changes detected to stdout, so there is no way for me to check the output. I have looked at the source code of this function and I think it is may not be possible with execute_from_command_line. Is there any workaround this? I am using this script within my Django app running in Docker. I appreciate any insights! -
uwsgi failed to open python file /root/ ... /wsgi.py (DJANGO)
/var/log/uwsgi/myapp.log: Tue Jan 11 15:27:45 2022 - *** Starting uWSGI 2.0.18-debian (64bit) on [Tue Jan 11 15:27:45 2022] *** Tue Jan 11 15:27:45 2022 - compiled with version: 10.0.1 20200405 (experimental) [master revision 0be9efad938:fcb98e4978a:705510a708d3642c9c962beb663c476167e4e8a4] on 11 April 2020 11:15:55 Tue Jan 11 15:27:45 2022 - os: Linux-5.4.0-92-generic #103-Ubuntu SMP Fri Nov 26 16:13:00 UTC 2021 Tue Jan 11 15:27:45 2022 - nodename: 185-46-8-164.cloudvps.regruhosting.ru Tue Jan 11 15:27:45 2022 - machine: x86_64 Tue Jan 11 15:27:45 2022 - clock source: unix Tue Jan 11 15:27:45 2022 - pcre jit disabled Tue Jan 11 15:27:45 2022 - detected number of CPU cores: 1 Tue Jan 11 15:27:45 2022 - current working directory: / Tue Jan 11 15:27:45 2022 - detected binary path: /usr/bin/uwsgi-core Tue Jan 11 15:27:45 2022 - chdir() to /root/eva/lawyer Tue Jan 11 15:27:45 2022 - chdir(): Permission denied [core/uwsgi.c line 2623] Tue Jan 11 15:27:45 2022 - VACUUM: pidfile removed. Tue Jan 11 15:27:45 2022 - chdir(): Permission denied [core/uwsgi.c line 1647] Tue Jan 11 15:27:45 2022 - *** Starting uWSGI 2.0.18-debian (64bit) on [Tue Jan 11 15:27:45 2022] *** Tue Jan 11 15:27:45 2022 - compiled with version: 10.0.1 20200405 (experimental) [master revision 0be9efad938:fcb98e4978a:705510a708d3642c9c962beb663c476167e4e8a4] on 11 April 2020 … -
Python django deployment error when using waitress
I am trying to deploy my django project in heroku but i am facing some error when i try to use waitress module this link wont lead to anything what to do -
NOT NULL constraint failed: registration_registration_customuser.user_id
I am trying to register a user for the first time but I am getting a IntegrityError. Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: registration_registration_customuser.user_id when I am trying to create a superuser it is asking me for a user id for which i have to only enter a integer value but it is not accepting any value PS C:\Users\HP\Downloads\E_Authentication_System-master (1)\E_Authentication_System-master> python3 manage.py createsuperuser Username: HP User (registration_customuser.id): 1 Error: user instance with id 1 does not exist. User (registration_customuser.id): 2 Error: user instance with id 2 does not exist. User (registration_customuser.id): and I also can't leave it blank either models.py class registration_customuser(AbstractUser): REQUIRED_FIELDS =['user'] USERNAME_FIELD = ('username') user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, default=None,blank=True, null=True, editable=False) password =models.CharField(max_length=128, verbose_name='password') last_login = models.DateTimeField(blank=True, null=True, verbose_name='last login') username = models.CharField(max_length=200, unique=True) fullname = models.CharField(max_length=254) email = models.EmailField(max_length=254,unique=True) mobile = models.CharField(max_length=12,unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) @property def is_anonymous(self): return False @property def is_authenticated(self): return True admin.py from django.contrib import admin from .models import registration_customuser admin.site.register(registration_customuser) views.py from django.shortcuts import render,redirect from django.urls import reverse from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.models import auth from random import randint from django.core.mail import EmailMessage from sms import send_sms from django.conf import … -
Django HTML to pdf not displaying when for loop longer than 1 page
Note: The html renders to pdf perfectly when the objected passed to the pdf function does not exceed the size of one page. Funnily enough when i remove the styling from the html it works, and by works i mean renders to pdf and create multiple pages... but now obviously without styling! HTML CODE {% load static %} @page { size: A4; margin: 1cm; @frame header_frame { /* Static frame */ -pdf-frame-content: header_content; left: 50pt; width: 512pt; top: 20pt; height: 40pt; } @frame col1_frame { /* Content frame 1 */ -pdf-frame-content: left_content; left: 44pt; width: 245pt; top: 90pt; height: 632pt; } @frame col2_frame { /* Content frame 2 */ -pdf-frame-content: right_content; left: 323pt; width: 245pt; top: 90pt; height: 632pt; } @frame row_frame { /* Content frame 2 */ -pdf-frame-content: table_content; left: 260pt; width: 500pt; top: 270pt; right: 323pt; } @frame { /* Content frame 2 */ -pdf-frame-content: middle_content; left: 50pt; width: 500pt; top: 300pt; right: 323pt; } @frame footer_frame { /* Static frame */ -pdf-frame-content: footer_content; left: 50pt; width: 512pt; top: 772pt; height: 20pt; } @frame footer { -pdf-frame-content: footerContent; bottom: 0cm; margin-left: 10cm; margin-right: 10cm; height: 1cm; } } .page-break{ page-break-after: always; } </head> <body> <div class="container-fluid"> <div id="header_content" … -
Django Models : array of fields
I need a form with 'hundreds' of integer input fields. I was thinking to create an array of integer fields in my model, but this doesn't seem to function: class Array(models.Model): name=models.CharField(max_length=10) data=[] for i in range(100): data.append(models.IntegerField(default=0,blank=True)) Via de shell I can create a record, change a data field and store... from app1.models import Array a=Array(name='first') a.data[0]=10 a.save() but retrieving later doesn't function: I get only <django.db.models.fields.IntegerField> but no actual values... I know about the ArrayField in postgres, but I just use SQLite... Any smarter way than creating 100 individual IntegerFields? -
Django DRF bulk_update primary key
I have used the example from the docs for implementing bulk update: class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping: book.delete() return ret class BookSerializer(serializers.Serializer): # We need to identify elements in the list using their primary key, # so use a writable field here, rather than the default which would be read-only. id = serializers.IntegerField() ... class Meta: list_serializer_class = BookListSerializer https://www.django-rest-framework.org/api-guide/serializers/#listserializer When I try to use this and update a row, I get an error: duplicate key value violates unique constraint \"api_book_pkey\"\nDETAIL: Key (id)=(7) already exists.\n" So it seems like it is not trying to update, rather than creating a new one with the same id. But for me it looks like it is really calling child.update. What is wrong here? -
How to serve media files with control traffic?
I need to serve protected files to users limit by user download quota (for each user). So, I must to calculate every file download. It's easy if I use HttpResponse() for serve files, but it is not efficient and very slow. How do I control every media file download using NGINX server for serve media? Is there any way?