Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show only one object in django admin list view?
Problem I wish to show only the last row of a QuerySet based on the ModelAdmin's ordering criteria. I have tried a couple of methods, but none has worked for me. Model: class DefaultConfig(models.Model): created_at = models.DateTimeField() ... Attempt 1: I tried overriding the ModelAdmin's get_queryset method and slicing super's result, but I came up with some issues. I.E: class DefaultConfigAdmin(models.ModelAdmin): model = Config ordering = ('-created_at',) def get_queryset(self, request): qs = super().get_queryset(request) return qs[<slice>] I tried the following values for [<slice>]s: [-1:]: raised an Exception because negative slicing is not supported [:1]: raised AssertionError: Cannot reorder a query once a slice has been taken. Attempt 2: I tried obtaining the max value for created_at and then filtering for records with that value. I.E: class DefaultConfigAdmin(models.ModelAdmin): model = Config def get_queryset(self, request): qs = super().get_queryset(request) return qs.annotate(max_created_at=Max('created_at')).filter(created_at=F('max_created_at')) But silly me, that works at row level, so it will only return aggregates over the row itself. Further attempts (TBD): Perhaps the answer lies in SubQuerys or Windowing and ranking. Is there a more straight forward way to achieve this though? -
how Querying Dijango date save on JSONField
i save multi date in json filed example : row 1 : [ "2022-10-26", "2022-11-10" , "2022-11-16", , "2022-11-17"] row 2 : [ "2022-09-26", "2022-09-10" , "2022-09-16"] row 3 : [ "2022-12-16" ] **how i can filter date bigger than 2022-10-01 ? ** in the example i must get row 1 & 3 database is MYSQl Django Ver 4.1 example : row 1 : [ "2022-10-26", "2022-11-10" , "2022-11-16", , "2022-11-17"] row 2 : [ "2022-09-26", "2022-09-10" , "2022-09-16"] row 3 : [ "2022-12-16" ] in the example i must get row 1 & 3 -
Django stripe is returning "No such token: 'tok_1M2CbwG5K6HWS5kNipsQbCKh'" as error message
Anytime i tried to make a test payment on stripe, it returns the error below, sk_test_hBNQ83MDWulMeAawYbGftrcC00pDMpmoAB tok_1M2CbwG5K6HWS5kNipsQbCKh 86.0 25 Request req_eboPGGTsmc4D3a: No such token: 'tok_1M2CbwG5K6HWS5kNipsQbCKh' i tried with the api keys from stripe but still it wont work. -
django clone project migrate error occured
"django.db.utils.OperationalError" occurred while setting using django cookiecutter. config\settings\base.py DATABASES = { "default": env.db( "DATABASE_URL", default="postgres://postgres:root@localhost:5432/instagram", ), } C:\dev\clone\instagram>py manage.py migrate Traceback (most recent call last): File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 244, in ensure_connection self.connect() File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\dev\clone\instagram\manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 91, in handle self.check(databases=[database]) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\model_checks.py", line 36, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 1461, in check *cls._check_indexes(databases), File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 1864, in _check_indexes connection.features.supports_covering_indexes File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = … -
Nginx unable to access css files in static folder for django admin
I have django running on AWS. Nginx is used as proxy with gunicorn as web server. I followed the [digitaocean][1] tutorial to configure. The problem is that django admin interface doesnt show any ui as no css files are loaded. nginx error log show this: [error] 46553#46553: *7 open() "/home/ubuntu/projectdir/static/admin/css/base.css" failed (13: Permission denied), client: 190.176.82.41, server: 142.22.84.99, request: "GET /static/admin/css/base.css HTTP/1.1", host: "142.22.84.99", referrer: "http://142.22.84.99/admin/" i changed the ownership of static folder to group www-data but still the same issue. ubuntu version is 22.04, django is 4.1.3 and python is 3.10.6 [1]: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 -
Django queryset.update() seems to act lazy
I have a Django model with a field named 'order': class Foo(models.Model): user = models.ForeignKey(...) order = models.PositiveIntegerField(null=True) class Meta: unique_together = [ ['user', 'order'], ] I want to implement an update method for my serializer to be able to reorder an object. Let's consider our object's current order is 5 and we want to change it to 1. So the scenario is sth like this: 1- make obj's current order null 2- increament order of objects that have an order between our obj's current_order and new_order 3- change obj's order to new_order My firs code was this: def update(self, instance, validated_data): user = self.context['request'].user current_order = instance.order new_order = validated_data['order'] instance.reorder(None) if new_order < current_order: qs = PIN.objects.exclude(order__isnull=True).filter( user_id=user.id, order__gte=new_order, order__lt=current_order ).update(order=F('order')+1) else: qs = PIN.objects.exclude(order__isnull=True).filter( user_id=user.id, order__gt=current_order, order__lte=new_order ).update(order=F('order')-1) But the problem is the order of updating objects in database and I get unique constraint error: ('user', 'order') = ('x', '2') already exist I did read the [django documentations][1] for queryset.update method, so, order_by method is not the result. I decided to change my code to this: user = self.context['request'].user current_order = instance.order new_order = validated_data['order'] instance.reorder(None) if new_order < current_order: qs = Foo.objects.exclude(order__isnull=True).filter( user_id=user.id, order__gte=new_order, order__lt=current_order ) … -
Python can not read characters
when i sent request in api import requests url = 'webiste' headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'} response= requests.get(url.strip(), headers=headers, timeout=10) response.encoding = response.apparent_encoding print(response.text) output is 0e1\u10e2\u10d4\u10db\u10d0 BOSE,\u10d3\u10d0\u10ec\u10e7\u10d4\u10d1\u10d0-\u10d2\u10d0\u10e9\u10d4\u10e0\u10d4\u10d1\u10d8\u10e1 \u10e1\u10d8\u10e1\u10e2\u10d4\u10db\u10d0,\u10d4\u10da\u10d4\u10e5\u10e2\u10e0\u10dd\u10dc\u10e3\u10da\u10d8 \u10d3\u10d8\u10e4\u10d4\u10e0\u10d4\u10dc\u10ea\u10d8\u10d0\u10da\u10e3\u10e0\u10d8 \u10e1\u10d0\u10d9\u10d4\u10e2\u10d8,\u10eb\u10e0\u10d0\u10d5\u10d8\u10e1 \u10e1\u10d0\u10db\u10e3\u10ee\u10e0\u10e3\u10ed\u10d4 \u10d9\u10dd\u10dc\u10e2\u10e0\u10dd\u10da\u10d8\u10e1 \u10e1\u10d8\u10e1\u10e2\u10d4\u10db\u10d0,\u10ec\u10d4\u10d5\u10d8\u10e1 \u10d9\u10dd\u10dc\u10e2\u10e0\u10dd\u10da\u10d8\u10e1 \u10e1\u10d8\u10e1\u10e2\u10d4\u10db\u10d0,\u10e1\u10e2\u10d0\u10d1\u10d8\u10da\u10e3\u10e0\u10dd\u10d1\u10d8\u10e1 \u10e1\u10d8\u10e1\u10e2\u10d4\u10db\u10d0,\u10d3\u10d0\u10d1\u10da\u10dd\u10d9\u10d5\u10d8\u10e1 \u10e1\u10d0\u10ec\u10d8\u10dc\u10d0\u10d0\u10e6\u10db\u10d3\u10d4\u10d2\u10dd \u10d3\u10d0\u10db\u10e3\u10ee\u10e0\u10e3\u10ed\u10d4\u10d how to encode in utf-8 ? -
JWT token expire successfully but still able to access Django API's
I'm using JWT token auth in django. I set access-token timing to '1 minute' after 1-min the access & refresh token get expire and but when i try to access API url it gives access and show data. i check with the verifyToken same token shows invalid. and using same token for api call it shows success=True and print 'hello1' Can anyone tell me whats wrong with JWT Check below code for referance. JWT Docs for referance. https://django-rest-framework-simplejwt.readthedocs.io/en/latest/ Code: Setting.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer', ), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'slash.controllers.pagination.PageNumberCustomPagination', 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', } CRONJOBS = [ ('0 23 * * *', 'slash.cron.delete_expired_blacklisted_token'), ] CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ) DRF_API_LOGGER_DATABASE = True DRF_LOGGER_QUEUE_MAX_SIZE = 50 DRF_LOGGER_INTERVAL = 10 DRF_API_LOGGER_EXCLUDE_KEYS = ['password', 'token', 'access', 'refresh'] # Sensitive data will be replaced with "***FILTERED***". DRF_API_LOGGER_SLOW_API_ABOVE = 200 URLS.py path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('token/blacklist/', TokenBlacklistView.as_view(), name='token_blacklist'), … -
serialize write-only field which is not present in django model using viewset
I am using a django viewset and I want to serialize a field which is not in the model. it is an extra field that would be passed by the user. class Bank(models.Model) name = models.CharField(max_length=255) objects = models.Manager() class BankingDetailsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) name = serializer.CharField() documents = serializers.ListField(write_only=True) class Meta: model = Bank fields = ['id', 'name', 'documents'] I am using a modelViewset for my view. However I noticed that after I serialize, the documents field is missing -
Predict user requests and prepare response
Is it possible to predict user request and prepare response even before a request is been made? Test case: I have an endpoint that connect to another API that takes so long to respond up to 12 sec and that makes my application performance drop significantly while i can't modify that api and i can't stop using it. this api takes 2 user input which are start_date and end_date. i want to find a way to optimise that and i was thinking of pre-preparing the data before even receiving a request for it but i still don't know if it is possible or not. Technology i use VueJs in frontend and python(Django) in the backend. i would appreciate the help considering that matter. i did try to make it into jobs but still the same the processes fire when the user ask for the data and the job take the same time as normal implementation in code -
Can I use regular expressions in Django F() expressions?
I have a model: class MyModel(models.Model): long_name = models.CharField(unique=True, max_length=256) important_A = models.CharField(unique=True, max_length=256) important_B = models.CharField(unique=True, max_length=256) MyModel.long_name contains information, that I need to put in dedicated fields (important_A and important_B). An example of a string in long_name would be S1_arctic_mosaic_tile_029r_016d_300_20221108T062432.png I basically need to match one part of the string in long_name, i.e. everything between the 4. and the 5. underscore ("029r") and put it into important_A, and everything between the 5. and the 6. ("016d") into important_B. Since the database (PostgreSQL on Django 3.2.15) is quite big (~2.000.000 rows), looping (and using things like Python's str.split()) is not an option, as this would take too long. I'm thus looking for a way to use regex in the migration to populate important_A and important_B from long_field. My current migration looks like this: from django.db import migrations, models from django.db.models import F def populate_fields(apps, schema_editor): MyModel = apps.get_model("myapp", "mymodel") MyModel.objects.all().update(important_A= F('long_name=r"S1_.*_(\d{2,3}(r|l)_\d{2,3}(u|d))_.*\.png"') ) class Migration(migrations.Migration): dependencies = [ ('icedata', '0036_something'), ] operations = [ migrations.RunPython(populate_fields), ] When I try to run this migration, I get the following error: django.core.exceptions.FieldError: Cannot resolve keyword 'filename=r"S1_.*_(\d{2,3}(r|l)_\d{2,3}(u|d))_.*\.png"' into field. Choices are: long_name, id When I instead use F('long_name__regex=r"S1_.*_(\d{2,3}(r|l)_\d{2,3}(u|d))_.*\.png"'), I instead get: Cannot resolve keyword … -
I want to get the details after I click on the Add to Cart button but I am getting error saying cart doesn't take an argument
This is views.py file from the cart section where I want to add product, remove product and show product details in the cart. Error is : Cart() takes no arguments. from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from ecommerce.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], override_quantity=cd['override']) return redirect('cart:cart_detail') @require_POST def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) products = [] for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={ 'quantity': item['quantity'], 'override': True}) return render(request, 'cart/detail.html', {'cart': cart}) -
How to refer to model class (name) from html form to views.py with Django?
I want users to be able to download a Django model which is being displayed in the app. There can be many types of models, therefore I want to generalize my code. Currently I let users download the model in excel by means of the following code in HTML: <form id="downloadfile" method="post" action="{% url 'download_file' filename='Irrelevant.xlsx'%}"> {% csrf_token %} <input type="hidden" value="Plant" name="database" /> <input type="submit" name="downloadfile" class="btn btn-success" value="Download Plant"> </form> My views.py: # Define function to download excel file using template from database.models import Plant def download_file(request, filename=''): if 'downloadfile' in request.POST: db_name = request.POST.get('database') #How to specify Plant database? response = xlsx_generator(Plant, db_name) #db_name is used to name the .xlsx file and is just a string. return response else: #some other things to do for other post requests As you can see, I import the Plant model from database.models, and refer to it manually in the xlsx_generator. What I would like to do is refer to this imported model from the posted form so that I don't have to refer to it manually anymore. e.g. db_model = request.POST.get('database') and then response = xlsx_generator(db_model, db_name) where db_model refers to Plant model. Can this be achieved? And if yes, … -
Get the value of the dict in the first element of the list
class PermsField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 64 kwargs['verbose_name'] =_('permission') super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] del kwargs["verbose_name"] return name, path, args, kwargs class AuzGroup(models.Model): perms = PermsField() class Profile(models.Model): user = models.OneToOneField( to=User, on_delete=models.CASCADE, parent_link=True, related_name='profile', primary_key = True) perms = PermsField() auz_groups = models.ManyToManyField( AuzGroup, through='ProfileToAuzGroupM2M') class ProfileToAuzGroupM2M(models.Model): auz_group = models.ForeignKey('AuzGroup', on_delete=models.CASCADE) profile = models.ForeignKey('Profile', on_delete=models.CASCADE) [{'perms': "['consultant', 'project manager', 'admin', 'viewer admin']"}] I create my custom AuzBackEnd and i want to recreate the function get_group_permissions(self, user_obj, obj=None). This function should return the variable perms in the class AuzGroup. I cant simply return user_obj.profile.auz_group.perms. I find an other way, i use values so when i use it, i do list(user_obj.profile.auz_groups.values('perms')) (i use list() to have the good type). With this solution i get '[{'perms': "['consultant', 'project manager', 'admin', 'viewer admin']"}]' but i only want "['consultant', 'project manager', 'admin', 'viewer admin']" more simply i want the value of the dict in the first element of the list. I dont know how i can do it if you can help me, thx. PS: The better thing i have is list(list(user_obj.profile.auz_groups.values('perms'))[0]['perms'].split(",")) but this give me '{"'admin'", "'project manager'", "'consultant'", "'viewer admin'"}' and i got … -
Error installation custom django app package
I'm trying to install in a Django project my own package but when add the app to INSTALLED_APPS through the next error: ModuleNotFoundError: No module named 'django_dashboards_app' Code pypi Anybody could help me please ? Thanks in advance. -
ModuleNotFoundError: No module named 'xmltodict' - getting this error in python shell
I am getting this error even though I installed the python package. ` from django import forms from xmlform.models import MultiLookupValue, MultiLookup import json import xmltodict with open("C:/Users/Adithyas/Desktop/copy/xmlinvoice/xmlform/Supplier.xml") as xml_file: data_dict = xmltodict.parse(xml_file.read()) json_data = json.dumps(data_dict) y = json.loads(json_data) def importx(): i = [] for i in range(1, 48950): record = y['objects']['record'][i] x = MultiLookupValue.objects.create(value=record) x.save() ` This is my code. I am trying to run this code on python shell but getting this error. This is my code. I am trying to run this code on python shell but getting this error. -
How to pass params query string in django GET request?
My path: path('<str:link>/', ListUserSearchView.as_view()), My View: class ListUserSearchView(APIView): def get(self, request, link): url = "baseurl" querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": "apikey", "X-RapidAPI-Host": "apihost" } response = requests.request("GET", url, headers=headers, params=querystring) data = response.text return Response(data) I would like to pass the link from params but this does not work, any help ? -
How do i store connections to other website on a server?
I am currently trying to write an application, which collects data from various websites using their APIs. How would i store/manage connections to those websites, so that the users do not have to log in every time they use the application? -
Add one year license to my Django project made by me for a pathology lab
So I have made a project for a pathology Lab. They will be using it in localhost. I now have hand it over to them. But I want to a one year expiry license to it. so one year later I will have to offer them another license. so is it possible I can do that? I tried searching for it over the internet but found nothing! -
AttributeError: 'coroutine' object has no attribute 'all'
I'm running Django 4.1 and for ModelChoiceField I need to pass a queryset, but async function passes coroutine. So, is there any way to handle this? async def get_currency_queryset(): return await sync_to_async(Currency.objects.all)() class AddOfferForm(forms.ModelForm): currency_to_sell = forms.ModelChoiceField( queryset=get_currency_queryset(), empty_label="Choose currency", widget=forms.Select(attrs={"class": "form-select"}), ) -
Docker server on Django [closed]
I was using docker in my Django project. But due to some issue, I uninstalled docker from my system. But now I am trying to run the server(localhost). But the server name is showing 'kubernetes.docker.internal'. Could anyone help to resolve this problem? -
Django restAPI: How to split up frontend and backend
I have the following setup: I have a django-project containing of a frontend and a backend. The frontend is the portal, where the user can login, manage their account and create/delete API-keys used in the backend. The backend is a restAPI for which the an API key (created by the user) is required. I use djangorestframework and djangorestframework-api-key. So far so good. The problem now is: How to separate frontend and backend properly? Ideally, frontend and backend should have as little dependencies on each other as possible, Of course, both need access to the API-keys which right now is done via a Django-model. This however leads to code-duplication (same model required in both frontend and backend). This feels a little shady to me.... What is the best way to achieve that? Is there something fundamentally wrong in the setup? I have tried "separating" the two by defining only the table-layout, but this then simply leads to two "independent" implementations of the model in front- and backend. Feels like the same thing as described above. Any suggestions are appreciated! -
in Django, I use sweetalert2
I have used sweetalert2 to pop up messages, it works great when page return render but when I used return redirect not works there is something I need to add it. any helps Thanks I want a sweetalert2 to pop up when the user submit forms in Django views messages.success(request, 'yes') return render(request, 'app/home.html') Not pop up messages.success(request, 'yes') return redirect('app:home') in html page {% for message in messages %} <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script> {% if message.tags == 'success' %} <script> Swal.fire( 'good', '{{message}}', 'success' ) </script> {% endif %} {% endfor %} -
How to upload multiple images to a django product model using DRF
Currently I am able to upload only 1 image per product. My Model class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png') brand = models.CharField(max_length=200, null=True, blank=True) category = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) price = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) This is my serializer class ProductSerializer(serializers.ModelSerializer): reviews = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = '__all__' def get_reviews(self, obj): reviews = obj.review_set.all() serializer = ReviewSerializer(reviews, many=True) return serializer.data This is the views file @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) serializer = ProductSerializer(product, many=False) return Response(serializer.data) I am trying to also upload the images to a folder which has same product name if possible. -
Implement hmset in python with dictionary of list and nested dictionary
I was trying to implement below redis code into python django application hmset test_template:TEMPLATE_ID test_tags "[{\"key\":\"test_manual_entry_1\",\"value\":\"Some_value_1\"},{\"key\":\"test_manual_entry_2\",\"value\":\"Some_value_2\"}]" I have tried hset and hmset functions but both are giving the error. Below is sample of my code looks like this class RedisUtil: def hset(self, key_name, data): key_name = "test_template:TEMPLATE_ID" list_data = [{"key": "test_manual_entry_1", "value": "Some_value1"}, {"key": "test_manual_entry_2", "value": "Some_value2"}] data = {"test_tags": [json.dumps(d) for d in list_data]} # output list: ['{"key": "test_manual_entry_1", "value": "Some_value1"}', '{"key": "test_manual_entry_2", "value": "Some_value2"}'] I have tried below methods to save but all methods are giving me error # Method 1 self.redis_client.hset(key_name, data) # Exception: redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first. #Method 2 self.redis_client.hset(key_name, "test_tag", data["test_tags"]) # Exception: redis.exceptions.DataError: Invalid input of type: 'list'. Convert to a bytes, string, int or float first. Also, I would like add there that there may be case where my list will be empty, this could be an edge case. Thanks in advance for any help.