Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django filter - filter a property of a model through a range of values
I have this model class Person(models.Model): name = models.CharField(max_length=150) date_birth = models.DateField() and this property to calculate years and months of birth @property def eta_annimesi(self): date2 = datetime.combine(self.date_birth , datetime.min.time()) now = datetime.now() duration = (now.year - date2.year) * 12 + now.month - date2.month years = duration // 12 months = duration % 12 if years > 0: if months > 0: msg_anni = years.__str__() + ' anni ' +months.__str__() +' mesi' else: msg_anni = years.__str__() + ' anni' else: if months > 0: msg_anni = months.__str__() +' mesi' else: msg_anni = 'Appena nato' return msg_anni I need to create filters on an html page that allow me to create a range between two integer values. (e.g. from 0 to 2 years) If it were possible even months but it's not important. I managed it by giving the possibility to enter the range of two dates but that's not what I need. Ideas and suggestions? Thanks in advance to anyone who wants to give me a hand. I need to create filters on an html page that allow me to create a range between two integer values. (e.g. from 0 to 2 years) If it were possible even months but … -
picking django template variable from rendered template to use in javascript
I am still new to django and struggling with this issue : I have a price slidebar in html that i picked up from a template. In html, the bar looks like this : <div class="price-range ui-slider ui-corner-all ui-slider-horizontal ui-widget ui-widget-content" data-min="33"" <!-- to replace with :{{ price_max.product_price__max }}" --> data-max="15" ></div> <div class="range-slider"> <div class="price-input"> <p>Prix:</p> <input type="text" id="minamount" /> <input type="text" id="maxamount" /> </div> </div> </div> <a href="#">Filter</a> I upload price_max and also price_min correctly from the view as they can be directly displayed on the webpage as text. But the slidebar uses javascript to be rendered and picks up those data-min and data-max values to display the dynamic result like this : enter image description here the javascript: /*------------------- Range Slider --------------------- */ var rangeSlider = $(".price-range"), minamount = $("#minamount"), maxamount = $("#maxamount"), minPrice = rangeSlider.data('min'), maxPrice = rangeSlider.data('max'); rangeSlider.slider({ range: true, min: minPrice, max: maxPrice, values: [minPrice, maxPrice], slide: function (event, ui) { minamount.val( ui.values[0]+'€'); maxamount.val( ui.values[1]+'€'); } }); minamount.val( rangeSlider.slider("values", 0)+'€'); maxamount.val( rangeSlider.slider("values", 1)+'€'); replacing data-min and data-max by django templates variables doesn't work, i'm still unclear exactly why but i suppose it has to do with django rendering order. Another difficulty is that i … -
Trigger function when input field is changed programmatically
I have a slider which changes the value of the input fields named 'workload1' and 'workload2'. Having adjusted the slider, the form 'test-form1' should be submitted. (I do not have any submit button, and all my filtering option work with event listeners) After submitting the form, the page is reloaded, and the slider has to be set to the values the user has manually adjusted. So if someone moves the slider, the page is reloaded and the slider is at the same position as the person has moved it. In order to make this happen, I pass the 'workload_min' and 'workload_max' back to my template 'myfile.html'. Now the question is, how can I trigger the trigger the event listener when the slider is moved? I have tried with dispatchEvent(event), however, since the values are passed back to the template, the dispatchEvent(event) will be triggered again and again, in a endless reloading of the page. I have also tried with simple addEventListener('input', function ()) but the change of the input field, trough movement of the slider is not detected. Does someone know how to handle this problem? html: <input form="test-form1" type="text" name="workload1" id="workload1" readonly="readonly"> <input form="test-form1" type="text" name="workload2" id="workload2" readonly="readonly"> <div … -
How can I set this?
I am new to django. it is very important that django.contrib.staticfiles.finders.AppDirectoriesFinder be there in your STATICFILES_FINDERS. resource:https://django-admin-tools.readthedocs.io/en/latest/quickstart.html#installing-django-admin-tools Where are STATICFILES_FINDERS django.contrib.staticfiles.finders.AppDirectoriesFinder -
Django REST Framework - Weird Parameter Shape due to JSON Parser?
Currently I'm contacting my APIViews through AJAX requests on my frontend. config = { param1: 1, param2: 2, param3: 3 } $.ajax(APIEndpoints.renderConfig.url, { type: APIEndpoints.renderConfig.method, headers: { "X-CSRFToken": csrfToken }, data: { "config": config, "useWorkingConfig": true } } However, when I receive the data in my APIView, I get an object with the following shape: { "config[param1]": 1, "config[param2]": 2, "config[param3]": 3, "useWorkingConfig": true } According to different sources that I have checked, DRF does support nested JSON objects, so what am I missing? Is this something to do with the default behavior of the JSON Parser? It doesn't seem to be very useful, as you would basically need to preprocess the data before using your serializers (since they expect a nested structure). The same happens with lists, with your parameters being received as list_param[] instead of list_param. If its useful for anything, these are my DRF settings REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'EXCEPTION_HANDLER': 'django_project.api.exception_handler.custom_exception_handler', # Camel Case Package Settings 'DEFAULT_RENDERER_CLASSES': ( 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', 'djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer', ), 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'djangorestframework_camel_case.parser.CamelCaseFormParser', 'djangorestframework_camel_case.parser.CamelCaseMultiPartParser', 'djangorestframework_camel_case.parser.CamelCaseJSONParser', ], 'JSON_UNDERSCOREIZE': { 'no_underscore_before_number': True, }, } Its very probable that Im just missing something or its an intended behavior that Im not aware of.