Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Relationship Type Between Comments and an App
I'm new to setting up database schemas and am working a problem where I have multiple models that should contain a comments section. I'm using Django with SQLite for reference. For example there are Projects which are made up of Tasks. Each Project and Task should have a comments section. Projects can contain many Tasks, but one task will only point to one Project. I have one model for Comments that will ever only point to one Project or one Task, but Projects and Tasks will have multiple Comments. I think what I want is a Many to one relationship on the Comments model, but then I would need multiple FK fields depending on where the comment is attached (Project or Task). My full app will have 8-10 locations where we'd want to have comments. Thanks in advance! -
How to avoid Django to change field on model migration when using makemigrations?
I need to avoid python manage.py makemigrations to alter the uniqueness of a field. The reason behind it is that if I leave the unique=True on the model the function bulk_create with update_conflicts generates the following error: django.db.utils.ProgrammingError: there is no unique or exclusion constraint matching the ON CONFLICT specification This error does not occurs if I migrate with unique=True then I remove it when running the app. It may be a bug on the update_conflicts implementation as it's recent. Here is the function to bulk_create: MyModel.objects.bulk_create( vendors, update_conflicts=True, unique_fields=["my_field"], update_fields=["other_field", "another_field"], ) Here is the initial model creation: # 0001_initial.py class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="MyModel", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("my_field", models.CharField(db_index=True, max_length=50, unique=True)), ... ], ), ] Here is what I want to avoid when rerunning makemigrations as I want to keep field uniqueness. # 0002_alter_my_table_my_field.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("my_database", "0001_initial"), ] operations = [ migrations.AlterField( model_name="my_model", name="my_field", field=models.CharField(db_index=True, max_length=50), # I need this to continue unique ), ] `` -
Django admin drop down menu dependent won't load
First, I know there are other post on topic but until now none worked for me hence here I am kindly asking your help. The task is simple: in Django Admin I have a form with a drop-down menu whose select must filter and fill-in another drop-down menu. First I tried to simply add a jQuery to my form to get the changes on field select. The .js is correctly loaded together with other Javascripts but simply nothing happen when I made a selection on the parent drop-down. Second I tried to add the widget on form declaration. Same result as above. Following is my last attempt, result as above: Models.py class Utenti(models.Model): nome = models.CharField(max_length = 188) cognome = models.CharField(max_length = 188) dataNascita = models.DateField(max_length = 8, verbose_name = "Data di nascita") genere = models.CharField(max_length = 19, choices = generi, null = True, blank = True, verbose_name = "Genere") provincia = models.ForeignKey(Provincia, on_delete = models.SET_NULL, null = True) citta = models.ForeignKey(Comune, on_delete = models.SET_NULL, null = True, verbose_name = "Citta'") cf = models.CharField(max_length = 16, validators = [ validate_codice_fiscale ]) class Meta: verbose_name = "Utente" verbose_name_plural = "Utenti" def __str__(self): return str(self.nome) + " " + str(self.cognome) Admin.py class … -
Reverse for 'category_2' with arguments '('',)' not found
I want whenever I click on the category, I can see the available categories and by clicking on each one I can display the products of that category and again by clicking on the product name, I can see the page of that product. Here, clicking on the category in the first step will display this error. what's the reason in views.py: def product_detail(request, product_id): product = get_object_or_404(Product, pk=product_id) comments = Comment.objects.filter(product=product) offers = PriceOffer.objects.filter(product=product).order_by('-offer_price') off_list = [float(product.first_bid)] maximum = float(product.first_bid) if request.method == 'POST': #comment #offer context = { 'product': product, 'comments': comments, 'offers': offers, 'off' : off } return render(request, 'auctions/product_detail.html', context) def category(request): categories = Category.objects.all() return render(request, 'auctions/category.html', {'categories': categories}) def category_2(request,cat_id): category = Category.objects.get(id=cat_id) products = Product.objects.filter(category=category) return render(request, 'auctions/product_detail.html', {'category': category, 'products': products}) urls.py: path("product_detail/<int:product_id>/", views.product_detail, name="product_detail"), path("category", views.category, name="category"), path("category_2/<int:cat_id>/", views.category_2, name="category_2"), category.html: {% extends "auctions/layout.html" %} {% block body %} <h3><a href="{% url 'category_2' cat_id %}">{{ category.name }}</a></h3> {% endblock %} product_detail.html(Only the relevant part): <h2>{{ category.name }}</h2> {% for product in products %} <h3>{{ product.name }}</h3> {% endfor %} layout.html(Displays the linked category at the top of the page): <li class="nav-item"> <a class="nav-link" href="{% url 'category' %}">Category</a> </li> error: Request Method: … -
Data is not getting into database from Django form
I press 'submit' button, there is 'post' request in the terminal, but there is no new model in database. forms.py class PinCreationForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={ 'class':'create-pin-file-input' })) name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'create-pin-text-input', 'placeholder': 'Богатый мужчина' })) description = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'create-pin-text-input', 'placeholder': 'Мужик стоит дрочит' })) tags = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'create-pin-text-input', 'placeholder': 'Спорт, Машина, Огород' })) class Meta: model = PinModel fields = ('image', 'name', 'description', 'tags') models.py class PinModel(models.Model): name = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) tags = models.TextField() image = models.ImageField(upload_to='pin_images') user = models.ForeignKey(to=User, on_delete=models.CASCADE) views.py class CreatePinView(CreateView): model = PinModel form_class = PinCreationForm template_name = 'pinapp/create-pin.html' success_url = reverse_lazy('users:login') html section class="create-pin-section"> <div class="create-pin-div"> <h2>Create Pin</h2> <form action="{% url 'create-pin' %}" class="create-pin-form" method="post"> {% csrf_token %} <label for="{{ form.image.id_for_label }}">Choose Pic</label> {{ form.image }} <label for="{{ form.name.id_for_label }}">Choose da name</label> {{ form.name }} <label for="{{ form.description.id_for_label }}">Choose da description</label> {{ form.description }} <label for="{{ form.tags.id_for_label }}">Choose da tags</label> {{ form.tags }} <button type="submit">Create</button> </form> </div> </section> i want to explain, that i want is for the 'user' field to be filled in with the user who submitted the form i tried everything that i found, no results. -
Trouble install mysqlclient in Cpanel
Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [43 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb # Options for building extention module: extra_compile_args: ['-I/usr/include/mysql', '-std=c99'] extra_link_args: ['-lmariadb', '-pthread', '-lz', '-ldl', '-lm', '-lpthread', '-lssl', '-lcrypto'] define_macros: [('version_info', (2, 2, 0, 'final', 0)), ('version', '2.2.0')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-39 creating build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/times.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/_exceptions.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/release.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/converters.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/connections.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/init.py -> build/lib.linux-x86_64-cpython-39/MySQLdb copying src/MySQLdb/cursors.py -> build/lib.linux-x86_64-cpython-39/MySQLdb creating build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/ER.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/CR.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/init.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants copying src/MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-cpython-39/MySQLdb/constants running egg_info writing src/mysqlclient.egg-info/PKG-INFO writing dependency_links to src/mysqlclient.egg-info/dependency_links.txt writing top-level names to src/mysqlclient.egg-info/top_level.txt reading manifest file 'src/mysqlclient.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' adding license file 'LICENSE' writing manifest … -
Django admin login not showing OTP Device
I tried adding the otp_totp plugin. and pip install the requirements but still not getting anywhere. I have added different creating a models.py file and an admin.py file still not helping. This is my settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_otp', 'django_otp.plugins.otp_totp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] The urls.py file from django.contrib import admin from django.urls import path from django_otp.admin import OTPAdminSite from django_otp.admin import OTPAdminSite admin.site.__class__ = OTPAdminSite urlpatterns = [ path('admin/', admin.site.urls), ] [enter image description here](https://i.stack.imgur.com/QwFQ6.png) -
Add a condition to query list of a function in Python
I have an eCommerce website with Django, I want to put a condition with if statement to my payment function that only if product sold status is false proceed to payment and if not output a message to user. I cannot workout a way to approach this. any help would be appreciated here is my payment function : def acc_go_to_gateway_view(request): cart_items = AccountCart.objects.filter(user=request.user) print (cart_items) total_price = 0 if cart_items: for item in cart_items: total_price += (item.product.price) * item.quantity amount = total_price user_mobile_number = '' factory = bankfactories.BankFactory() try: bank = factory.auto_create() bank.set_request(request) bank.set_amount(amount) bank.set_client_callback_url('/acc-callback-gateway') bank.set_mobile_number(user_mobile_number) # اختیاری bank_record = bank.ready() return bank.redirect_gateway() except AZBankGatewaysException as e: logging.critical(e) raise e and this is my product model sold status is like this : class Product(models.Model): . . . . sold = models.BooleanField(default=False) and the Cart model that the bank function conntects to is : class Cart(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(AccountProduct, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.product.name since the payment function works with my cart model , and in my cart model the product model connects via a foreign key i couldnt use filter() modifier and i cant workout how to do this -
python program use case for the interview [closed]
You are given words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification. Note: Each input line ends with a "\n" character. Constraints: The sum of the lengths of all the words do not exceed All the words are composed of lowercase English letters only. Input Format The first line contains the integer, . The next lines each contain a word. Output Format Output lines. On the first line, output the number of distinct words from the input. On the second line, output the number of occurrences for each distinct word according to their appearance in the input. Sample Input 4 bcdef abcdefg bcde bcdef Sample Output 3 2 1 1 Explanation There are distinct words. Here, "bcdef" appears twice in the input at the first and last positions. The other words appear once each. The order of the first appearances are "bcdef", "abcdefg" and "bcde" which corresponds to the output. -
Getting Users current Page url in djangorestframework
How can I get the url a user is making their request "from" in Django Rest Framework? Currently using const current_url = window.location.href const api_key = "API_KEY" fetch(`http://127.0.0.1:8000/posts/api/${api_key}?url=${current_url}) But I feel this method isn't secure enough as it can be altered from the front end, and a different URL can be hardcoded there. So, I need to get the user's current url from the Backend. -
In Django admin, how do I manage complex user privileges?
Suppose you have this entity structure in Django with to-many relationships: - Company - Division - Department - Unit Every user is part of a Unit, so I managed the rights to create, edit and delete entities in Django Admin by assigning groups for users that had Department, Division or Company privileges. E.g. "DepartmentAdmin", "DivisionAdmin", etc. To determine the correct privilege, I just followed the Unit up the chain. Easy enough. Now I have to refactor: users can now be members of more than one Unit (perhaps keeping their "main" Unit). They can have arbitrary rights to administer any other Department, Division, etc.. How would I best model that? I have tried with a new entity Membership, a kind of join table with additional information about the role / privileges. Is this a good idea? I found that this creates a lot of dependencies elsewhere and determining the rights is quite complicated. e.g. class Membership(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="other_departments") department = models.ForeignKey(Department, on_delete=models.CASCADE, related_name="other_members") position = models.CharField(_("Position"), max_length=32, null=True, blank=True) Or is there a better way by leveraging the existing admin rights management features of Django? How would you go about this? Thanks! -
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 …