Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template error iterating through dict in jinja template
Here's my code {% for key, value in dictionary.items() %} <a class="dropdown-item" id={{key}}>{{value}}</a> {% endfor %} This is my dictionary dictionary ={"A":"A tab", "B":"B tab","C":"C tab"} I'm using python3 with jinja templates, here's the error I'm facing Django Version: 3.2.12 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '()' from 'dictionary.items()' -
Filling the database table at the expense of the other two Django
I have 3 models based on which I want to build my forms on the site: class Fields(models.Model): shortName = models.CharField(max_length=40) fullName = models.CharField(max_length=40) type = models.CharField(max_length=40) created_at = models.DateTimeField(default=datetime.utcnow()) modified_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Field' verbose_name_plural = 'Fields' class Forms(models.Model): name = models.CharField(max_length=40) created_at = models.DateTimeField(default=datetime.utcnow()) modified_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Form' verbose_name_plural = 'Forms' class FormFields(models.Model): formID = models.IntegerField() fieldID = models.IntegerField() class Meta: verbose_name = 'FormField' verbose_name_plural = 'FormFields' The editing of the form is planned only through the admin panel, in fields I will store all possible fields, and in forms the forms are available for use, in ormfields I want to attach fields to forms Is there any way for me when creating a record in the forms to immediately select the fields there and have it automatically added to the formfields? I tried to implement it through a filter-horizontal, but it didn't work, maybe I specified something wrong: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import * class FormsInline(admin.StackedInline): model = Forms filter_horizontal = ('Fields',) class CustomFields(UserAdmin): save_on_top = True list_display = ('shortName') inlines = [FormsInline] admin.site.register(Fields) admin.site.register(Forms, CustomFields) admin.site.register(FormFields) -
Creating a desktop app with plotly-python
I have been researching for a way to create a desktop app with plotly dynamic graphs. I have been thinking about these following options: using django, and creating the desktop app with electron.js creating an embebbed browser with PyQt5 and running the graphs from it I would like to know if one of these options is possible, or another way of running plotly in a desktop app. -
JQuery / AJAX - Async view - eventlisteners not responding and .remove() is not respecting the selection
it is my first time writing JQuery/AJAX and (silly me) I'm tryng to do something quite complex actually (or at least it is for me lol). Basically I am making an infinte carousel. I am sending the paginated data through a Django view, and I am using JQuery to load it asycronously (so to not refresh the page continuously and lose the previous content). This is the relevant code (I am not including any django related code, because everything there is working just fine, the issue is in the HTML/JS. However if you want to take a look at it, just let me know) HTML <main> <div id="outside-container"> <div id="inside-container" class="infinite-container"> {% for city in cities %} {% get_weather city.name 'metric' 'it' as weather_info %} <div class="items"> <div class="data-div"> <ul> <li><b>{% destructure weather_info 'location' 'city' %}</b> </li> <li class="weather">{% destructure weather_info 'weather' 'description' %}</li> <img src="{% destructure weather_info 'weather' 'icon' %}"> <li>{% destructure weather_info 'main' 'temperature' %}</li> <li>{% destructure weather_info 'location' 'time'%}</li> </ul> </div> <img loading="lazy" class="carousel-img" src="{{city.image.url}}"> </div> {% endfor %} </div> </div> <div id="directions"> <a id="right-button">Right</a> <a id="next-slide" href="?page=2">Next</a> </div> </main> CSS body { margin: 0; padding: 0; background: linear-gradient(-45deg, #4699f8, #fff2f7, #23a6d5, #1779e9); background-size: 400% 400%; animation: … -
Django give a Like Button using JS and DOM result ->404
I got problem with 'live' like unlike button in Django and JavaScript DOM after button is clicked I got an error POST http://127.0.0.1:8000/like/24 404 (Not Found) likePost @ javascripts.js:24 (anonymous) @ javascripts.js:40 javascripts.js:7 I don't know if the problem is in the 'await fetch' function or maybe I used the wrong class or id somewhere. Where to start? javascript.js const reloadPostHTML = async (postId) => { const homePageResponse = await fetch(window.location.href); const newHTML = await homePageResponse.text(); const newDocument = new DOMParser().parseFromString(newHTML, "text/html"); console.log(newDocument) const newPostElem = newDocument .querySelector(`[data-post-id='${postId}']`) .closest(".post"); const oldPostElem = document .querySelector(`[data-post-id='${postId}']`) .closest(".post"); oldPostElem.innerHTML = newPostElem.innerHTML; makeLikeButton(oldPostElem.querySelector(".like-button-wrapper")); }; const likePost = async (postId, csrfToken) => { await fetch(`/like/${postId}`, { method: 'POST', credentials: 'include', headers: { "X-CSRFToken": csrfToken } }); reloadPostHTML(postId); }; const makeLikeButton = (elem) => { elem.querySelector('button').addEventListener("click", (event) => { event.preventDefault(); const postId = elem.dataset.postId; const csrfToken = elem.dataset.csrfToken; likePost(postId, csrfToken); }); }; const makeLikeButtons = () => { for (let elem of document.getElementsByClassName("like-button-wrapper")) { makeLikeButton(elem); } }; makeLikeButtons(); urls.py path( 'article_detail/<int:pk>/', login_required( ArticleDetail.as_view(template_name = "web/article_detail_view.html") ), name='article_detail' ), path('like/<int:pk>', views.like, name='like'), -
'ConnectionHandler' object has no attribute cursor
I'm trying to execute a store procedure from django After searching I found using 'connection.cursor' can do that But djagno give me the error 'ConnectionHandler' object has no attribute cursor Can someone tell me why My code: def newproduct(request): if(request.method == 'POST'): data = NewProductForm(request.POST) if(data.is_valid()): p_data = data.cleaned_data with connections.cursor() as cursor: query = 'EXEC product.newproduct @product_id={0}, @product_name={1}, @product_desc={2}, @price={3},@amount={4}, @category_id={5}, @admin_id={6},@product_img={7}'.format(p_data['product_id'], p_data['product_name'], p_data['product_desc'], p_data['price'],p_data['amount'], p_data['category_id'], p_data['admin_id'], p_data['product_img'] cursor.execute(query) return HttpResponse('ok') else: return HttpResponse('Notvalid') I cannot find any solution about this problem -
Django sharing a lock between workers gunicorn
I am trying to loop inside a view function and I don’t want another worker to run the same loop. For which i am using Lock() but i am unable to achieve this. from multiprocessing import Lock import time lock = Lock() def loop_func(request): lock.acquire() # loop start for i in range(0,100): print ("did work ", i) time.sleep(1) finally: lock.release() can someone help me if there is a way where i can make the shared lock for all workers so that lock will wait till the other worker to finish and enter the loop -
Automate update of models based on conditions
I have a model class Session(models.Model): name = models.CharField(max_length=12) active = models.BooleanField(default=False) date = models.DateField() startTime = models.TimeField() The active field is set based on the date and start time. For eg - Suppose during the creation of an object, the date is for tomorrow, and let there be any time, I want to know the process and not the code on how and what to study to make this object active on that particular date and time. BY default the active field is False, or should I change the way I'm thinking to implement it? Thanks -
Postgres not using trgm index with Concat
I created a trigram index on full name where full_name = first_name || ' ' || last_name. CREATE INDEX "user_full_name_trgm" ON "user" using gin (upper(first_name || ' ' || last_name) gin_trgm_ops); I am using django queryset to filter over fullname. queryset = queryset.annotate(full_name=Concat("first_name", Value(" "), "last_name")) queryset = queryset.filter(full_name__istartswith=full_name) which generates WHERE clause as WHERE (UPPER(CONCAT("user"."first_name", CONCAT(' ', "user"."last_name"))::text) LIKE UPPER('mike%') The explain analyse shows that its not using user_full_name_trgm index. However when I use pipe to join the strings, the index is being used. WHERE (UPPER(first_name || ' ' || last_name) LIKE UPPER('mike%') How can I make django query to use the index? Can I modify query.annotate in such a way that it creates sql query without Concat? Or can I create index in such a way that it is used even with concat? -
call a property decorator through value in django module
I am having issue for the property decorator throug values from the models, The models is class Bills(models.Model): salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) @property def balance(self): return 0 if self.cash == True else self.totalAmount - self.advance i am working on the union method, to display credit bills and any paid transaction are there i am calling the method as bill_trans = Bills.objects.filter(purchasedPerson__id__contains = pk, cash = False).values( 'purchasedPerson__name', 'cash', 'totalAmount', 'remarks', 'created') in the place of total amount i needed balance property is that possible or there is there any other method to make union for the class MemberTrans(models.Model): purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) paid = models.BooleanField(default=False) amount = models.IntegerField() remarks = models.CharField(max_length = 200) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) mem_trans = MemberTrans.objects.filter(purchasedPerson__id__contains = pk).values( 'purchasedPerson__name', 'paid', 'amount', 'remarks', 'created' ) Bill_trans should union with mem_trans -
django.db.utils.operationalerror unable to open database file
I have been struggling finding a solution to my issue "django.db.utils.operationalerror unable to open database file ". I have changed permissions and set my path to an absolute one yet still have the same error. this is my settings.py file """ Django settings for bastionblog project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os from main import constants # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIRS = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = constants.SECRET_KEY # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['77.68.125.183'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bastionblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIRS], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'bastionblog.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES … -
How to validate Child model (StackedInline) fields based on a value of Parent model's field in Django?
I have following structure. models.py class Parent(models.Model): PROVIDER1 = "Provider1" PROVIDER2= "Provider2" PROVIDERS= ( (PROVIDER1, "Test Provider One"), (PROVIDER2, "Test Provider Two"), ) provider = models.CharField( choices=PROVIDERS, max_length=255, default=PROVIDER1, ) # Few more parent fields will be here class Child(models.Model): some_field= models.CharField(max_length=255) # Few more fields will be here parent = models.ForeignKey( Parent, on_delete=models.CASCADE ) admin.py class ChildFormset(BaseInlineFormSet): def clean(self): super().clean() for form in self.forms: if not form.is_valid(): return # errors exist, so return class ChildInline(admin.StackedInline): model = Child formset = ChildFormset extra = 1 min_num = 1 validate_min = True max_num = 1 can_delete = False @admin.register(Parent) class Parent(admin.ModelAdmin): form = ParentForm inlines = [ ChildInline, ] forms.py class ParentForm(forms.ModelForm): class Meta: model = Parent fields = "__all__" def clean(self): cleaned_data = super().clean() # How to access Child model's fields values here to validate them? class Media: # Custom JS to show/hide provider specific fields/divs js = ("js/mycustom.js",) Requirement: When user choose Provider 1 in the Parent I would like to do following Display Child Model's fields (Inline). Validate Child model's fields on submit. I was able to use custom JavaScript for first requirement (hiding and showing fields). But for second requirement I am not able to get the … -
reasons for serializer not validating data DRF
I am sending the data through postman as follows my model.py is as follows def get_upload_path(instance, filename): model = instance._meta name = model.verbose_name_plural.replace(' ', '_') return f'{name}/images/{filename}' class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Photo(models.Model): name = models.CharField(max_length=255, null=True, blank=True) photo = models.ImageField(upload_to=get_upload_path, null=True, blank=True) default = models.BooleanField(default=False, null=True, blank=True) width = models.FloatField(default=100, null=True, blank=True) length = models.FloatField(default=100, null=True, blank=True) description = models.CharField(max_length=2000, null=True, blank=True) latitude = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) longitude = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) album = models.ForeignKey(ImageAlbum, related_name='album_data', on_delete=models.CASCADE, null=True, blank=True) my view.py is as follows class ImageAlbumListApiView(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser, ] def get(self, request): image_album = ImageAlbum.objects.all() serializer = ImageAlbumSerializer(image_album, many=True) return Response(serializer.data) def post(self, request): serializer = ImageAlbumSerializer(data=request.data) print(request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) My serializer.py is as follows class PhotoSerializer(serializers.ModelSerializer): class Meta: model = models.Photo fields = '__all__' class ImageAlbumSerializer(serializers.ModelSerializer): album_data = PhotoSerializer(many=True, read_only=True) file = serializers.ListField( child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False, write_only = True), write_only=True) class Meta: ###Test### model = models.ImageAlbum fields = ['id', 'album_data', 'file'] read_only_fields = ['id'] def create(self, validated_data): #album_data = validated_data.get('album_data') print(validated_data) uploaded_files = validated_data.get('file') #image_info = validated_data.pop('images') album = models.ImageAlbum.objects.create() … -
Django ORM for fetching latest record for specific ID
How do I write a django ORM to fetch the most recent records from the table for a specific id. Example: I have table(tr_data) data like: id trs(foreign key) status last_updated 1 301 3 2022-11-28 06:14:28 2 301 4 2022-11-28 06:15:28 3 302 3 2022-11-28 06:14:28 4 302 4 2022-11-28 06:15:28 5 302 2 2022-11-28 06:16:28 I want to have a queryset values that gives me trs id with its latest status.I have tried with aggragate and MAX but not getting the desired result. Expecting ouput as : [{"trs":301, "status":4},"trs":302,"status":2}] -
How to get an records with each month in a date range of two fields?
I have a study year model which has a start and end date. class StudyYear(models.Model): date_begin = models.DateField(...) date_end = models.DateField(...) I need a Queryset in which there are records for each study year with a month in its date range (start_date:end_date) Example: For the study year (09/01/2022:01/02/2023), qs should contain records: ... (code=9_2022, name='September 2022'), (code=10_2022, name='November 2022'), (code=11_2022, name='October 2022'), (code=12_2022, name='December 2022'), (code=1_2023, name='January 2023'), (code=2_2023, name='February 2023'), ... Honestly, I have no idea how to solve this problem, I really hope for your help! -
how to compare dictionaries and color the different key, value
I have a django application. And I have two texboxes where data is coming from two different functions. So the data is displayed in the texboxes. But the key,value has to be marked red when there is a difference in the two dictionaries. So in this example it is ananas that has the difference. So I have the TestFile with the data: class TestFile: def __init__(self) -> None: pass def data_compare2(self): fruits2 = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 30, } set2 = set([(k, v) for k, v in fruits2.items()]) return set2 def data_compare(self): fruits = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 24, } set1 = set([(k, v) for k, v in fruits.items()]) return set1 def compare_dic(self): set1 = self.data_compare() set2 = self.data_compare2() diff_set = list(set1 - set2) + list(set2 - set1) return diff_set the views.py: from .test_file import TestFile def data_compare(request): test_file = TestFile() content_excel = "" content = "" content = test_file.data_compare() content_excel = test_file.data_compare2() diff_set =test_file.compare_dic() context = {"content": content, "content_excel": content_excel, "diff_set": diff_set} return render(request, "main/data_compare.html", context) and the template: {% extends 'base.html' %} {% load static %} {% block content %} <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"> <title>Document</title> </head> <body> <div … -
Django Rest Framework's API for Razorpay Callback couldn't be authenticated
@api_view(['POST']) @permission_classes([]) #@permission_classes([IsNormalUser])# cant use, JWT misses @authentication_classes([]) def verifyRazorPay(request): if success: return Response(success) else: return Response(failure) As you can see in the code this is a callback API for Razorpay. But I couldn't make this secure by any of the permission_classes, authentication_classes because Razorpay doesnt use any of JWT tokens for headers that I use in my website application. How to secure this in any manner by authorizing .. that anonymous users cant throttle it. -
How to save a resized image Django?
I try to save both, an original and a resized image and can't understand on what step Django will understand from WHICH FIELD it will take the image to resize and then save. MODELS.PY: from django.db import models from django_resized import ResizedImageField class Post(models.Model): thumbnail = models.ImageField(upload_to ='uploads/posts/large/') thumbnail_small = ResizedImageField(size=[100, 100], upload_to='uploads/posts/small/') FORMS.PY class PostForm(forms.ModelForm): class Meta: model = Post fields = ['thumbnail','thumbnail_small'] HTML: <form method = "POST" action = "{% url 'adminpanel' %}" enctype = "multipart/form-data"> {% csrf_token %} <input type = "file" id = "file" name = "thumbnail" accept = "image/png, image/jpeg"> <button type = "submit" class = "btn" name = "apost">Add Post</button> </form> So, the question is, where will Django understand that it has to save image directly from the <input name = "thumbnail"> directly to thumbnail = models.ImageField(upload_to ='uploads/posts/large/') and also to thumbnail_small = ResizedImageField(size=[100, 100], upload_to='uploads/posts/small/')? Thanks in advance. -
django serializer error: images_data = self.context['request'].FILES KeyError: 'request'
models.py ` # from django.db import models from user.models import User from chat.models import TradeChatRoom, AuctionChatRoom class Goods(models.Model): class Meta: db_table = 'Goods' ordering = ['-created_at'] # 일단 추가해뒀습니다 seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sell_goods') buyer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='buy_goods', null=True) trade_room = models.ForeignKey(TradeChatRoom, on_delete=models.CASCADE) auction_room = models.ForeignKey(AuctionChatRoom, on_delete=models.CASCADE) title = models.CharField(max_length=256) content = models.TextField() category = models.CharField(max_length=32) status = models.BooleanField(null=True) predict_price = models.IntegerField() start_price = models.IntegerField() high_price = models.IntegerField(null=True) start_date = models.DateField(null = True) start_time = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User, related_name='like_goods', null=True) class GoodsImage(models.Model): class Meta: db_table = "GoodsImage" goods = models.ForeignKey(Goods, on_delete=models.CASCADE) image = models.ImageField(upload_to='goods/') ` serializer.py from rest_framework import serializers from .models import Goods,GoodsImage class GoodImageSerializer(serializers.ModelSerializer): image = serializers.ImageField(use_url=True) def get_image(self, obj): image = obj.goods_set.all() return GoodsPostSerializer(instance=image, many = True, context = self.context) class Meta: model = GoodsImage field =('image',) class GoodsPostSerializer(serializers.ModelSerializer): image = GoodImageSerializer(many=True, read_only = True) class Meta: model = Goods fields = ( 'seller', 'buyer','auction_room','title','content', 'category','status','predict_price','start_price','high_price', 'trade_room','start_date','start_time','created_at','like','image', ) read_only_fields = ("seller",) def create(self, validated_data): goods = Goods.objects.create(**validated_data) images_data = self.context['request'].FILES for image_date in images_data.getlist('image'): GoodsImage.objects.create(goods = goods, image = image_date) return goods error images_data = self.context['request'].FILES KeyError: 'request' I want to save multiple images, but I keep getting an error. I don't … -
What is right order for defining django view decorators
I want to set more than one decorator for my django function view. The problem is that I can't figure out how should be the order of decorators. For example this is the view I have: @permission_classes([IsAuthenticated]) @api_view(["POST"]) def logout(request): pass In this case, first decorator never applies! neither when request is POST nor when it's GET! When I change the order, to this: @api_view(["POST"]) @permission_classes([IsAuthenticated]) def logout(request): pass the last decorator applies before the first one, which is not the order that I want. I want the decorator @api_view(["POST"]) to be applied first, and then @permission_classes([IsAuthenticated]). How should I do that? -
Mysterious Issues uploading images Django
I hope someone can help me out here, something strange and mysterious is happening with my code. I have a project which was working normally, but suddenly the images stopped to get uplodad. I was working on an update method in the viewset when I realized that. even more awkward is that I have two apps on my application one uploads the images normally and other doesn't. I have tried to change the upload_to direction on the field which is not been uploaded and noticed that the new direction hasn't been applied, the destination folder is saved in the database with a previous direction (even though the picture never gets uploaded) below you have the codes: first the result of an update: notice the address { "profile": 4, "card": "teste2", "points": 0, "created": "2022-11-29T16:05:33.502027Z", "updated": "2022-11-30T10:26:15.063888Z", "code": "673476", **"image": "http://127.0.0.1:7000/medias/media/app_user/img_DENklQy.jpg"** } now the models, notice the upload_to: class MyCards(models.Model): profile = models.ForeignKey(AppUserProfile, on_delete=models.CASCADE) card = models.ForeignKey(Cards, on_delete=models.CASCADE) points = models.IntegerField(default=0) **image = models.ImageField(upload_to='mycards', blank=True)** created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) code = models.CharField(max_length=6, blank=True, null=True) my settings: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = '/medias/' MEDIA_ROOT = os.path.join(BASE_DIR, 'medias' ) viewset, I have removed the update overriding method, to check if was … -
My colleague and I argue is pizza or kebab better for increasing programming performance
My colleague and I argue is pizza or kebab better for increasing programming performance. Pizza is richer with carbohydrates, while kebab has more veggies and meat in it and is better balanced. We work in Django framework. We'd like to hear your professional opinion. We tried both pizza and kebab and after pizza we feel sleepy some time. While kebab doesn't get you sleepy, but it doesn't get you full either. -
How to use Lookups that span relationships in Django
I have models User, Store, Warehouse and Product. I need to get all products from the warehouse. User have a lot of stores. One store have a lot of warehouses. А product with the same identifier (SKU) can be stored in different warehouses. def get_queryset(self): return Product.objects.filter( warehouse__store__user_id=self.request.user.pk)\ .order_by('-offer_id') Am I right to filter products such way? -
Getting bad Request Error when I try to send formdata including an attachment to DRF Backend from React Native Frontend
I am working on a react native project where I have to send a "Request Financial Aid" form to backend, The form also consists of a file(image or pdf), I have used react native document picker to get the file then I used file uri to fetch the blob. The next thing I did is send the formdata to backend however my backend is not getting all the values which I send from frontend which may be the reason why I am getting Bad Request. Error Trace Here My Backend works fine when I send data from my web app so I know the issue isn't in the backend. This is How I am picking the file: const selectFile = async () => { // Opening Document Picker to select one file try { const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.allFiles], }); console.log('res simple', res); console.log('res : ' + JSON.stringify(res)); //fetch uri from the response const fileUri = res.uri; console.log('res : ' + fileUri); setSingleFile(res); // handleAcceptedFiles(res); } catch (err) { setSingleFile(null); if (DocumentPicker.isCancel(err)) { ToastAndroid.show('Canceled', ToastAndroid.SHORT); } else { alert('Unknown Error: ' + JSON.stringify(err)); throw err; } } }; This is how I am getting blob using file uri. … -
Can I get error index with bulk_create/bulk_update?
I'm using bulk_create method to insert data from an Excel sheet to db. This data can be incorrect (ex: cell contains "Hello World" when it should be an integer) and I'd like to return user thorough information error. Currently, bulk_create raises a ValueError, ex: Field 'some_integer_field' expected a number but got 'Hello World'. Is it possible to get more details about this error, something like : **Line 4** - Field 'some_integer_field' expected a number but got 'Hello World'. without saving each object individually ? Does it even make sense since bulk_create produces a single transaction ? I'm running Django 4.1.3 with PostgreSQL 12. My code looks like self.MyModel.bulk_create(self.objects_to_create)