Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Correct way to handle database errors in Django
I have doubts about how to implement certain things in a Django Rest API (I'm using DRF), and I want to ask you for guidelines. Imagine two models, for example, Employee, and Department. Each employee belongs to a Department, so the model should contain a foreign key in Employee pointing to the Department to which he belongs. We cannot save an Employee if we do not assign a valid Department. So, the scenarios we need to handle are, from the top of my head: An Employee with no Department An Employee with an invalid Department Now, because this is a REST API, I assume that the data that feeds the application came from the POST call. So, both scenarios can be represent as: bad_payload = { "employee_name": "John Doe", } inconsistent_payload = { "employee_name": "John Doe", ... "department": "Invalid Department" } Assuming Invalid Department is not on the database. So, my questions: Would the view be the best place to validate, or would it be better to trust the error that the database will throw when trying to insert the data into the table? (Remember, the foreign key has the NOT NULL restriction. If the validation is done on the … -
Generating and storing sitemaps for a django-tenants project
I am currently working on a Django SaaS project powered by django-tenants having a few tenants. What is the best way to generate sitemaps for a multi-tenancy app? Is it preferable to save the sitemap file for each tenant in disk storage or to cache each sitemap in memory? -
Cannot reinitialise DataTable in Django
I'm confused on how can I infuse my json format from django to Datatable , what I tried below using loop in the script {% for json in company %} <script>..</script> {% endfor% } but It persist error DataTables warning: table id=DataTables_Table_0 - Cannot reinitialise DataTable. Is there's any wrong with my implementation, Am I correct? to fetch all data from views.py json to datatable , is there anyway? Javascript {% block footer_scripts %} {% for row in company %} <script> $(function () { var dt_basic_table = $('.datatables-basic'), dt_complex_header_table = $('.dt-complex-header'), dt_row_grouping_table = $('.dt-row-grouping'), dt_multilingual_table = $('.dt-multilingual'), dt_basic; // DataTable with buttons // -------------------------------------------------------------------- if (dt_basic_table.length) { dt_basic = dt_basic_table.DataTable({ ajax: assetsPath + 'json/table-datatable_example.json', //I want to infused here the json format from views.py columns: [ { data: '' }, { data: 'id' }, { data: 'id' }, { data: 'full_name' }, { data: 'email' }, { data: 'start_date' }, { data: 'salary' }, { data: 'status' }, { data: '' } ], columnDefs: [ { // For Responsive className: 'control', orderable: false, searchable: false, responsivePriority: 2, targets: 0, render: function (data, type, full, meta) { return ''; } }, { // For Checkboxes targets: 1, orderable: false, searchable: false, … -
Unable to display continuous output from a python script to HTML view in django
I am trying to display the continuous output from a python script on the HTML page but the output is being displayed once the entire execution of the script is completed. I have used subprocess to run the python script(test.py) and when I execute the python script independently I could see the output line by line but the same is not working when I use it along with websockets. Can anyone please help me fix the problem? Here is my code: consumers.py import os import subprocess from channels.generic.websocket import AsyncWebsocketConsumer class MyAsyncWebsocketConsumer(AsyncWebsocketConsumer): async def connect(self): print("Websocket connected") print("Channel name...", self.channel_name) print("Channel layer...", self.channel_layer) await self.channel_layer.group_add('programmers', self.channel_name) await self.accept() async def receive(self, text_data=None, bytes_data=None): print("Message received from the client", text_data) current_dir = os.getcwd() script = current_dir + '/' + 'test.py' try: p = subprocess.Popen(['python', script], stdout=subprocess.PIPE, bufsize=3) for line in iter(p.stdout.readline, b''): line = line.decode("utf-8").strip() await self.send(text_data=line) except subprocess.CalledProcessError as e: print(e) async def disconnect(self, code): print("Websocket disconnected", code) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> <h3>Count Page</h3> <textarea id="chat-log" cols="100" rows="20"> </textarea><br> <input type="button" value="Submit" id="script-run-submit"> <script> var ws = new WebSocket('ws://127.0.0.1:8000/ws/awsc/') ws.onopen = function() { console.log("Websocket connection opened") } ws.onmessage = function(event) { console.log("Message received … -
Django Package on virtual environment Malfunction after a certain time after reinstallation on cPanel share hosting server on deployment
I'm hosting a django project on a Shared hosting server cpnal that use CloudLinux. I've respect all the step and requirements to host a django project on a shared hosting server using passanger_wsgi.py. When I create a python application, getting a virtual enviromnent and installing all required package for my django project to work properly everything work very well and my application itself doesn't have any error and I have done all the test. But after a certain time, takes one or two weeks my python app get some packages error, some of them(mysqlclient, pillow, ....) and I'm obliged to delete the application, recreate it again and reinstall all the package to make everything work again. I've try to solve the error with the hosting service admin -> installing the lsapi and also install the python development package for Mysql. By my side I've tried to change the Mysql client package with pymsql and other. But still getting that error but it's periodic after one or two weeks after reinstallation. So please what can I do. I need some help before taking the decison of trying another hosting service. Is there something i'm missing, please help me. -
uwsgi harakiri is set but it doesn't work
I have configured the django project for run in the uwsgi.ini file and also set harakiri to increase timeout, but it doesn't work. Help me please [uwsgi] chdir = /app static-map = /static=/app/static module = svms.wsgi:application env = DJANGO_SETTINGS_MODULE=svms.settings uid = 1000 master = true # threads = 2 processes = 5 harakiri = 5000 max-requests = 1000 # respawn processes after serving 1000 requests vacuum = true die-on-term = true -
ImportError: attempted relative import beyond top-level package
I am using django framework, Here i have created the first_app application in django, i have created a simple view which will return hello world http response, I am trying to map this url in the urls.py, but it throws import_error by saying that " attempted relative import beyond top-level package", i have attached the project folder structure below for reference, How do i need import that view in urls.py file which are in above attached folder structure. I am using this pattern "from ..first_app import views" which throws error like attached format -
How does Django QuerySet cache work from get() method
I understand that query sets are cacheable and they get evaluated (DB gets hit) when the data set is first iterated on. But what happens with get() method (ex: MyModel.objects.get(id=1)). When does the DB get hit and when do we use a cached result? I am specifically interested in a flow with an API GET request (if that makes a difference). If I have several MyModel.objects.get(id=1 calls within the request lifecycle, will I be hitting the DB every time I call that get() or will I be using cached results ? -
some text always appear to replace my form when I try to upload my file in Django
[<InMemoryUploadedFile: istockphoto-147642455-612x612.jpg (image/jpeg)>, <InMemoryUploadedFile: istockphoto-157120359-612x612.jpg (image/jpeg)>, <InMemoryUploadedFile: istockphoto-160146563-612x612.jpg (image/jpeg)>] This text above appears to replace my file field when I click the upload button, and the form was working perfectly before and now this is happening Before I click the upload button After I click the upload button #model.py class CarImage(models.Model): make = models.ForeignKey(Makes, on_delete=models.CASCADE, related_name='makes') other_images_of_car = models.FileField(upload_to="car_images/", null=True) # views.py class ProductImages(forms.ModelForm): # other_images_of_car = forms.ImageField(widget=forms.ClearableFileInput(attrs={'class': 'form-control tick form-control-user', 'id':'formFile','multiple':True})) class Meta: model = CarImage fields =['other_images_of_car'] widgets = { 'other_images_of_car': forms.FileInput(attrs={'multiple': True}), } @login_required def cars_upload_all(request): if request.method == "POST": product_upload_more_image = request.FILES.getlist("other_images_of_car") product_upload = ProductsUpload(request.POST, request.FILES) product_upload2 =ProductsUpload2(request.POST, request.FILES) other =others(request.POST, request.FILES) if product_upload.is_valid() and product_upload2.is_valid() and other.is_valid(): car = product_upload.save(commit=False) car2 = product_upload2.save(commit=False) other2 = other.save(commit=False) car.owner = request.user car.save() car2.car = car car2.save() other2.others = car other2.save() for i in product_upload_more_image: CarImage.objects.create(make=car, other_images_of_car=i) messages.success(request, "Updated Successfully") return redirect("mobil:add") else: product_upload = ProductsUpload() product_upload_more_image = ProductImages() product_upload2 = ProductsUpload2() other =others() return render(request, "mobil/uploadcar.html", { "product_upload":product_upload, "product_upload_more_image":product_upload_more_image, "product_upload2": product_upload2, "other":other, }) Please help!!!!!!!!!! This stuff have been given me hard times THANKS I have removed all the attr properties I add, in the form class and widget I change from FileField to ImageField too -
How to get first record group by non relational join query, Django?
Model: class AD(model.Model): serial = models.CharField(unique=True, max_length=50) po_number = models.IntegerField(blank=True, null=True) class IDA(model.Model): serial = models.CharField(unique=True, max_length=50) class POR(models.Model): po_number = models.IntegerField(unique=True) is_closed_po = models.BooleanField(default=True) Raw Query: Select MIN(a.serial) as first_value, a.po_number From AD a Join IDA i ON a.serial=i.serial Join POR p ON a.po_number=p.po_number Where p.is_closed_po=0 Group By a.po_number What I'm trying to do in Django: AD.objects.extra( select={'is_closed_po': 'por.is_closed_po'}, tables=['por', 'ida'], where=['ad.po_number = por.po_number', 'ad.serial = ida.serial', 'is_closed_po = 0' ], ).values('serial', 'po_number') How can I achieve this in Django? Any help would be much appreciated. -
CS50 Web Project 2: How to save the starting bid
I am working on Project 2 for CS50 Web Programming course (an eBay-like e-commerce auction site in Django) and I would like to save the starting bid of an auction in order that compare it with later auctions. Please see my code below: models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Category(models.Model): categoryName = models.CharField(max_length=20) def __str__(self): return self.categoryName class Bid(models.Model): bid = models.IntegerField(default=0) # Bid for the listing # User who made the bid user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="userBid") class Listing(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=100) imageUrl = models.CharField(max_length=500) isActive = models.BooleanField(default=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True, related_name="category") price = models.ForeignKey(Bid, on_delete=models.CASCADE, blank=True, null=True, related_name="bidPrice") watchlist = models.ManyToManyField(User, blank=True, null=True, related_name="listingWatchlist") def __str__(self): return self.title class Comments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="userComment") listing = models.ForeignKey(Listing, on_delete=models.CASCADE, blank=True, null=True, related_name="listingComment") comment = models.CharField(max_length=200) def __str__(self): return f"{self.author} comment on {self.listing}" Function for adding a bid (into views.py) def addNewBid(request, id): currentUser = request.user listingData = Listing.objects.get(pk=id) isListWatchList = request.user in listingData.watchlist.all() allComments = Comments.objects.filter(listing=listingData) newBid = request.POST['newBid'] isOwner = request.user.username == listingData.owner.username # The bid must be at least as large as … -
How to load manifest.json in django from react build folder? manifest.json not found error
Im developing a website using react bundled inside django servic static files. Everything appears to be working but my react is not working properly due to django not finding the manifest.json files. I have tried a few solutions that i found here in StackOverflow: mainly adding: path('manifest.json', TemplateView.as_view(template_name='manifest.json', content_type='application/json'), name='manifest.json') to my Django urls.py file and that worked to an extent, but then the error i get changes to: http://localhost:8000/logo192.png 404 (Not Found) Error while trying to use the following icon from the Manifest: http://localhost:8000/logo192.png (Download error or resource isn't a valid image) I also noticed that the react favicon was not loading so I found a fix here for that by using: <link rel="icon" href="http://localhost:8000/media/favicon.ico" /> instead of <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> Where the media folder is the folder im serving my urls.py file in django as my media root. That got the favicon working but the logo192.png not found error still persists, but when I tried the same method for the png file i get the same error. How do I fix it? -
Django Value Error: Cannot Assign Queryset must be instance, ManyToMany Relationship
I have built a model,OpeningDays, to manage a ManyToMany relationship (opening_days field in my BookingManagement model), since I wanted to add some additional data to each instance. I am using the 'through' approach as you can see from my models.py. Within my form, I have a CheckboxSelectMultiple, and for each day which is checked I want to create a model instance. However, I am getting the following error message: ValueError at /listings/createlisting/openingdays/b8s43t Cannot assign "<QuerySet [<DaysOfWeek: Monday>, <DaysOfWeek: Tuesday>, <DaysOfWeek: Wednesday>]>": "OpeningDays.daysofweek" must be a "DaysOfWeek" instance. The exception is being raise on this line of my code: if form.is_valid(): In order to try and solve this I have attempted to iterate through the queryset in my view with a for loop. However this hasn't worked either and I get the same error message. Any ideas how I can fix this? My models.py: class DaysOfWeek(models.Model): day = models.CharField(max_length=13) def __str__(self): return str(self.day) class BookingManagement(models.Model): listing = models.ForeignKey(Listing, verbose_name="Listing", on_delete=models.CASCADE) opening_days = models.ManyToManyField(DaysOfWeek, verbose_name="Opening Days", through="OpeningDays") booking_slots_per_day = models.IntegerField(verbose_name="Available booking slots per day", blank=True) max_bookings_per_time_slot = models.PositiveIntegerField(verbose_name="Maximum bookings per time slot", blank=False) standard_booking_duration = models.PositiveIntegerField(verbose_name="Standard booking duration in minutes", blank=False) min_booking_duration = models.PositiveIntegerField(verbose_name="Minimum booking duration in minutes", blank=True) max_booking_duration = models.PositiveIntegerField(verbose_name="Maximum … -
Django: Traceback error when running project
i keep this traceback even tho i have no modules called 'sitee' in my project, i double-checked, i don't even have a word that starts with 'sit' anyway. but i don't have any model named sitee My professor and I already tried lot of methods, such us reinstalling django, python and so on, i remember that i made another project called 'sitee' but it was on a different folder , in a different directory,already deleted it!!! i don't understand why it keeps showing it PS D:\djangoo\ECOMMERCE\backend> python manage.py runserver >> Traceback (most recent call last): File "D:\python\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "D:\python\Lib\site-packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "D:\python\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\django\core\management\commands\runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "D:\python\Lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in … -
Role Based Access using groups in django and drf
I have 2 models named Menu-Items and Category. class Category(models.Model): slug = models.SlugField() title = models.CharField(max_length= 255, db_index=True) class MenuItem(models.Model): title = models.CharField(max_length= 255, db_index=True) price = models.DecimalField(max_digits=6, decimal_places=2, db_index=True) featured = models.BooleanField() category = models.ForeignKey(to=Category, on_delete=models.PROTECT) I have 3 types of users (Managers, Delivery Crew, and Customers). Manager-> Can perform CRUD on Menu-items. Delivery Crew (DC) -> can only view(get and list) menu-items. Customer -> can only view category and menu-items I have done authentication using Djoser. I have created 3 groups of users(managers, dc, and customers) and have added the necessary permissions to the groups. Now how do I ensure that when a manager logs in he is able to perform the actions that he is allowed to and the same for Dc and customers? Here's what I did. I created 2 permissions isManager, and isDC. class IsManager(BasePermission): def has_permission(self, request, view): return request.user.groups.filter(name= "Manager").exists() class IsDeliveryCrew(BasePermission): def has_permission(self, request, view): return request.user.groups.filter(name= "Delivery Crew").exists() and in my views class MenuItemManagerView(ModelViewSet): queryset = MenuItem.objects.all() serializer_class = MenuItemSerilaizer permission_classes = [IsAuthenticated, IsManager] class MenuItemDeliveryCrewView(ListAPIView, RetrieveAPIView): queryset = MenuItem.objects.all() serializer_class = MenuItemSerilaizer permission_classes = [IsAuthenticated, IsDeliveryCrew] Now, it is doing the basic task of checking if the logged-in user is … -
Django: Paypal webhook event on re-subscription
I have implemented a Paypal webhook in Django. I have difficulty keeping track of resubscription on Paypal. I am trying to use the "PAYMENT.SALE.COMPLETED" event and I have seen other questions which suggest using the same event but the next billing date (next_billing_date) in my database does not change. Please see the code below, can you tell me what I am doing wrong or do I need to use some other event. def paypal_webhooks(request): try: if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META: return Response(status=400) auth_algo = request.META['HTTP_PAYPAL_AUTH_ALGO'] cert_url = request.META['HTTP_PAYPAL_CERT_URL'] transmission_id = request.META['HTTP_PAYPAL_TRANSMISSION_ID'] transmission_sig = request.META['HTTP_PAYPAL_TRANSMISSION_SIG'] transmission_time = request.META['HTTP_PAYPAL_TRANSMISSION_TIME'] event_body = request.body.decode(request.encoding or "utf-8") valid = notifications.WebhookEvent.verify( transmission_id=transmission_id, timestamp=transmission_time, webhook_id=webhook_id, event_body=event_body, cert_url=cert_url, actual_sig=transmission_sig, auth_algo=auth_algo, ) if not valid: return Response(status=400) webhook_event = json.loads(event_body) event_type = webhook_event["event_type"] # payment completed if event_type == "PAYMENT.SALE.COMPLETED": subscription_id = webhook_event['resource']['id'] subscription = Subscriptions.objects.filter(subscriptionID=subscription_id).last() if subscription: subscription.active = True subscription.active_billing = True subscription.next_billing_date = webhook_event['resource']['billing_info']['next_billing_time'][:10] subscription.save() # subscription cancelled if event_type == "BILLING.SUBSCRIPTION.CANCELLED": subscription_id = webhook_event['resource']['id'] subscription = Subscriptions.objects.filter(subscriptionID=subscription_id).last() if subscription: subscription.active_billing = False subscription.save() # subscription failed if event_type == "BILLING.SUBSCRIPTION.PAYMENT.FAILED": subscription_id = webhook_event['resource']['id'] subscription = Subscriptions.objects.filter(subscriptionID=subscription_id).last() if subscription: subscription.active = False subscription.active_billing = False subscription.save() PaymentMethods.resub_free(subscription.user) return Response({"success": True}, status=200) except Exception as e: return … -
Is it standard to set is_authenticated to True in Django?
I'm fairly new to Django and I use Django 4.2. I am making a website and I've been stuck in the logout logic. I'm confused as to whether I should have set the is_authenticated field to True by default in the models.py file. I've googled a lot but I run don't understand how to really authenticate users in login and logout. Can anyone help me understand the logic? Where do I use login decorators and how do I set the field is_authenticated to true during login and false during logout -
django-dotenv not working in Django version> 4.0
When i try to import django-dotenv module it's throwing error like "No Module Named 'dotenv'". even after installing the module using pip install django-dotenv in my virtual environment (OS: Win10). enter image description here I go through some of the documentation where they mention this error will occurs when you are using both 'python-dotenv' & 'django-dotenv'. but in my case i have only installed 'django-dotenv' package. Please let me know for how to get rid of this issue. Thanks! -
time data '2023-04-15T16:22:03.721461+05:00' does not match format "%Y-%m-%dT%H:%M:%S.%f+%Z'"
I get my data from drf as json and ther my datetime looks like: `'2023-04-15T16:22:03.721461+05:00'` but i want show datetime in template like: `'15-04-2023 16:22'` so i use tamplatetag: # app/templatetags/event_extras.py @register.filter(expects_localtime=True) def parse_iso(value): return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f+%Z'") and html like: {% load event_extras %} <th>{{r.datetime|parse_iso}|date:'d/m/Y H:M'}</th> but got this error: time data '2023-04-15T16:22:03.721461+05:00' does not match format "%Y-%m-%dT%H:%M:%S.%f+%Z'" -
Fetching API from django rest framework for functionality
I have probably jumped the gun by doing this with my current knowledge, but I have built a an API on the back end of my app with django rest frame work. I have built all the front end templates etc, the only thing I am missing is fetching the API for functionality. I am looking for some one to point me in the right direction as to what i do next, for example how to make my cart functional on the font end. My current code for my Cart: API VIEWS: class CartViewSet(CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet): queryset = Cart.objects.prefetch_related('items__product').all() serializer_class = CartSerializer class CartItemViewSet(ModelViewSet): http_method_names = ['get', 'post', 'patch', 'delete'] def get_serializer_class(self): if self.request.method == 'POST': return AddCartItemSerializer elif self.request.method == 'PATCH': return UpdateCartItemSerializer return CartItemSerializer def get_serializer_context(self): return {'cart_id': self.kwargs['cart_pk']} def get_queryset(self): return CartItem.objects \ .filter(cart_id=self.kwargs['cart_pk']) \ .select_related('product') SERIALIZERS class CartItemSerializer(serializers.ModelSerializer): product = SimpleProductSerializer() total_price = serializers.SerializerMethodField() def get_total_price(self, cart_item:CartItem): return cart_item.quantity * cart_item.product.price class Meta: model = CartItem fields = ['id', 'product', 'quantity', 'total_price'] class CartSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) items = CartItemSerializer(many=True, read_only=True) total_price = serializers.SerializerMethodField() def get_total_price(self, cart): return sum([item.quantity * item.product.price for item in cart.items.all()]) class Meta: model = Cart fields = ['id', 'items', 'total_price'] … -
How to make htmx colour animations work with Django?
I have a simple Django project. I'm trying to get this example HTMX colour changing element working. https://htmx.org/examples/animations/ I have copied and pasted the exact code they use into my Django index.html file: <style> .smooth { transition: all 1s ease-in; } </style> <div id="color-demo" class="smooth" style="color:red" hx-get="/colors" hx-swap="outerHTML" hx-trigger="every 1s"> Color Swap Demo </div> <script> var colors = ['blue', 'green', 'orange', 'red']; onGet("/colors", function () { var color = colors.shift(); colors.push(color); return '<div id="color-demo" hx-get="/colors" hx-swap="outerHTML" class="smooth" hx-trigger="every 1s" style="color:' + color + '">\n'+ ' Color Swap Demo\n'+ '</div>\n' }); </script>``` This prints out the following: https://i.stack.imgur.com/VOJny.png But unlike what is shown in the demo, it doesn't change colours every 1 second. My command line for the Django server keeps throwing this error every 1 second: https://i.stack.imgur.com/TrZoo.png Why is this happening and how can I fix this? -
How can I display photos stored on Amazon S3 with Subquery code of Django?
I deployed a Web App made by Django to AWS and stored media files to Amazon S3. But when I use Subquery code I wrote below, I can not get the media files and correct urls of Amazon S3. What should I change my code? user = get_object_or_404(MyUser, pk=5) subqs = ItemPhoto.objects.filter(item=OuterRef('item')).filter(priority=1) queryset = Order.objects.prefetch_related( Prefetch( 'orderdetail_orderid', queryset=OrderDetail.objects.select_related('order', 'item').annotate( item_photos=Subquery(subqs.values('photo')), ), to_attr='oor', ), ).filter(user=user).order_by('-created_at') photos1 = [item.item_photos for order in queryset for item in order.oor] #[sh/Gold Ship/76e91e2d048147c9939d099224e09554.jpg, sh/Epiphaneia/9476dcb430754049b16c62949ecd3839.jpg] photos2 = [item.item_photos.photo for order in queryset for item in order.oor] # Traceback (most recent call last): # File "<console>", line 1, in <module> # File "<console>", line 1, in <listcomp> # AttributeError: 'str' object has no attribute 'photo' item_photos = ItemPhoto.objects.all() photos3 = [p.photo for p in item_photos] #[<ImageFieldFile: sh/Gold Ship/76e91e2d048147c9939d099224e09554.jpg>, <ImageFieldFile: sh/Epiphaneia/9476dcb430754049b16c62949ecd3839.jpg>] photos4 = [p.photo for p in item_photos] # templates can display photos with these urls #['https://xxxxx.s3.xxxxx.amazonaws.com/media/sh/Gold%20Ship/76e91e2d048147c9939d099224e09554.jpg, 'https://xxxxx.s3.xxxxx.amazonaws.com/media/sh/Epiphaneia/9476dcb430754049b16c62949ecd3839.jpg'] models.py def get_itemimage_path(instance, filename): prefix = 'sh{}{}{}'.format(os.sep, instance.item, os.sep) name = str(uuid.uuid4()).replace('-', '') extension = filename.split('.')[-1] return '{}{}.{}'.format(prefix, name, extension) class ItemPhoto(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="item_photo", verbose_name="item_id",) photo = models.ImageField("item_photo", blank=True, upload_to=get_itemimage_path) priority = models.IntegerField("priority",) template.html <img src="{{ item.item_photos }}"> # src="sh/Gold Ship/76e91e2d048147c9939d099224e09554.jpg" <- I can not get photo with … -
showing identation fault even though it is idented
def gen_frames(): cap = cv2.VideoCapture(0) while True: success, frame = cap.read() if not success: break ret, buffer = cv2.imencode('.jpg', frame) frame = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') if request.method == 'POST': msg = request.POST.get('msg') if msg: save_path = os.path.join(save_folder, "captured_image.jpg") cv2.imwrite(save_path, frame) print(request.headers) return render(request,"account/captured.html",{}) cap.release() It keeps on saying TabError: inconsistent use of tabs and spaces in indentation The identation fault is at if request.method == 'POST': -
Any way to optimize my file and folder pattern
I am writing app, where i have folders and files component. I think the way it works is slow. I have 2 models: BookmarkFolder and Bookmark, they're connected through ForeignKey so each folder could have multiple bookmarks. In my template I've listed folders and I can open each by clicking on "Extend" button, it renders all files under it (I use htmx). list of folders. The problem is every time I open folder it makes query to database and it seems slow to me. How can I optimize it to work faster or maybe there's better ways to implement this folder and files pattern without using JS framework? -
In Django Template: display the sum of calculated variables
right now I wonder if there is a way to show up the sum of variables in a Django-Template. What I mean is, if i have variables of the same kind, is there a template-sided function to add them? I know, that the "logic" should be normally outside a template, so i wrote a function that does the calculation i want to see in the template: def mission_duration(self): duration = self.end - self.begin return duration.days and use it in template by {{ mission.mission_duration }} and it works fine. But if i have several of these variables in a template, is there an easy way to sum their values up and show the result? Right now, the variables are displayed by querying the database going through a for-loop. The result is likely to be displayed outside of the loop elswhere in the template... or on the other side: how can i put this on model/view.py to solve the problem outside the template? missions are in an oneToMany relationship table to "employees"...and normally data of employees are displayed. so for a model/view solution i have no idea at the moment, how to cycle to alle mission entries of an employee to build …