Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static files not updating inside docker container
My Django project uses Docker, gunicorn, and whitenoise. I recently altered settings to prepare for deployment, most notably adding configurations for AWS-hosted media files. Now when I run the project locally and collectstatic the static files do not update in the browser. I do, however, see the changes where static files are collected. Things I've tried/double checked: Ensuring I have a shared volume between the container and where static files are kept/updated Adding a step to collectstatic in my Dockerfile Confirming my static files settings Is something about django-storages causing the issue? I thought that previously I was able to make SCSS changes and have them show up by refreshing the browser. But that's not happening. Even running collectstatic inside the container has no effect. # relevant settings.py INSTALLED_APPS = [ ... "whitenoise.runserver_nostatic", "storages", ... ] MIDDLEWARE = [ "django.middleware.cache.UpdateCacheMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ... ] # AWS config (use in production only) USE_S3 = env.bool("USE_S3", default=not DEBUG) if USE_S3: AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", default="") AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", default="") AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", default="") AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = env.str("AWS_S3_REGION_NAME", default="us-east-2") AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } # S3 Public Media Settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' # … -
Django_tables2 + django_filter, edit template of table, reload after POST
I am using django_tables2 and django_filter in my website. I use standard template bootstrap.html but slightly modified. The problem is i can not use 'querystring' or 'render_attrs' anywhere. When I use simply: {% render_table table %} everything works fine. Also when I only display data, it works. Here's my html and the code. First of all, code that works: (home.html) {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% block table-wrapper %} <div class="table-container"> {% block table %} <table class="table table-bordered table-hover w-100 shadow-lg p-3 mb-5 bg-white"> {% block table.thead %} {% if table.show_header %} <thead class="table-dark" {{ table.attrs.thead.as_html }}> <tr> {% for column in table.columns %} <th {{ column.attrs.th.as_html }}>{{ column.header }}</th> {% endfor %} <th style="width:11%">Akcja</th> </tr> </thead> {% endif %} {% endblock table.thead %} {% block table.tbody %} <tbody {{ table.attrs.tbody.as_html }}> {% for row in table.paginated_rows %} {% block table.tbody.row %} <form method="post" action="."> {% csrf_token %} {% for column, cell in row.items %} <td {{ column.attrs.td.as_html }}> {{ cell }} </td> {% endfor %} <td> {% if row.record.zam_status == 0 %} <button type="submit" name="zatwierdz_zam" value ={{row.record.pk}} class="btn btn-dark btn-sm">Zatwierdź</button> <button type="submit" … -
using React JS components in django teamplates though static files (hybrid model) - what's wrong? (newbie JS/React question)
I am new to JS/React/npm/webpack, and fairly new to Django. I am trying to build search experience (i.e. front-end) for my existing Django web application, and I am planning to use elastic/search-ui components for that. I did some research (How to get Django and ReactJS to work together?) and I am following the hybrid model guide (https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/) where static JS files are used in Django templates. I got to the point where I could display some text from JS script in Django template, now I am trying to display imported JS component and I got stuck. This is my code: package.json: ... "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode development" }, ... "devDependencies": { "@elastic/search-ui": "^1.5.1", "babel": "^6.23.0", "babel-loader": "^8.1.0", "react": "^17.0.1", "react-dom": "^17.0.1", "react-scripts": "^4.0.3", "webpack": "^5.26.3", "webpack-cli": "^4.5.0" } webpack.config.js: const path = require('path'); module.exports = { entry: './ui-react-src/index.js', // path to our input file output: { filename: 'index-bundle.js', // output bundle file name path: path.resolve(__dirname, './reviewer/static/ui-react-build'), // path to our Django static directory }, }; django html template I want to load React components to: {% extends "base_generic.html" %} {% block content %} Test React component <hr> {% load static … -
Django _set.all() filter in QuerySet
I have database and I want to extract specific data of specific user from queryset. Now i have this VIEW def index(request): customerByName = Customer.objects.get(name='pablo') shopListById = ShopList.objects.get(transaction_id=1) shpoListSpecific = customerByName.shoplist_set.all() specificProducts = shopListById.shoplistproduct_set.all() context = {'customerByName':customerByName, 'shpoListSpecific':shpoListSpecific, 'shopListById':shopListById, 'specificProducts': specificProducts} return render(request, 'QuickShopperApp/home.html', context) MODELS class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) device = models.CharField(max_length=200, null=True, blank=True) def __str__(self): if self.name: name = self.name else: name = self.device return str(name) class Product(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class ShopList(models.Model): # cart customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) #product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) class ShopListProduct(models.Model): # each ShopList will have multiple ShopListProduct product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) shopList = models.ForeignKey(ShopList, on_delete=models.SET_NULL, null=True) #shoplistitem.shoplist quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.product) template.html <h3>specificProducts: {{specificProducts}}</h3> On my side i see items of specific customer. specificProducts: <QuerySet [<ShopListProduct: Apple>, <ShopListProduct: Cucumber>, <ShopListProduct: Cucumber>]> How can i get only Apple, Cucumber, Cucumber? -
How do I run Lighthouse CLI during tests in Django?
I would like to run Lighthouse CLI during tests in Django. By default, Django tests don't run a server that can respond to HTTP requests, so this is not possible. How can I run Lighthouse CLI during Django tests? -
Elastic Beanstalk: ModuleNotFoundError: No module named 'OpenSSL'
When deploying my app to Elastic Beanstalk it keep returning the error ModuleNotFoundError: No module named 'OpenSSL' when it is installing the python secrets module. I had the same error on my local machine and installed PyOpenSSL to resolve it. I however keep getting this error in elastic beanstalk despite installing PyOpenSSL first in my requirements.txt file .. error log 2021/03/19 11:37:57.559862 [INFO] Collecting pyOpenSSL Using cached pyOpenSSL-20.0.1-py2.py3-none-any.whl (54 kB) Collecting freezegun==1.1.0 Using cached freezegun-1.1.0-py2.py3-none-any.whl (16 kB) Collecting pytest==6.2.2 Using cached pytest-6.2.2-py3-none-any.whl (280 kB) Collecting secrets Using cached secrets-1.0.2.tar.gz (7.9 kB) 2021/03/19 11:37:57.559967 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 1. Stderr: ERROR: Command errored out with exit status 1: command: /var/app/venv/staging-LQM1lest/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py'"'"'; __file__='"'"'/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-azo2b_35 cwd: /tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/ Complete output (12 lines): Traceback (most recent call last): File "/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py", line 10, in <module> import OpenSSL ModuleNotFoundError: No module named 'OpenSSL' requirements.txt pyOpenSSL freezegun pytest secrets -
Custom field in Django ArrayField throws an error
PROBLEM I have CustomField nested in ArrayField. CustomField itself works well, also migrations throw no error. When I try to save MyModel(code=[StandardCode(...), ...]), why I get the following error: TypeError: asdict() should be called on dataclass instances I know that for some reason django tries to call my DataClassField get_prep_value() with value=[StandardCode(...), ...] Why that happens? How could this behaviour got fixed? FIELD DEFINITION class DataClassField(models.CharField): description = "Map python dataclasses to model." def __init__(self, dataClass, *args, **kwargs): self.dataClass = dataClass kwargs['max_length'] = 1024 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs['dataClass'] = self.dataClass return name, path, args, kwargs def from_db_value(self, value, expression, connection): if value is None: return value obj = json.loads(value) return from_dict(data_class=self.dataClass, data=obj) def to_python(self, value): if isinstance(value, self.dataClass): return value if value is None: return value obj = json.loads(value) return from_dict(data_class=self.dataClass, data=obj) def get_prep_value(self, value): try: if value is None: return value return json.dumps(asdict(value)) except Exception as e: print(value) raise e DATACLASS DEFINITION: @dataclass class StandardCode: code: str codeSystem: str displayName: str MODEL DEFINITION from django.contrib.postgres.fields import ArrayField class MyModel code = ArrayField(DataClassField(dataClass=StandardCode, null=True), size=2, default=list) -
How to send csrf token in xmlHttpRequest?
Using Ajax or xmlHttpRequest I want to download excel file from django backend. Backend creates file in memory and returns it to user. According to this answer I should use for this xmlHttpRequest, but there is no info how to set csrf middleware token in post request. I tried: To set request.setRequestHeader like this: request.setRequestHeader('x-csrf-token, window.CSRF_TOKEN) - token is missing and in data: request.send({'csrfmiddlewaretoken': window.CSRF_TOKEN, 'req': 'ExportAllMessages'}); I can't find any working solution with Ajax. -
How to have different expiry times for Web and Mobile Apps in Django simple jwt?
I am currently using Django Rest Framework to serve a React JS application, but recently, we are adding support for a React Native application as well. Now, as I use Django Simple jwt, here's the code for the expiry of the refresh and access tokens: settings.py ACCESS_TOKEN_LIFETIME = datetime.timedelta(hours=2) REFRESH_TOKEN_LIFETIME = datetime.timedelta(days=3) SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': ACCESS_TOKEN_LIFETIME, 'REFRESH_TOKEN_LIFETIME': REFRESH_TOKEN_LIFETIME, ... } While this works really well on web, I do not want the phone app users to have to get logged out automatically every 3 days. Is there a way to alter the refresh token lifetime based on the device that is asking for the tokens? If yes, how? -
Django Signals: How To Create Objects On Object Creation
I am trying to create an object on another model's object creation but i dont know what to put in the function save_collection_list_item to make this work. I am getting the error: 'Collection' object has no attribute 'collection_list_item' so what should i replace it with? models: class Collection(models.Model): posts = models.ManyToManyField(Post, related_name='collection_posts', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection_name = models.CharField(max_length=100) collection_description = models.CharField(max_length=1000, blank=True) collection_likes = models.ManyToManyField(User, related_name='liked_collections', blank=True) collection_image = models.ImageField(upload_to="images/") private = models.BooleanField(default=False) follows = models.ManyToManyField(User, related_name='collection_follows', blank=True) def __str__(self): return self.collection_name class Collection_List_Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) saved = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.collection.collection_name signals: @receiver(post_save, sender=Collection) def create_collection_list_item(sender, instance, created, **kwargs): if created: #collection_list_item = Collection_List_Item.objects.create(collection=instance, user=instance.author) Collection_List_Item.objects.create(collection=instance, user=instance.author) @receiver(post_save, sender=Collection) def save_collection_list_item(sender, instance, **kwargs): instance.collection_list_item.save() # What should i change this to? -
Django how to get model values inside another model?
I want the value of username from forms that I get as a string so that when I upload an image it is stored in a subdirectory with that username. i.e. if 'bob' registers the image should be saved in 'static/auth_image/bob/image_name.extension'. Also if I could it during the registration form filling that would be great. models.py class User_data(models.Model): username = models.CharField(max_length=256, null=True, blank=True) email = models.EmailField(max_length=254, null=True, blank=True) four_digit_pass = models.CharField(max_length=256, null=True, blank=True) private_key = models.CharField(max_length=256, null=True, blank=True) profile_pic = models.ImageField(upload_to='static/profilepic', null=True) def getUsername(self): return self.username def __str__(self): return str(self.username) class AuthImages(models.Model): owner = models.ForeignKey('User_data', null=True, on_delete=models.CASCADE) uname=owner. def save_auth_image(self): uname = self.username self.auth_image_file = models.ImageField( upload_to='static/auth_image/%s' % uname, null=True) forms.py class RegistrationForm(forms.ModelForm): four_digit_pass = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User_data fields = ['username', 'email', 'four_digit_pass', 'profile_pic', 'private_key'] register.html {% extends "storage_app/base.html" %} {% block body_block %} <div class="jumbotron"> <h1>Register Page</h1> </div> <div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <p>Private Key should not be changed or shared with anyone</p> <button type="submit">Upload</button> </form> </div> {% endblock body_block %} here in HTML, i want to take input for the second i.e. auth_image directly from webcam if possible This is my first question also I am new to Django so … -
After adding custom validation in AUTH_PASSWORD_VALIDATORS django admin change password removes password1 field
After adding custom validation in AUTH_PASSWORD_VALIDATORS django admin change password removes password1 field. -
search data using ajax and django and redirect to related pages
I am building a website and I want to implement searching. I want the user to enter some text and want to show suggestions using ajax. when the user click on specific product or category I want to redirect the user to related page. Here is what I have done so far: $(function () { $("#search").autocomplete({ source: "{% url 'ajax-search' %}", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 5, }); }); <div class="search"> <label for="search"></label> <input type="text" oninput="" style="height: 36px" class="searchTerm" placeholder="What are you looking for?" name="searchtext" id="search"> <button type="submit" class="searchButton"> <i class="fa fa-search"></i> </button> </div> path('ajax/search', views.autocompleteModel, name='ajax-search'), def autocompleteModel(request): if request.is_ajax(): q = request.GET.get('term', '') lookups = Q(name__icontains=q) | Q(category__name__icontains=q) products = Product.objects.filter(lookups).distinct() results = [] for product in products: place_json = {} place_json = product.name product_url = 'prodcuts/product/' + str(product.id) results.append(place_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) -
Django REST Framework internal value
I have a simple serializer with a date field (not ModelSerializer). class MySerializer(Serializer): some_date = DateField() I'm trying to access the date object after deserialization. slz = MySerializer(data={"some_date": "2020-05-03"}) # I surely have a better error handling in my actual code assert slz.is_valid() some_extracted_date = slz.data["some_date"] I would like my variable some_extracted_date to be a datetime.date instance. But the value in the MySerializer.data dict is a string. Is there a way to get this datetime.date instance ? -
How to dynamically set the limit_value of the build-in MinValueValidator inside a Django 3.1 ModelForm
I'm trying to dynamically set the limit_value of the build-in MinValueValidator inside a Django 3.1 ModelForm. The below code works for a fixed limit_value of 10 (see line 21 in views.py). models.py from django.contrib.auth.models import AbstractUser from django.db import models class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bids") bid = models.DecimalField(decimal_places=2, max_digits=9) views.py from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django import forms from .models import User, Listing, Category, Bid from django.db.models import Max from decimal import Decimal, DecimalException from django.core.validators import MaxValueValidator, MinValueValidator from django.core.exceptions import ValidationError class NewBidForm(forms.ModelForm): class Meta: model = Bid fields = '__all__' widgets = { 'user': forms.HiddenInput(), 'listing': forms.HiddenInput(), } def __init__(self, *args, **kwargs): super(NewBidForm, self).__init__(*args, **kwargs) self.fields['user'].show_hidden_initial=True self.fields['listing'].show_hidden_initial=True self.fields['bid'].validators=[MinValueValidator(10)] def clean(self): if 'user' in self.changed_data or 'listing' in self.changed_data: raise forms.ValidationError('Non editable field have changed!') return self.cleaned_data def index(request): listings = Listing.objects.all() return render(request, "auctions/index.html", { "listings" : listings, }) def listing(request, listing_id): if request.method == 'POST': data = request.POST form = NewBidForm(data) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("index")) else: listing = Listing.objects.get(pk=listing_id) bids = Bid.objects.filter(listing=listing) if bids: highest_bid = bids.aggregate(Max('bid'))['bid__max'] else: highest_bid … -
How to access form field in html class
I am building a BlogApp and I am trying to customize the FileUpload button. What i am trying to do I am trying to customize the File Upload button using CSS button , I am unable to access it with my model instance ( {{ form.file}} ) CSS .btn-upload { position: relative; overflow: hidden; display: inline-block; } .btn-upload input[type=file] { position: absolute; opacity: 0; z-index: 0; max-width: 100%; height: 100%; display: block; } .btn-upload .btn{ padding: 8px 20px; background: #337ab7; border: 1px solid #2e6da4; color: #fff; border: 0; } .btn-upload:hover .btn{ padding: 8px 20px; background: #2e6da4; color: #fff; border: 0; } #This is my image field by {{ form.image }} in template HTML {{ form.file}} What have i tried I tried using this <input type="file" name="file" class="btn-upload"> BUT it didn't worked for me. Any help would be really Appreciated. Thank You in Advance. I tried many time by adding classes and ids but none of them worked for me. I don't how can i -
Regarding Django runserver issue [closed]
My Django runserver does not start while start to create project and does not show any error messages also while I am using pyrated windows 10.Please help me resolve my problem. -
Dynamic Command for Kubernetes Jobs
So hopefully this makes sense to the non-Djangoers of the k8s community. I will try my best to explain the setup / reasoning. With Django, we have LOTS of what are called management commands that we can run within the scope and environment of our Django app that can really help development and deployment. I'm sure most other frameworks have similar, if not identical, concepts. An example would be the "python manage.py migrate" command that ensures our codebase (migration scripts) are applied to and reflect in the associated database. There are approx. 30 - 50 core commands we can run, we can also create our own, as well as apply those from any installed third party applications. Anyways. The most important takeaway is that there are a lot of commands we can and do run. Now, I have the following k8s Job to run the "migrate" command: apiVersion: batch/v1 kind: Job metadata: name: asencis-web-migrate-job spec: template: spec: containers: - name: asencis-web-migrate-job image: asencis/asencis-base:latest imagePullPolicy: Always command: ['python', 'manage.py', 'migrate'] envFrom: - configMapRef: name: asencis-config - secretRef: name: asencis-secret restartPolicy: Never backoffLimit: 5 This job essentially runs the python manage.py migrate command within the application scope/environment. It works like a charm: … -
Best way to re/use redis connections for prometheus django exporter
I am getting an error redis.exceptions.ConnectionError: Error 24 connecting to redis-service:6379. Too many open files. ... OSError: [Errno 24] Too many open files I know this can be fixed by increasing the ulimit but I don't think that's the issue here and also this is a service running on a container. The application starts up correctly works for 48 hours correctly and then I get the above error. Which implies that the connections are growing over time exponentially. What my application is basically doing background_task (ran using celery) -> collects data from postgres and sets it on redis prometheus reaches the app at '/metrics' which is a django view -> collects data from redis and serves the data using django prometheus exporter The code looks something like this views.py from prometheus_client.core import GaugeMetricFamily, REGISTRY from my_awesome_app.taskbroker.celery import app class SomeMetricCollector: def get_sample_metrics(self): with app.connection_or_acquire() as conn: client = conn.channel().client result = client.get('some_metric_key') return {'some_metric_key': result} def collect(self): sample_metrics = self.get_sample_metrics() for key, value in sample_metrics.items(): yield GaugeMetricFamily(key, 'This is a custom metric', value=value) REGISTRY.register(SomeMetricCollector()) tasks.py # This is my boilerplate taskbroker app from my_awesome_app.taskbroker.celery import app # How it's collecting data from postgres is trivial to this issue. from my_awesome_app.utility_app.utility … -
my code keeps showing me this error 404: the current path,get, didn't match any of these
this is my code I don't know where the error is coming from. It is telling me that Using the URLconf defined in ehiz.urls, Django tried these URL patterns, in this order: admin/ [name='home'] add/ [name='add'] The current path, get, didn't match any of these. Views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request,'base.html',{'name':'Gael'}) def add(request): val1 = int(request.GET['num1']) val2 = int(request.GET['num2']) res = val1 + val2 return render(request, 'result.html',{'result':res}) base.html {% extends 'main.html' %} {% block content %} <h1>hello {{name}}</h1> <form action="get"> <input type="text" name="num1" placeholder="Enter first number"><br> <input type="text" name="num2" placeholder="enter second number"><br> <input type="submit"> </form> {% endblock %} result.html {% extends 'main.html' %} {% block content %} the result is : {{result}} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('add/',views.add,name='add') ] -
How can I solve the error "page not found(404)" in my 1st django project?
I'm very new to django and I stuck in my first project the error says Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about using the URLconf defined in emuhay.urls, Django tried these URL patterns, in this order: admin/ The current path, about, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I'm expecting "Contat page" but page not found displayed every time my code is below #Url code from django.contrib import admin from django.urls import path from django.http import HttpResponse def home(request): return HttpResponse('Home Page') def contact(request): return HttpResponse('Contact Page') urlpatterns = [ path('admin/', admin.site.urls), path('',home), path('about/',contact), ] #setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'yra+iwr3x_)@ssxj)e%h^7=m(te0mh!_4xx61g7j2j4y)o9z&$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hihi', ] 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 = … -
django.core.exceptions.FieldError: Cannot compute Sum('<CombinedExpression: F() + F()): is an aggregate
I have a code: k = company.departments.all().annotate( net_pay_amount_sum=Sum('employees__payments__net_pay_amount'), earnings_sum=Sum('employees__payments__earnings__amount'), taxes_sum=Sum('employees__payments__taxes__amount'), ).annotate( total_sum=Coalesce(ExpressionWrapper( Sum(F('net_pay_amount_sum') + F('earnings_sum') + F('taxes_sum')), output_field=fields.DecimalField()), 0) ).values_list('name', 'total_sum') and when I run it I got exeption: django.core.exceptions.FieldError: Cannot compute Sum('<CombinedExpression: F(net_pay_amount_sum) + F(earnings_sum) + F(taxes_sum)>'): '<CombinedExpression: F(net_pay_amount_sum) + F(earnings_sum) + F(taxes_sum)>' is an aggregate Can someone tell me how can I sum this withot exeptions Sum(F('net_pay_amount_sum') + F('earnings_sum') + F('taxes_sum')), -
Django textarea form
i need to set rows and cols for a textarea in my HTML page from Django but it doesnt work. I already put rows and cols in mine form Views.py class EditForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'name':'title'})) body = forms.CharField(widget=forms.Textarea(attrs={'name':'body', 'rows':3, 'cols':5})) def new(request): return render(request,"encyclopedia/handlepage.html", { "title": "CREATE NEW PAGE", "edit": False, "editpage": EditForm() }) handlepage.html {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>{{title}}</h1> <a href="https://guides.github.com/features/mastering-markdown/">Markdown guides</a> {% if edit %} //Useless right now {% else %} <form method="POST" action="{% url 'save' %}"> <input type="submit" value="SAVE ENTRY"><br> {% csrf_token %} {{ editpage }} </form> {% endif %} {% endblock %} Then my page should have a small text area but it have the same size independent by its row and cols like this -
Object of type 'RecursionError' is not JSON serializable
Comparing length of two files and if not equal insert def compare(length, initial_val) i = initial_val if i == length: return 1 else: tags_extracted_from_template = re.findall(r'<[^>]+>', str(file1_list[i])) tags_extracted_from_user_form = re.findall(r'<[^>]+>', str(file2_list[i])) if "".join(tags_extracted_from_template) != "".join(tags_extracted_from_user_form): file2_list.insert(i, "".join(tags_extracted_from_template)) return compare(len(file2_list),0) print(file2_list) return compare(len(file2_list), i + 1) if len(file1_list) != len(file2_list): compare(len(file2_list), 0) print("Final Length", len(file2_list)) -
lauching pipenv shell creates a subshell in the wrong directory
MacBook-Pro-van-Ferry:voorbeeld ferryholzhaus$ pipenv shell Launching subshell in virtual environment... . /Users/ferryholzhaus/.local/share/virtualenvs/ferryholzhaus-AnfvKXxr/bin/activate Restored session: vr 19 mrt 2021 11:52:49 CET ferryholzhaus@MacBook-Pro-van-Ferry ~ % . /Users/ferryholzhaus/.local/share/virtualenvs/ferryholzhaus-AnfvKXxr/bin/activate (ferryholzhaus) ferryholzhaus@MacBook-Pro-van-Ferry ~ %