Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Listening for HTMX events with Alpine.js in Django
Django templates can listen for events from HTMX via listeners added to the Javascript part of code. In this case I want to change DOM element(s) after an update on the page. Below works fine: document.body.addEventListener('htmx:afterSwap', (() => { // get input element, clear its value })) I'm using Alpine.js which helps handling dynamic parts on the client side. I want to connect it to HTMX events since it apparently picks up custom events. Unfortunately, when trying to subscribe to any HTMX event, e.g. htmx:after-swap in <form x-on:htmx:after-swap="console.log('event received')" hx-post="{% url 'my_url' %}" hx-target="#responses" > I have no output in the console. Do I need to first trigger Alpine's 'custom event' from plain Javascript (e.g. in the working addEventListener block above) or can I connect HTMX with Alpine.js directly? I have tried: various cases combinations (I gather kebab is the way for Alpine.js); tried various HTMX events such as htmx:load; replaced x-on with @; found HTMX+Alpine.js examples elsewhere (for instance involving x-data prefix) but none of them worked for me. I would like to understand the process, thank you. -
Sample and hold using Pandas
I have a Pandas dataframe that looks like this ID Time Value 0 1 10 1.0 1 2 10 2.0 2 1 20 NaN 3 3 20 4.0 4 1 30 NaN 5 2 30 NaN 6 4 30 NaN I want to do sample and hold for each ID, using the last known non-null value to impute some of the nulls based on the parameter max_time. For every row where Value is null and time is t, if there is a row with the same ID with time t_other such than t-max_time <= t_other <= t, then I want to replace the Value of my row with the Value of the row with the max t_other that satisfies this constraint. For example, in the table shown above, if max_time=10, then for ID = 1 at Time = 20 we have a null Value which can be filled by the value at Time = 10. So the result would become ID Time Value 0 1 10 1.0 1 2 10 2.0 2 1 20 1.0 3 3 20 4.0 4 1 30 NaN 5 2 30 NaN 6 4 30 NaN The other nulls don't have a value in the … -
opencv error conv_winograd_f63.cpp ubuntu 22 python3.10 cv2 although works on 2nd machine
I have a development machine working with ubuntu 22, python 3.10 and cv2; when I try to replicate on another machine then I get runtime error: from section calling age prediciton from haarclassifier and age_net.caffemodel: line 118 return age_net-forward() cv2.error: OpenCV(4.7.0-dev) (note this after building files from source orcv2 4.7.0 or 4.6.0 same result) /home/art/opencv_build/opencv/modules/dnn/src/layers/cpu_kernels/conv_winograd_f63.cpp:401: error: (-215:Assertion failed) CONV_WINO_IBLOCK == 3 && CONV_WINO_ATOM_F32 == 4 in function 'winofunc_BtXB_8x8_f32' I have tried various permutations of installing opencv-python or opencv-contrib-python or building and compiling the opencv files from source, always with the same result. Works on the original machine but always throws this error on the second machine when running the same python code. I have searched online generally and in stackoverflow and I don't see anyone noting this error. Anyone know? Tried to duplicate machine where it is working and various permuations of installing opencv either directly: pip3 install opencv-python or pip3 install opencv-contrib-python or build the opencv files from source, which is generally to build the dependencies: sudo apt install build-essential cmake git pkg-config libgtk-3-dev \ libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \ libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \ gfortran openexr libatlas-base-dev python3-dev python3-numpy \ libtbb2 libtbb-dev libdc1394-dev clone the repositories: $ … -
Sort Columns by assigned column
I have a following code: import bs4 as bs import requests import yfinance as yf import datetime import pandas as pd import time starttimer = time.time() resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies') soup = bs.BeautifulSoup(resp.text, 'lxml') table = soup.find('table', {'class': 'wikitable sortable'}) tickers = [] for row in table.findAll('tr')[1:]: ticker = row.findAll('td')[0].text tickers.append(ticker) tickers = [s.replace('\n', '') for s in tickers] start = datetime.datetime(2020, 1, 1) end = datetime.datetime(2022, 1, 1) data = yf.download("GOOGL", start=start, end=end) print(data) eodPrices = pd.DataFrame(data=data); percentageChange = round(eodPrices.pct_change()*100,2).shift(-1) percentageChange.sort_values(by=['Close'],inplace=True) dataframe = pd.DataFrame(percentageChange,columns = ['Close']) print(dataframe) The code gets data for required ticker/s from yfinance module, then sort (Ascending) them. I receive following response: I have several issues with this response: I don't see a ticker in the response and when I try to download more tickers I receive following error: ValueError: The column label 'Close' is not unique. For a multi-index, the label must be a tuple with elements corresponding to each level. I don't know how to fix this. My desired response should be as following: Current date formatting: I'd like to have just a date e.g. "2020-03-13". It seems to be hardcoded and I can't change it, is there a way how to do it? Thank … -
QSlider value change interrupts audio playback of QMediaPlayer [closed]
I am having difficulties using PySide6 to control the playback of music. I have implemented a slider to allow the user to control the progress of the music, but I am having issues: when the slider is used, the music stops and does not resume. How can I ensure that the slider works properly with the music playback in PySide6? https://drive.google.com/file/d/10f0RBy4jzDH1eyd5Zb52CfZyWEhm9x4b/view?usp=share_link pause the music while moving, then when I release the slider it resumes the music. I searched for codes like this on the internet but none working well either import sys from PySide6.QtCore import Qt, QUrl from PySide6.QtGui import QPalette from PySide6.QtWidgets import QApplication, QMainWindow, QSlider, QPushButton, QHBoxLayout from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput import time class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setGeometry(200, 200, 300, 200) self.player = QMediaPlayer() self.audio = QAudioOutput() self.player.setAudioOutput(self.audio) self.player.setSource(QUrl.fromLocalFile('./muzgas/505.mp3')) self.button = QPushButton("play", self) self.button.setGeometry(50, 100, 100, 30) self.slider = QSlider(Qt.Horizontal, self) self.slider.setGeometry(50, 50, 200, 20) self.slider.sliderMoved.connect(self.jump_to_time) self.button.clicked.connect(self.play) def play(self): time.sleep(0.5) self.player.play() self.audio.setVolume(0.01) self.slider.setRange(0, self.player.duration() // 1000) def jump_to_time(self, position): print(position) self.player.setPosition(position * 1000) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec()) -
Pycharm can't recognize apps that added using manage.py startapp django
when I add app to my django project by using 'python manage.py startapp [app_name]' and add app_name to my INSTALLED_APPS in django settings pycharm can't recognized imports from that apps (when I run my server, it runs without error). What should I do? I upload some images below for more detials my working directory is like this: -ToDoApp-DRF-CBV[PyCharm Working Directory] --core ----core ----manage.py ----accounts ----blog --gitignore --... when I change my working directory to 'core' it can find modules (which is normal) but I can't do that because I have VCS in my current working directory and other code editors like VSCode find my apps for imports and only PyCharm can't recognized them. -
I there any way to use PySocks in multithread? RuntimeError: can't register atexit after shutdown
I am trying to use telethon library with porxy(for proxy using PySocks) but getting error RuntimeError: can't register atexit after shutdown. Without proxy everything works well. Here is my code: import asyncio import subprocess from threading import Thread, Event from telethon import TelegramClient, events, sync from telethon.tl.functions.users import GetFullUserRequest from telethon.tl.functions.messages import CheckChatInviteRequest from telethon.tl.functions.channels import GetFullChannelRequest from telethon.tl.functions.account import UpdateUsernameRequest from telethon.tl.functions.photos import UploadProfilePhotoRequest from telethon.tl.functions.account import UpdateProfileRequest from opentele.td import TDesktop from opentele.api import API, UseCurrentSession, CreateNewSession import socks #import python_socks numbers = ["380666666666", "380666666667"] my_proxy = { 'proxy_type': socks.HTTP, 'addr': 'someproxyip', 'port': 12321, 'username': 'someusername', 'password': 'somepassword' } def main(thread_cntr): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) print(f"Inside {thread_cntr}") number = numbers[thread_cntr] print(f"inside {thread_cntr}") api = API.TelegramIOS.Generate() print("gen") client = TelegramClient(f"{number}", api=api, loop=loop, proxy=my_proxy) print("client") client.connect() if not client.is_user_authorized(): print("No auth") code_request = client.send_code_request(phone=number, force_sms = True) print(code_request) client.sign_up(phone=number, code=input("Code: ")) client.start() me = client.get_me() print(me.username) return True threads = [] thread_cntr = 0 for num in numbers: threads.append(Thread(target=main, args=(thread_cntr, ))) thread_cntr += 1 print(threads) for thread in threads: print("\nStarting thread") thread.start() print("Thread started") I also tied python-socks[asyncio] instead of PySocks but get same error. If join all threads with thread.join() everything also works but in single thread which is … -
Django Reverse for not found. 'account_profile' is not a valid view function or pattern name
Учу Django. Я работаю над своим проектом для курса, и сейчас я полностью застрял. Трудно что-то мне даются эти urls. Прошу помощи. Проблема с urls. Подскажите где я не правильно сделал. Вот такая ошибка: Reverse for 'account_profile' not found. 'account_profile' is not a valid view function or pattern name. urls.py from django.urls import path, include from .views import AccountProfile, UpdateProfile, auth_code urlpatterns = [ path('profile', AccountProfile.as_view(), name='account_profile'), path('edit', UpdateProfile.as_view(), name='account_edit'), path('auth_code', auth_code, name='auth_code'), path('', include('allauth.urls')), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'news', 'protect', 'django_filters', 'django.contrib.flatpages', 'django_apscheduler', 'board', 'accounts', 'bootstrap4', 'ckeditor', 'ckeditor_uploader', ] NoReverseMatch at /index Reverse for 'account_profile' not found. 'account_profile' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/index Django Version: 4.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'account_profile' not found. 'account_profile' is not a valid view function or pattern name. Exception Location: E:\D6\venv\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: board.views.Index Python Executable: E:\D6\venv\Scripts\python.exe Python Version: 3.9.13 Python Path: ['E:\\D6', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\python39.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\marsh\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'E:\\D6\\venv', 'E:\\D6\\venv\\lib\\site-packages'] Server time: Sun, 19 Mar 2023 20:34:10 +0000 Error during template rendering In template E:\D6\templates\default.html, error at line 30 Reverse … -
NoReverseMatch at Reverse for '{}' with arguments '('',)'.: ['(?P<id>[0-9]+)/\\Z']
NoReverseMatch at /Bookstore/book_detail/7/ Reverse for 'edit_book' with arguments '('',)' not found. 1 pattern(s) tried: ['Bookstore/edit_book/(?P[0-9]+)/\Z'] url.py path('edit_book/int:id/', views.edit_book, name = 'edit_book'), # delet book url path('delete_book/<int:id>', views.delete_book, name = 'delete_book') View.py def edit_book(request, id): book = Book.objects.get(id =id) form = EditBookForm(instance = book) if request.method == 'POST': form = EditBookForm(request.POST, request.FILES, instance = book) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'update_book.html', context) for deleting the book, takes id as an argument def delete_book(request, id): # getting the book to be deleted book = Book.objects.get(id=id) # checking if the method is POST if request.method == 'POST': # delete the book book.delete() # return to home after a success delete return redirect('home') context = {'book': book} return render(request, 'delete_book.html', context) The template file is here template html Error show in these line of code Edit Delete any one help in finding the solution it face noreverse error in the question -
calling a url with reverse with query string during unit testing
I have this URL that i want to test: urlpatterns = [ path('produce<str:code>', ProduceSpreadSheet.as_view(), name="produce" ), ] my test is: class ProduceSpreadSheetTest(TestCase): def setUp(self): self.code = "abcd" def test_valid_token(self): url = reverse('produce', query_kwargs={'code': self.code}) response = client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) I get the error: TypeError: reverse() got an unexpected keyword argument 'query_kwargs' when I change query_kwargs to kwargs: I get the error: TypeError: get() got an unexpected keyword argument 'code' The method to be tested is: class ProduceSpreadSheet(APIView): def get(self, request): code = request.query_params.get('code',None) // continue I want to call it with .../produce?code=abcd query_kwargs and kwargs and reverse('produce') + 'code=code' -
TypeError: load() missing 1 required positional argument: 'f'
I am using MacPro M1 Pro chip Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU. How to solve this issue/ What change is to be made to help me to execute the following command: python pc_certification.py --model resnetv2_50x1_bit_distilled_cutout2_128 --dataset imagenette --num_img -1 --num_mask 6 --patch_size 32 import torch import torch.backends.cudnn as cudnn import numpy as np import os import argparse import time from tqdm import tqdm import joblib from utils.setup import get_model,get_data_loader from utils.defense import gen_mask_set,double_masking_precomputed,certify_precomputed parser = argparse.ArgumentParser() parser.add_argument("--model_dir",default='checkpoints',type=str,help="directory of checkpoints") parser.add_argument('--data_dir', default='data', type=str,help="directory of data") parser.add_argument('--dataset', default='imagenette',type=str,choices=('imagenette','imagenet','cifar','cifar100','svhn','flower102'),help="dataset") parser.add_argument("--model",default='vit_base_patch16_224',type=str,help="model name") parser.add_argument("--num_img",default=-1,type=int,help="number of randomly selected images for this experiment (-1: using the all images)") parser.add_argument("--mask_stride",default=-1,type=int,help="mask stride s (square patch; conflict with num_mask)") parser.add_argument("--num_mask",default=-1,type=int,help="number of mask in one dimension (square patch; conflict with mask_stride)") parser.add_argument("--patch_size",default=32,type=int,help="size of the adversarial patch (square patch)") parser.add_argument("--pa",default=-1,type=int,help="size of the adversarial patch (first axis; for rectangle patch)") parser.add_argument("--pb",default=-1,type=int,help="size of the adversarial patch (second axis; for rectangle patch)") parser.add_argument("--dump_dir",default='dump',type=str,help='directory to dump two-mask predictions') parser.add_argument("--override",action='store_true',help='override dumped file') args = parser.parse_args() DATASET = args.dataset MODEL_DIR = os.path.join('.',args.model_dir) DATA_DIR = os.path.join(args.data_dir,DATASET) DUMP_DIR = os.path.join('.',args.dump_dir) if not os.path.exists(DUMP_DIR): … -
Why Python multiprocessing Pool context manager __exit__ does not close and join
Python's multiprocessing Pool context manager exit calls .terminate(), but a very common pattern that does not use context manager is p = Pool() p.map(do) p.close() p.join() I know that map blocks, and therefore when done in a context manager, there isn't a need to call .close() and .join() (or is it actually better to call them?): with Pool() as p: p.map(do) I also know that .close() and .join() are useful for non-blocking usages e.g. apply_async. If there are some other important reasons to call .close() then .join(), why isn't it in the exit call of Pool context manager? If there are no other benefits, shouldn't we do the following instead: p = Pool() p.map(do) p.terminate() -
AsyncIO for loop conversion
I am new with AsyncIO. I want some help converting the below scenario. I have a set of json files, these will be read and pass it to the post request. This operation does sequentially N number of times I want to covert the below to use parallelism using AsyncIO to do the operation asynchronously. def test(n): num = 0 for names in os.list(dir): filename = os.path.join(.,b=name) while num> n: request.post(url, filename) num = +1 This code runs for all json files sequentially. Can some one help me write the code in asynchronous way that one thread will be running one with 1st json file and if there is any ideal cpu it should run with 2nd json and go on I am new to this. Can anyone help me with this code approach. Thank you -
Playsound module is not running in vs code
how to fix the Error 259 in vs code i tried each and evry way possible to run this code but still not able to run this code. -
Tensorflow sampled_softmax_loss inside model.fit() loss function
I am trying to create a custom word2vec model. To speed up the training process, negative sampling is usually used. There is the function tf.nn.sampled_softmax_loss for this purpose, it requires inputs as a parameter, which apparently is the output of the layer before the softmax layer. This question addresses this, however it doesn't seem possible to use tf.nn.sampled_softmax_loss in a custom loss function, since you only have y_true and y_pred and not the input or output from hidden layers. Is there a way to still get inputs from the context of a custom loss function? This is a snippet from my code (currently not working because of the wrong inputs argument): def sampledLoss(y_true, y_pred): outputWeights, outputBias = self.model.layers[2].weights print(tf.transpose(outputWeights).shape, outputBias.shape, tf.reshape(tf.argmax(y_true, 1), (-1, 1)).shape, y_pred.shape) return tf.nn.sampled_softmax_loss(tf.transpose(outputWeights), outputBias, tf.reshape(tf.argmax(y_true, 1), (-1, 1)), y_pred, 5, vocabulary.vocabSize, num_true = 1) self.model.compile(optimizer="adam", loss=sampledLoss) self.model.fit(trainGen, epochs=epochsAmount) -
Axios network error with vue.js when calling API endpoint
I'm making an API call using axios to my backend server in Django from my Vue.js web app. However, I'm getting the following error on Chrome. (https://i.stack.imgur.com/uq8OG.png) (https://i.stack.imgur.com/nOFNk.png) I suspect it may be a CORS error, but I'm not sure how to deal with this properly on Vue. My code looks like this: async RecentListingsList() { await axios .get("/api/v1/recent-listings/") .then(response => { this.recentListings = response.data }) .catch(error => { console.log(error) }) } I tried using a proxy in package.json and vue.config.js, but this didn't have any effect. I also tried changing the CORS_ALLOWED_ORIGINS setting in settings.py in my Django app. Not sure what else to do. -
Django Modelform DecimalField drop trailing 0s for display, up to 2 decimal places
I have a Modelform that contains multiple DecimalFields with decimal_places=4. I need 4 decimal places as that is a reflection of the underlying data. This is a financial utility where mean values might consume all 4 decimal places. Users should be allowed to enter up to 4 decimal places, and forms should be displayed with up to 4 decimal places. I am not looking for any sort of rounding or truncation. What I want to do is limit the display of trailing 0s in modelforms being rendered in my template, up to a minimum of 2 trailing 0s, as these are dollars. For instance: 3.1234 would still remain as 3.1234 3.1230 would become 3.123 3.1200 would become 3.12 3.1000 would become 3.10 3.0000 would become 3.00 I have came up with the following inside my modelforms init method: def __init__(self, *args, **kwargs): if self.initial: for field_name, field in self.fields.items(): if isinstance(field, forms.DecimalField) and field.decimal_places == 4 and self.initial.get(field_name): self.initial[field_name] = self.initial[field_name].normalize() Using the .normalize() drops ALL the trailing 0s (3.0000 -> 3), however, I want a minimum of 2. I thought of using .quantize(), to enforce a minimum of 2 decimal places, but this rounds values with more then 2 … -
unable to get video feed from camera using opencv in django web app
I have created a django web app and written code to get video feed from my laptop camera using opencv. def start(request): print("HI") def testDevice(source): cap = cv2.VideoCapture(source) if cap is None or not cap.isOpened(): print('Warning: unable to open video source: ', source) testDevice(0) # no printout testDevice(1) # prints message global video_thread if video_thread is None or not video_thread.is_alive(): stop_event.clear() video_thread = threading.Thread(target=run_video_feed) video_thread.start() return HttpResponse("Video feed started successfully.") else: return HttpResponse("Video feed is already running.") The above code is fetching video feed while running in localhost. But when I uploaded(hosted) it in the pythonanywhere, it is not fetching the video feed and it prints Warning: unable to open video source. -
Django user permission assigning group
I have a to do list model that admin user can create,edit,and delete to do items. In the model, the team field is a dropdown list where admin can choose a team, which refers to the group containing users. How can I show items created only to the users that belongs to the team that the admin user chose? Now each user can view tasks they created/edited but I'm not sure how to let admin user to assign group(team) to allow all users in group to view the task list. models.py from django.db import models from django.contrib.auth.models import User TEAM_CHOICES = ( (' ', ' '), ('team a','TEAM A'), ('team b', 'TEAM B'), ) class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) suggestion = models.TextField(null=True, blank=True) reply = models.TextField(null=True, blank=True) team = models.CharField(max_length=200,choices=TEAM_CHOICES, default=' ') complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: order_with_respect_to = 'user' views.py class CustomLoginView(LoginView): template_name = 'item/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('tasks') class RegisterPage(FormView): template_name = 'item/register.html' form_class = UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('tasks') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) … -
Where to save this class?
Updated models.Model: class GetOrNoneManager(models.Manager): """returns none if object doesn't exist else model instance""" def get_or_none(self, **kwargs): try: return self.get(**kwargs) except ObjectDoesNotExist as e: logger.warning(e) return None class BaseModel(models.Model): class Meta: abstract = True ordering = ('-created_at',) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField('Дата создания', auto_now_add=True, db_index=True) updated_at = models.DateTimeField('Дата изменения', auto_now=True) objects = GetOrNoneManager() def str(self): return self.id.hex fffffffffffffffffffffffffffffffffffffff Is there any certain file that i should create to save code like that? -
Django using rest_framework url_pattern not mapping to model instance view
I have a Django (python) application that uses rest_framework api. I want the api to map to /api/v1/[/id]. The GET /api/v1/whs gives a page that lists the Wh objects in the database (which is MongoDB/Djongo/pymongo). Problem: GET /api/v1/whs/640444031170f24828f324bc/ does not call the def get_object(self) function (evidences by the fact the print statement never runs). The Wh document with that ObjectId exists in the MongoDB database (verified). The request gives the following webpage output: HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Below is my code This is the portion of my settings.py: INSTALLED_APPS = [ ... 'rest_framework', ... ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } This is my models.py: from django.db import models from djongo.models import fields from django.contrib.auth.models import AbstractUser from django.contrib.auth.hashers import make_password from djongo.models import fields CHARFIELD_MAX_LENGTH = 1024 # Create your models here. class AbstractModel(models.Model): _id = fields.ObjectIdField() external_id = models.CharField(max_length = CHARFIELD_MAX_LENGTH, null = True, blank = True,) options = models.JSONField(null = True, blank = True,) created_at = models.DateTimeField(auto_now_add = True, null = False, blank = False,) updated_at = models.DateTimeField(null = True, blank = True,) class Meta: … -
I want to use path value from views.py to django template html
VIEWS.PY CODE data = { "product" : { "product1":{ "path":"assets/carouselImgs/laptop1.png" }, } } I want to use this path value to load image. HTML CODE <img class="carousel-img" src="{% static 'how can i use path value here' %}" alt=""> -
Why single html <p> tag is being spilt into two <p> tags with a <br> tag between them?
Below is my template html tag ( django): <p class="card-text cfs-9 cfc-grey">{{i.post|safe|truncatechars:100}}</p> This tag render totally fine on local server, but on production server, this single <p> tag is being split into two <p> tags and an extra <br> tag appear out on nowhere between them. I think the issue is with 'truncatechars' but i could not figure out. Below is view source code from both local and production server. Local Server view page source: <p class="card-text cfs-9 cfc-grey">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the…</p> Production server view page source: <p class="card-text cfs-9 cfc-grey"><br><p>In this post I'll be demonstrating how we can deploy Django website on…</p> I tried {{i.post|truncatechars:10|safe}} instead of {{i.post|safe|truncatechars:100}} but the problem remains.Tried using 'truncatewords' but still same problem. -
Specifying a relation through multiple shared foreign keys
Let's say we have 4 models, lets call them Alpha, Beta, Gamma, and Delta and the first two are something like: class Alpha(models.Model): gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT) delta = models.ForeignKey(Delta, on_delete=models.RESTRICT) text = models.CharField(max_length=1024) class Meta: constraints = [ models.UniqueConstraint(fields=['gamma_id', 'delta_id']) ] class Beta(models.Model): gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT) delta = models.ForeignKey(Delta, on_delete=models.RESTRICT) value = models.IntegerField() As you can see the two foreign keys can be used to associate any number of rows from Beta with one row from Alpha. There is essentially a one to many relationship between Beta and Alpha. For various reasons it is not feasible to replace the two foreign keys in Beta with a foreign key to Alpha. Is there a way to define a relationship on Alpha that returns all the rows from Beta that have the same gamma_id and delta_id -
How to use aggregate functions count or length in django
would like to use the count or length function in template, but I don't know how to go about it. I would like to count the items separately of all categories models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Rock', 'Rock'), ('Pop', 'Pop'), ('Reggae', 'Reggae'), ('Disco', 'Disco'), ('Rap', 'Rap'), ('Electronic music', 'Electronic music'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) views.py A simple listing of all elements class ProductListView(View): def get(self, request): products = CD.objects.all() return render(request, 'products/statistics.html', {'products': products})