Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to configure my celery periodic tasks outside of the Django settigns file? I can't import my tasks into settings
Here's how my project is organized. electron / ... electron / <----- sources root (pycharm) ... electron / ... celery.py settings.py tasks / tasks.py <----- Here are my tasks celery beat configuration in settings.py from celery.schedules import crontab from tasks import tasks CELERY_BEAT_SCHEDULE = { "toutes-les-minutes": { "task": "tasks.tache_journaliere", "schedule": crontab(minute="*/1"), }, } When I import my tasks like this: from ..tasks import tasks. I get the following error: ImportError: attempted relative import beyond top-level package When I import tasks like this: from tasks import tasks,the following error occurs django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I've been trying to correct these errors for a while, but it doesn't work. I even looked for solutions here. I still can't. Is it not possible to configure periodic tasks outside of the settings.py file? (in the celery.py file for example) -
How to access the session information coming in from a third party application in Django
I Need to check whether a user is logged in to a third party application from a redirection request that comes from that application. This request must contain a session token and the credentials used to log in to that application. Assuming that they're present, how can I access this information from inside a Django application? I tried SSO and Django Sessions, however couldn't find anything useful there. It would be really helpful to know if I am looking in the right place. -
Style sheet not running in Docker (was working in venv) for django
I've been pulling my hair out over this. I'm getting the following error message every time I load my page: listings:20 Refused to apply style from 'http://localhost:8000/static/meltexapp/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Here's my file structure: meltex -settings.py [...] meltexapp -static --meltexapp.css -templates --nav.html Dockerfile docker-compose.yaml [...] settings.py: from pathlib import Path import environ import os env = environ.Env() environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-raa_)uczfns2bd8y&-vl5cg0gvyrk29%sy641kwem$809elt2g" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = "meltexapp.User" # Application definition INSTALLED_APPS = [ "meltexapp", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "bootstrap5", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "meltex.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.template.context_processors.static", ], }, }, ] WSGI_APPLICATION = "meltex.wsgi.application" # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", … -
Merge 2 record in to record when the column datas are the same in django
How can i get the sum of the 'HARMAN' values into 1 record if the 'KARIŞIM KODU' is the same class ProjeVerileri(models.Model): harman = models.CharField(max_length=250,blank=True,null=True) karisim = models.CharField(max_length=250,blank=True,null=True) def __str__(self): return str(self.harman +' / ' + self.karisim) and this is my model, in the end i want my data to look like this if request.method == 'POST': karisim=request.POST.get('karisim') harman=request.POST.get('harman') ProjeVerileri.objects.create( karisim=karisim, harman = harman, ) this is my views -
Getting Exception Type: KeyError Exception Value: 'pk' in class CreateCheckoutSessionView(APIView)'s post method in line: hotel_id=self.kwargs["pk"]
I've integrated stripe payment gateway in my webapp(backend: django, frontend: reactjs). I'm fetching the details of hotels from DRF using axios in frontend to display all the hotels cards. On clicking a particular hotel card it's information page opens where that particular hotel's information is displayed and that particular hotel's id is fetched using useParams. So on clicking a particular hotel card it's information is displayed and now I have a payment button which on click should open the stripe payment gateway and that payment information should display that hotel's price,image only. models.py from django.db import models from django.core.exceptions import FieldDoesNotExist # Create your models here. class Hotels(models.Model): id=models.AutoField(primary_key=True) name = models.CharField(max_length=300,default=" ") email = models.EmailField() #address landmark = models.CharField(max_length=50,default=" ") city = models.CharField(max_length=50, default=" ") state = models.CharField(max_length=50,default=" ") country = models.CharField(max_length=50,default=" ") pincode = models.IntegerField(default=00) #contacts prefix = models.CharField(max_length=4,default=" ") phone = models.CharField(max_length=10,default=" ") # phone=models.BigIntegerField(max_length=10) #accessiblity visual_impaired=models.BooleanField(default=0) wheelchair_user=models.BooleanField(default=0) hearing_impaired=models.BooleanField(default=0) speech_impaired=models.BooleanField(default=0) #extra facility = models.TextField(default=" ") # rooms = models.IntegerField() # price = models.IntegerField() # ac_rooms = models.BooleanField() roomtype1=models.CharField(max_length=100,default="Regular") roomtype2=models.CharField(max_length=100,default="Regular") roomtype3=models.CharField(max_length=100,default="Regular") pricetype1=models.IntegerField(default=1000) pricetype2=models.IntegerField(default=1000) pricetype3=models.IntegerField(default=1000) facilityoftype1=models.TextField(default=" ") facilityoftype2=models.TextField(default=" ") facilityoftype3=models.TextField(default=" ") image=models.CharField(max_length=500,default=" ") def __str__(self): return self.name views.py from django.shortcuts import render from django.views.generic import TemplateView # Create your … -
Deadlock MySQL with Django's get_or_create on shared lock on creation
I am running a script on my database that has multiple threads running at the same time. They are running this code: with transaction.atomic(): ( aggregated_report, created, ) = db_model.objects.select_for_update().get_or_create( currency=currency, date=today_date, aggregator=aggregator, type=transaction.type, **kwargs, defaults={"value": transaction.value}, ) if not created: aggregated_report.value += transaction.value aggregated_report.save() When I ran my script I was faced with a dead lock when the get_or_create() did not find an object and had to create it. From an application stand point I am simply catching the OperationalError and retrying. This was the deadlock log from MySQL when I did SHOW ENGINE INNODB STATUS ------------------------ LATEST DETECTED DEADLOCK ------------------------ 2023-10-30 16:26:39 281472641544064 *** (1) TRANSACTION: TRANSACTION 2108849, ACTIVE 0 sec starting index read mysql tables in use 1, locked 1 LOCK WAIT 3 lock struct(s), heap size 1128, 2 row lock(s) SELECT `reports_aggregatedvalues`.`id`, `reports_aggregatedvalues`, `reports_aggregatedvalues`.`currency`, `reports_aggregatedvalues`.`date`, `reports_aggregatedvalues`.`type`, `reports_aggregatedvalues`.`aggregator`, `reports_aggregatedvalues`.`value` FROM `reports_aggregatedvalues` WHERE (`reports_aggregatedvalues`.`aggregator` = '---' AND `reports_aggregatedvalues`.`currency` = 'USD' AND `reports_aggregatedvalues`.`date` = '2023-10-09 00:00:00' AND `reports_aggregatedvalues` AND `reports_aggregatedvalues`.`type` = 'TRANSFER') LIMIT 21 FOR UPDATE *** (1) HOLDS THE LOCK(S): RECORD LOCKS space id 26 page no 5 n bits 384 index Unique Report of table `phoenix`.`reports_aggregatedvalues` trx id 2108849 lock mode S Record lock, heap no 313 … -
the input device is not a TTY ERROR in github actions
when i push code i want to test if everything is ok with code. problem is that docker exec command does not execute. i tried several methods and they gave different errors - name: Test run: | echo "run db" docker-compose up -d db echo "run web_api" docker-compose up -d web_api docker-compose exec web_api sh -c python application/manage.py test this part give the error TTY and another method i tried - name: Test run: | echo "run db" docker-compose up -d db echo "run web_api" docker-compose run --rm web_api sh -c python application/manage.py test this starts application but do not execute script -
How to update object which was got from django cache
I'm caching my objects, and when I need I'm trying to update value of object which was got from cache. save() method starts work, but doesn't save it, and also doesn't raise any error. models.py class AdvertisementQueryset(models.QuerySet): def active_advertisements(self) -> models.QuerySet: return self.filter( status=AdvertisementModelMixin.Statuses.ACTIVE ) def five_low_score_ads(self) -> models.QuerySet: if self.all().count() < 5: return self.all() return ( self.all() .order_by("score")[:5] ) class AdvertisementModelMixin(models.Model): class Statuses(models.TextChoices): ACTIVE = "active", _("Active") HIDDEN = "hidden", _("Hidden") DELETED = "deleted", _("Deleted") TEST = "test", _("Test") objects = AdvertisementQueryset.as_manager() link = models.URLField() view_count = models.PositiveIntegerField(default=0) duration = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) published_at = models.DateTimeField(blank=True, null=True) deleted_at = models.DateTimeField(blank=True, null=True) status = models.CharField( max_length=30, choices=Statuses.choices, default=Statuses.ACTIVE ) uuid = models.UUIDField(default=uuid4) score = models.IntegerField(default=0) @property def is_active(self): return self.status == self.Statuses.ACTIVE @property def is_deleted(self): return self.status == self.Statuses.DELETED @property def is_for_test(self): return self.status == self.Statuses.TEST @property def is_hidden(self): return self.status == self.Statuses.HIDDEN def view_count_increase(self): self.view_count += 1 print("INCREASED") self.save() def set_as_active(self): self.status = self.Statuses.ACTIVE self.save() def set_as_hidden(self): self.status = self.Statuses.HIDDEN self.save() def set_as_deleted(self): self.status = self.Statuses.DELETED self.deleted_at = timezone.now() self.save() def save(self, *args, **kwargs) -> None: if not self.published_at and not self.is_hidden: self.published_at = timezone.now() if not self.deleted_at and self.is_deleted: self.deleted_at = timezone.now() return super().save(*args, … -
Script isnt working properly after switching Form into ModelForm in django
In my django app I have changed my form for series discharge from forms.Form in forms.ModelForm and form itself is working properly. However, on that same form I have a button that would take remaining quantity of specific series that's being discarged and put that value into quantity input field. Before my form in forms.py was described like this: class DischargeForm(forms.Form): quantity = forms.DecimalField( label="Quantity to be discharged:", min_value=1, widget=forms.NumberInput(attrs={ "class": "form-control", "style": "width: 300px;" }); Now it looks like this: class DischargeForm(forms.ModelForm): class Meta: model = Discharge fields = ['quantity',] widgets = { 'quantity': forms.NumberInput(attrs={"class": "form-control", "style": "width: 300px;"} ), labels= {"quantity": "Quantity to be discharged:",} My script that enables the button functionality looks like this: <script> document.addEventListener("DOMContentLoaded", function () { const inputQuantityButton = document.getElementById("input-quantity"); inputQuantityButton.addEventListener("click", function(){ event.preventDefault(); const remainingQuantity = {{ series.quantity }}; document.getElementById("id_quantity").value = remainingQuantity; }); }); </script> Form with button on html page looks like this: <form method="post" id="discharge-form"> {% csrf_token %} {{ form.as_p }} <button id="input-quantity">Remaining quantity</button> <button type="submit">Discharge</button> </form> For some reason that button isn't working properly. When button is clicked form just gets sent as if submit button was clicked ( event.preventDefault(); isn't working?). I have inspected the html code django generates and … -
Logger in Django is somehow logging all SQL queries even though its not supposed to
So I work in a new place and I do not know everything about the project and there is no one who has answer to my question, no documentation, etc. The problem is: loggers are completely unreadable, many errors, almost everything important is logged to one file and the worst is that all SQL queries/requests to DB are logged, and I do not need them at all. Here is my logging config, I do not see anything related to SQL logging here, how can i find where in my project SQL logging is enabled? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '#######\n{asctime}\n {message}\n#######', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/sites/moneycase/logs/django_error.log', 'formatter': 'verbose', }, 'ubki': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/sites/moneycase/logs/ubki.log', 'formatter': 'verbose', }, 'ipay': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/sites/moneycase/logs/ipay.log', 'formatter': 'verbose', }, 'root_file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/sites/moneycase/logs/root.log', 'formatter': 'verbose', }, }, 'loggers': { 'ubki': { 'handlers': ['ubki'], 'level': 'DEBUG', 'propagate': True, }, 'ipay': { 'handlers': ['ipay'], 'level': 'DEBUG', 'propagate': True, }, 'root': { 'handlers': ['root_file'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } logging.config.dictConfig(LOGGING) -
How to allow blank in model property field in django?
I have a property defined as the following @property def user_nr(self) -> str: x = "generated str" # some logic based on field _user_nr return x @user_nr.setter def user_nr(self, new_value) -> None: self._user_nr = new_value how can I use that property in Django serilizer given that the value can be blank sometimes? I add the property name in fields in the serializer but the blank values get removed from the validated data so when I try to access user_nr in validated data it says no key named user_nr but if I set a value and not a blank string, I can access it normally. so how can I retain the blank in that case? -
Django query sum decimal based on column
I trie to find a solution to summary fields depended on a row. In the database the SQL would be: Database: ACCOUNT | LIMIT | MARKET | LENDING | BALANCE ---------------------------------------------- 1000010 | 200.00 | 0.00 | -234.55 | 1000.00 1000010 | 300.00 | 11.00 | 0.00 | -239.00 1000010 | -200.00 | 235.00 | -134.00 | 450.00 1000011 | 30.00 | 1.00 | -10.00 | -98.00 1000011 | -200.00 | 235.00 | -134.00 | 49.00 SQL statements: SUM(LIMIT) as bond_limit, SUM(MARKET) as market_value, SUM(LENDING) as lending_value, SUM(case when BALANCE > 0 then BALANCE else 0 end) as FREE, SUM(case when BALANCE < 0 then BALANCE else 0 end) as MISS This should be the result: ACCOUNT | LIMIT | MARKET | LENDING | BOND_LIMIT | MARKET_VALUE | LENDING_VALUE | FREE | MINUS 1000010 | 200.00 | 0.00 | -234.55 | Sum(LIMIT) | Sum(MARKET) | Sum(LENDING) | Sum(BALANCE) or 0 1000010 | 300.00 | 11.00 | 0.00 | Sum(LIMIT) | Sum(MARKET) | Sum(LENDING) | Sum(BALANCE) or 0 1000010 | -200.00 | 235.00 | -134.00 | Sum(LIMIT) | Sum(MARKET) | Sum(LENDING) | Sum(BALANCE) or 0 1000011 | 30.00 | 1.00 | -10.00 | Sum(LIMIT) | Sum(MARKET) | Sum(LENDING) | Sum(BALANCE) or … -
Encountering ValueError: not enough values to unpack (expected 3, got 0) with Celery in Django project on Windows 7
I have been working on a Django project on my Windows 7 machine, using VS-Code as my development environment. Recently, I decided to incorporate Celery for handling asynchronous tasks. However, I have been encountering a ValueError: not enough values to unpack (expected 3, got 0) whenever I try to retrieve the result of a task. Here's a snippet of how I am creating and calling the task: # common/test_tasks.py from celery import shared_task @shared_task def add(x, y): return x + y # In Django shell from common.test_tasks import add result = add.delay(4, 6) print(result.ready()) # Outputs: True print(result.get()) # Raises ValueError I have tried different Celery configurations and also different backends and brokers. Initially, I was using Redis as both the broker and backend, but I encountered the same error. I switched the broker to RabbitMQ (pyamqp://guest:guest@localhost//) while keeping Redis for the result backend. Still, the error persists. I also attempted to downgrade Celery to version 3.1.24 but faced installation issues on Windows. Here are my relevant settings in the settings.py file: # settings.py CELERY_BROKER_URL = 'pyamqp://guest:guest@localhost//' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' I've also checked the logs, but nothing stood out. The tasks seem to be executing successfully, but the error occurs … -
Python dateparser error, AttributeError: "safe_load()" has been removed, use
Today while I was trying to build my application without any changes made to old code just added logging and found below error by surprise. File "/app/search/parsers.py", line 9, in <module> import dateparser File "/home/python/.local/lib/python3.8/site-packages/dateparser/__init__.py", line 7, in <module> _default_parser = DateDataParser(allow_redetect_language=True) File "/home/python/.local/lib/python3.8/site-packages/dateparser/conf.py", line 84, in wrapper return f(*args, **kwargs) File "/home/python/.local/lib/python3.8/site-packages/dateparser/date.py", line 290, in __init__ available_language_map = self._get_language_loader().get_language_map() File "/home/python/.local/lib/python3.8/site-packages/dateparser/languages/loader.py", line 21, in get_language_map self._load_data() File "/home/python/.local/lib/python3.8/site-packages/dateparser/languages/loader.py", line 39, in _load_data data = SafeLoader(data).get_data() File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 108, in get_data return self.construct_document(self.composer.get_node()) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 123, in construct_document for _dummy in generator: File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 629, in construct_yaml_map value = self.construct_mapping(node) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 427, in construct_mapping return BaseConstructor.construct_mapping(self, node, deep=deep) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 242, in construct_mapping value = self.construct_object(value_node, deep=deep) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 145, in construct_object data = self.construct_non_recursive_object(node) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 179, in construct_non_recursive_object data = constructor(self, node) File "/home/python/.local/lib/python3.8/site-packages/dateparser/utils/__init__.py", line 192, in construct_yaml_include return yaml.safe_load(get_data('data', node.value)) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/main.py", line 1105, in safe_load error_deprecation('safe_load', 'load', arg="typ='safe', pure=True") File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/main.py", line 1037, in error_deprecation raise AttributeError(s) AttributeError: "safe_load()" has been removed, use yaml = YAML(typ='safe', pure=True) yaml.load(...) instead of file "/home/python/.local/lib/python3.8/site-packages/dateparser/utils/__init__.py", line 192 return yaml.safe_load(get_data('data', node.value)) script returned exit code 1 Can someone help what exactly changed … -
AWS issue with django backend and vue js frontend
my django backend is deployed on aws elastic beanstalk on default settings and auto scaling env type is single instance vue js frontend is hosted on aws s3, its setting is done with cloudfront and its now running on https from subdomain my backend is still on http and works fine on http and i have configured a https subdomain with ssl certificate, but when i add it to elastic beanstalk, elastic beanstalk gets severe health and stops gives this "100.0 % of the requests are erroring with HTTP 4xx. Insufficient request rate (6.0 requests/min) to determine application health." my rds is postgresql and handled separately, by just connecting it on django settings. I want to do rest api calls from aws s3 to elastic beanstalk it would be helpful, if you also specify django cors settings and frontend axios api call settings for such stack i tried with http back and front end and its working, I want to do rest api calls from aws s3 to elastic beanstalk backend both on https it would be helpful, if you also specify django cors settings and frontend axios api call settings for such stack thanks -
How can I filter the values of a foreign key field based on another foreign key field value in Django admin?
These are my models: class ProductType(models.Model): name = models.CharField(max_length=350, verbose_name=_('name')) is_active = models.BooleanField(default=True, verbose_name=_('is active')) class ProductSpecification(models.Model): product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, related_name='specifications', verbose_name=_('product type')) name = models.CharField(max_length=255, verbose_name=_('name')) class Product(models.Model): product_type = models.ForeignKey(ProductType, related_name='products', on_delete=models.RESTRICT, null=True, blank=True, verbose_name=_('product type')) class ProductSpecificationValue(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='specs_values', verbose_name=_('product')) specification = models.ForeignKey(ProductSpecification, on_delete=models.CASCADE, related_name='specs_values', verbose_name=_('specification')) value = models.CharField(max_length=255, verbose_name=_('value')) and in admin.py: class ProductSpecificationTabu(admin.TabularInline): model = ProductSpecification fields = ('name_en', 'name_fa',) @admin.register(ProductType) class ProductTypeAdmin(admin.ModelAdmin): fields = ('name_en', 'name_fa',) inlines = (ProductSpecificationTabu,) search_fields = ('name_en', 'name_fa',) class ProductSpecificationValueTabu(admin.TabularInline): model = ProductSpecificationValue fields = ('specification', 'value_en', 'value_fa',) autocomplete_fields = ('specification',) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): fields = ('product_type', ) inlines = (ProductSpecificationValueTabu, ) I want to limit the options for the 'ProductSpecificationValueTabu' based on the selected 'product_type' when choosing the product_type for a product. Should I do this using javascript? -
Large GB File upload to webserver
I have a requirement, where I want to create a web app(Either in Django or Fast API along with js in frontend), In which the user can upload large files (groups of files each file will be 3-4 GB), The collective size of these files may range 30-50 GB. How to approach this requirement. Can anyone help me navigate this requirement? -
Display Blob Image from MySQL to Django Template
I have models.py like this class p2_qc_ed(models.Model): qc_image = models.ImageField(upload_to='app_one/me/qc/ed/', null=True, blank=True) my views to upload the image like this captured_image_data = request.POST.get('capturedImageInput') format, captured_image_data = captured_image_data.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(captured_image_data), name='temp.' + ext) qc_entry = p2_qc_ed(qc_image=data) qc_entry.save() while form submission, capturedImageInput value was like "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAAAXNSR0IArs4c6QAAIABJREFUeF7svQ2P9Lp2nSlVvec/DxBkcufGztiZTOIYGRs2gnsB/0y/XdJgk2IVq1rci8UltqTu..." the image uploaded successfully and I can see the image in 'app_one/me/qc/ed/' folder. But when i try to retrieve the image i use the following snippet `def ed_test(request):` ` image_data = p2_qc_ed.objects.get(id=444).qc_image` ` encoded_image_data = base64.b64encode(image_data).decode('utf-8') ` ` print(image_data,encoded_image_data)` ` return render(request,'qc_checksheet/qc_ed_test.html','encoded_image_data':encoded_image_data})` here the printed values are b'app_one/me/qc/ed/temp.png' 'YXBwX29uZS9tZS9xYy9lZF9zYW5kaW5nL3RlbXAucG5n' but I cannot display it in django template. can someone help me what is wrong with this ? Thanks in advance. expected to display the uploaded image but i couldn't . -
Nested model in Wagtail Orderable
In Wagtail, I'm trying to create a Page that using Orderable model of Wagtail. And in that Orderable model, I'm trying to nest the "ImageWithAltText", the reason for this is because by default, Wagtail image does not provide alt text field. So I would like to create my own class for re-use anywhere that has image. Below is the code: class ImageWithAltText(models.Model): image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) image_alt_text = models.TextField(blank=True, null=True) panels = [ FieldPanel("image"), FieldPanel("image_alt_text"), ] class FAQItem(Orderable): page = ParentalKey("get_the_facts.GetTheFactPage", related_name="faq_items") media_file = models.ForeignKey(ImageWithAltText, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=500, blank=False) panels = [ FieldPanel("media_file"), FieldPanel("title"), ] class GetTheFactPage(Page): content_panels = Page.content_panels + [ InlinePanel("faq_items", label="FAQ"), ] I have no succeed with this, at the Admin site, the UI the not showing "image" and "image_alt_text" as expected. Please take a look at the picture below: I haven't had any clue why this happened yet. Please help me with this, thank you in advanced. -
Change User Password Page - Django
I created a profile page for the user. In the "change password" section: 👇 when I click on this form, unfortunately, it goes to this link: "http://127.0.0.1:8000/8/password/", if I defined in the links that it should go into this link: "http://127.0.0.1:8000/accounts/password/". where is the problem from? name of my project is "resume", and my app is "members". resume urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("main.urls", namespace="main")), path("blog/", include("blog.urls", namespace="blog")), path("accounts/", include("django.contrib.auth.urls")), path("accounts/", include("members.urls")), ] members urls.py: from django.urls import path from members.views import UserRegisterView, UserEditView, PasswordsChangeView from django.contrib.auth import views as auth_views app_name = "members" urlpatterns = [ path("register/", UserRegisterView.as_view(), name="register"), path("panel/", UserEditView.as_view(), name="panel"), path("password/", auth_views.PasswordChangeView.as_view()), ] -
Django unit test TypeError: the JSON object must be str, bytes or bytearray, not NoneType
I'm trying to write unit test and I faced this error a lot in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not NoneType and I can't tell where is the problem for example I have this simple unit test class CheckDiscountTest(TestCase): def setUp(self): self.test_order = { 'arrival_time':'12:00:00', } self.order = Order.objects.create(**self.test_order) self.test_discount = {'code': 'DISCOUNT','percentage': 10 } self.discount = Discount.objects.create(**self.test_discount) self.url = reverse('discount') def test_200(self): test_data = { 'code': 'DISCOUNT', 'id': self.order.id } response = self.client.post(self.url, data=test_data) self.assertEqual(response.status_code, status.HTTP_200_OK) for this @api_view(['POST', ]) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def check_discount(request): if ('code' in request.data and 'id' in request.data): order = Order.objects.get(id=request.data['id']) try: discount = Discount.objects.get(code=request.data['code']) order.order_related_invoice.cost = order.order_related_invoice.initial_cost - \ (order.order_related_invoice.initial_cost * (discount.percentage/100)) order.order_related_invoice.save() response_serializer = GetOrdersSerializer(order) return Response(response_serializer.data, status=status.HTTP_200_OK) except Discount.DoesNotExist: if ('id' in request.data): order = Order.objects.get(id=request.data['id']) order.order_related_invoice.cost = order.order_related_invoice.initial_cost order.order_related_invoice.save() response_serializer = GetOrdersSerializer(order) return Response(response_serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) else: if ('id' in request.data): order = Order.objects.get(id=request.data['id']) order.order_related_invoice.cost = order.order_related_invoice.initial_cost order.order_related_invoice.save() response_serializer = GetOrdersSerializer(order) return Response(response_serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) I'm just trying to understand the error and how to fix it can anyone help me -
Remote mysql server constantly stopping and rebooting
I have made a django chatting application that allows users to talk to one anoter. I am using websockets for chatting and a MySQL server as my database. Since a few days, the MySQL database (or the server itself) has been rebooting non stop. This is happening so frequently that I am getting an error in my django application that while a message that was sent was being sent by a user was being saved in the database, the connection was lost. I am also unable to load messages in chats, meaning the previous messages being sent by the user are not visible either. The other functionalities of the database seem to be working fine for some reason such as the profile being updated, your account info being stored accurately. The site temporarily works fine if I restart the server with the "sudo shutdown -r now" command but I get the same problem not too long after that. If you want, you can check out the functionality of the site over at https://aniconnect.org Here is the output when I do the journalctl command: gamedeveloper@animechatapp:~$ sudo journalctl -u mysql Sep 20 13:18:17 animechatapp systemd[1]: Starting mysql.service - MySQL Community Server... Sep … -
Python django static files in render
I'm not Able to load static files in django in production in using Whitestone but it's not working when debug = False this is my settings.py file I've read another stack overflow post saying to use apache or something else How to use one like I've heard of nginx how to use this where to put the files and how to make it deployable in render -
How can i add a popup to an already existing button?
I have this delete button on my posts that when you click on it it deletes the post I wanted to add a html popup that I have on that button so that when someone clocks on delete it first shows the confirmation popup and then delete the post if they clicked on ok how can I achieve that? Thanks Where my delete button is <div class="container"> <div style="margin-top: 25px"></div> <div class="card-deck mb-3 text-center"> <div class="card mb-4 box-shadow"> <div class="card-header"> <h4 class="my-0 font-weight-normal">{{post.title}}</h4> </div> <div class="card-body"> {{ post.body|truncatewords_html:30 }} <hr> <p><img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" width="75" height="75"> Author: {{ post.author }}</p> <a href="{% url 'detail' post.id %}" class="btn btn-info btn-small" >Read More <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-three-dots" viewBox="0 0 16 16"> <path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/> </svg></a> {% if user.is_authenticated %} <a href="{% url 'delete' post.id %}" class="btn btn-danger btn-small" >Delete <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16"> <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 … -
How to Perform Unit Conversion before Aggregating Model Fields in Django?
I have a Django model as follows: class WeightUnit: KILOGRAM = "kg" TONNE = "tonne" LBS = "lbs" CHOICES = [ (KILOGRAM, _("kg")), (TONNE, _("tonne")), (LBS, _("lbs")), ] TONNE_CONVERSION_FACTOR = { TONNE: 1, KILOGRAM: 0.001, LBS: 0.000453592, } class Product(models.Model): weight = models.FloatField(verbose_name=_("total weight")) weight_unit = models.CharField( _("weight unit"), choices=WeightUnit.CHOICES, default=WeightUnit.TONNE, max_length=5, ) Each instance of the Product model can have a different weight_unit, and I need to create a query that aggregates the weight field of all products while converting all weights to a single, common unit (e.g., tonnes) for the aggregation. This is the query that I tried and got KeyError: F(weight_unit): conversion_expression = ExpressionWrapper( F('total_weight') * WeightUnit.TONNE_CONVERSION_FACTOR[F('weight_unit')], output_field=FloatField(), ) return Products.objects.annotate( converted_weight=conversion_expression, ).aggregate( weight=Sum('converted_weight', default=0.0), )["weight"] How can I achieve this using Django's queryset and database expressions?