Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cant add slug, in django admin, using pre_save or save() admin form throws error
I have been trying too ad a slug field to my post model, in django. For the slug field i want to use a unique slug function, i have been trying to run it using both signals and overriding the save methods, but in either case the form gets invalidated in the admin page before its changed in the form. The form is invalidated both when slug is empty or when its not unique. Image from the admin rejecting the change My models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from .utils import unique_slug_generator class Post(models.Model): post_type = models.CharField(max_length=100, default='npc') title = models.CharField(max_length=100) slug = models.SlugField(unique=True) description = models.TextField() content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slug_generator(self) return super().save(*args, **kwargs) The signal i was trying instead from django.db.models.signals import pre_save from .utils import unique_slug_generator from django.dispatch import receiver from .models import Post @receiver(pre_save, sender=Post) def pre_save_post_receiver(sender, instance, *args, **kwargs): print("post reciver slug") if not instance.slug: instance.slug = unique_slug_generator(instance) And the unique slug generator i am trying to run from django.utils.text import slugify import random import string def random_string_generator(size=10, chars=string.ascii_lowercase … -
ckeditor_uploader stop working after deploy static files in google cloud storage
i work on a django app and right after i deploy the static files on google clouds the ckeditor and ckeditor_uploader stop working but every other static is working perfectly ckeditor settings : CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { 'default': { 'width': 'auto', 'toolbar': None, }, 'simple': { 'width': 'auto', 'toolbar': [ ['Undo','Redo','Find','Replace'], ['Bold','Italic','Underline','Strikethrough','Subscript','Superscript'], ['Link','Unlink'], ['Blockquote','TextColor'], ['Format','Font','Size'], ['Maximize'] ], }, } static and media and google cloud settings : STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "static/media/") ''' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] ''' # CONFIG # Google BUCKETS CONFIG # google credential from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR,'googlekey.json') ) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = '*****' GS_PROJECT_ID = '******' GS_DEFAULT_ACL = None GS_FILE_OVERWRITE = False GS_LOCATION = '' #MEDIA_URL = f'https://storage.googleapis.com/{GS_BUCKET_NAME}/' i ran 'python manage.py collectstatic' to upload all the files to google cloud if i remove google settings ckeditor run again without google settings with google settings -
AuthCanceled at /complete/azuread-tenant-oauth2/
I am using python social auth https://python-social-auth.readthedocs.io/en/latest/ and Azure backend https://python-social-auth.readthedocs.io/en/latest/backends/azuread.html for o365 login. However after entering all correct credentials i get authentication cancelled My error stack is below: Internal Server Error: /complete/azuread-tenant-oauth2/ Traceback (most recent call last): File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/utils.py", line 251, in wrapper return func(*args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/oauth.py", line 395, in auth_complete response = self.request_access_token( File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/oauth.py", line 373, in request_access_token return self.get_json(*args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/base.py", line 238, in get_json return self.request(url, *args, **kwargs).json() File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/base.py", line 234, in request response.raise_for_status() File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/requests/models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://login.microsoftonline.com/common/oauth2/token During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_django/views.py", line 31, in complete return do_complete(request.backend, _do_login, user=request.user, File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/actions.py", line 45, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/utils.py", line 254, in … -
Problem finding .env with WSGI using Django stack with dotenv
I have a Django app and I'm trying to secure my SECRET_KEY using dotenv. manage.py runserver works just fine but the site hosted with apache2 does not work and apache give me the error log: mod_wsgi (pid=32200): Failed to exec Python script file '/opt/bitnami/projects/accuhx/accuhx/wsgi.py'. mod_wsgi (pid=32200): Exception occurred processing WSGI script '/opt/bitnami/projects/accuhx/accuhx/wsgi.py'. Traceback (most recent call last): File "/opt/bitnami/projects/accuhx/accuhx/wsgi.py", line 23, in <module> application = get_wsgi_application() File "/opt/bitnami/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/bitnami/python/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 196, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I'm assuming this is because my manage.py can find the .env but the wsgi.py cannot, but I have no idea why. My structure: accuhx | |-manage.py |-accuhx | | | |-settings.py |-.env |-wsgi.py WSGI.py: import os import dotenv from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accuhx.settings') application = get_wsgi_application() manage.py def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accuhx.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and … -
Presave form instance in order to use its many-to-many field Django
I am inheriting from CreateView and want to redefine it's form_valid() method so I could manually create relations between two models in my many-to-many field. My class looks like this: class CreateRecipe(CreateView): template_name = 'create_recipe.html' form_class = CreateRecipeForm success_url = reverse_lazy('index') def form_valid(self, form): recipe = form.save(commit=False) recipe.author = self.request.user ingredients = [self.request.POST[name] for name in self.request.POST.keys() if 'nameIngredient' in name] queryset = Ingredient.objects.filter(name__in=ingredients) for obj in queryset: recipe.ingredients.add(obj) slug = slugify(to_lower=True) recipe.Slug = slug(form.cleaned_data['name']) form.save_m2m() return super().form_valid(form) It returns an error which basically says that I first need to assign id to my recipe object before using it's many-to-many field. Isn't form.save(commit=False) what does that? I thought it was equal to: object = MyModel() so that you can assign values to it but it ain't actually saved unlike Model.objects.create(). How can I properly presave form instance to use it's many-to-many field? Thank you. -
Page not found "search/" Django
i'm trying to add a search bar to my project, i installed a Postgresql docker image, when i try to enter to http://127.0.0.1:8000/search/ i get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/search/ Raised by: blog.views.post_detail No Post matches the given query. this is my view: def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Post.published.annotate( search = SearchVector('title', 'body') ).filter(search=query) context = {'form': form, 'query': query, 'results': results} return render(request, 'blog/post/search.html', context) this is my search.HTML (i made it this easy to see if i can enter the page): {% extends "blog/base.html" %} {% block title %}Search{% endblock %} {% block content %} <h1>Search for posts</h1> <form method="get"> {{ form.as_p }} <input type="submit" value="Search"> </form> {% endblock %} this is my urls.py: from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), path('new_post/', views.new_post, name='new_post'), path('<slug:post_slug>/', views.post_detail, name='post_detail'), path('<slug:post_slug>/share/', views.post_share, name='post_share'), path('edit_post/<slug:post_slug>/', views.edit_post, name='edit_post'), path('delete_post/<slug:post_slug>/', views.delete_post, name='delete_post'), path('search/', views.post_search, name='post_search'), ] the problem should be on urls.py i guess, but not sure at all.. -
Is there a way to dynamically add django models/permissions
I have no idea how to solve this. I would like to have users give permissions to other users in a dynamically created "folder". For example, an editor makes a private folder called Newspaper (creates a new private dynamic link /Newspaper with some templates). He edits one of the templates and saves it to the db. He wants another user to be able to check and edit the template or upload new files etc. He gives another user in the app permissions to do so. How do I assign these edit permissions to a person, while the link was dynamically created by another user? Do I need a dynamic model or is there an easy fix? -
Query in production (https) does not work, while query in development server (http) does
When I run this in development the query returns the objects, when I do the same code in production on the server, there is nothing to be found. The development environment is using the same DB. It's weird because other queries on my production site work fine... videofilter = Video.objects.filter(video=video_path) videoId = videofilter[0].id videoName = videofilter[0].name associatedvideo = Video.objects.get(id=videoId) # video is a url: https://s3-us-west-2.amazonaws.com/bucketName/5b732630-bf8c-4fb3-a392-9caaa80b9f33.jpg Is there an issue with https and S3? or is the production environment have rules about queries that are different than development? -
Problems with ElasticSearch integration
I added elasticsearch to my project, and almost everything works, but now I can't add community object through admin panel. When I am trying to do that I am getting strange error related to elasticsearch. I tried to google, but didn't find any useful information. Maybe some of you faced the same problem and know how to fix it. error documents.py community_index = Index('coms') community_index.settings( number_of_shards=1, number_of_replicas=0 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @community_index.doc_type class CommunityDocument(Document): id = fields.IntegerField(attr='id') title = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) class Django: model = communities_models.Community serializers.py class CommunityDocumentSerializer(DocumentSerializer): class Meta: document = communities_documents.CommunityDocument fields = ( 'id', 'title', ) views.py class CommunityViewSet(DocumentViewSet): document = communities_documents.CommunityDocument serializer_class = communities_serializers.CommunityDocumentSerializer lookup_field = 'id' filter_backends = [ FilteringFilterBackend, OrderingFilterBackend, DefaultOrderingFilterBackend, SearchFilterBackend, ] search_fields = ( 'title', ) filter_fields = { 'id': { 'field': 'id', 'lookups': [ LOOKUP_FILTER_RANGE, LOOKUP_QUERY_IN, LOOKUP_QUERY_GT, LOOKUP_QUERY_GTE, LOOKUP_QUERY_LT, LOOKUP_QUERY_LTE, ], }, 'title': 'title.raw', } ordering_fields = { 'id': 'id', 'title': 'title.raw', } ordering = ('id') and here is the apps that I used 'elasticsearch_dsl','django_elasticsearch_dsl','django_elasticsearch_dsl_drf', elasticsearch config ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' }, } -
Having error while installing pip install 'python-decouple'
Collecting python-decouple Using cached python-decouple-3.3.tar.gz (10 kB) Using legacy setup.py install for python-decouple, since package 'wheel' is not installed. Installing collected packages: python-decouple Running setup.py install for python-decouple ... error ERROR: Command errored out with exit status 1: command: 'c:\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple\setup.py'"'"'; file='"'"'C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\slms_\AppData\Local\Temp\pip-record-aljfw6bc\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\python38\Include\python-decouple' cwd: C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple Complete output (16 lines): running install running build running build_py creating build creating build\lib copying decouple.py -> build\lib running egg_info writing python_decouple.egg-info\PKG-INFO writing dependency_links to python_decouple.egg-info\dependency_links.txt writing top-level names to python_decouple.egg-info\top_level.txt reading manifest file 'python_decouple.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'python_decouple.egg-info\SOURCES.txt' running install_lib byte-compiling c:\python38\Lib\site-packages\decouple.py to decouple.cpython-38.pyc error: [Errno 13] Permission denied: 'c:\python38\Lib\site-packages\pycache\decouple.cpython-38.pyc.2802584858032' ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple\setup.py'"'"'; file='"'"'C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\slms_\AppData\Local\Temp\pip-record-aljfw6bc\install-rec -
Pip install commands error ConnectTimeoutError
I am trying to install Django 1.8.11 on my Windows 10 PC, but i am getting this error when run pip install django==1.8.11: Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001CE97C60D68>, 'Connection to xxxx.xxxx.xxx.xx timed out. (connect timeout=15)')': /simple/pip/ (xxxx.xxxx.xxx.xx Is an address that I use as proxy some times) I have Python version: 3.5.4 and pip version: 9.0.1 I have checked proxy settings with netsh winhttp show proxy Current WinHTTP proxy settings: Direct access (no proxy server). I am not behind any corporate proxy My system proxy settings are Automatically detect settings -> ON Use setup script -> OFF Use a proxy server -> OFF Also tried ping pypi.python.org Ping statistics for 151.101.4.223: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 92ms, Maximum = 102ms, Average = 95ms So, I have access to the internet Also i removed temp files If anyone knows where is that xxxx.xxxx.xxx.xx configured so I can remove it, don't know what else to do. -
Stripe Change Database Entry When Trial Ends
I have a database table 'User Memberships' with a column called 'Membership' where the values in that column could either be 'Free', 'Monthly', 'Yearly'. 'Free' is a free non-paying membership while 'Monthly' and 'Yearly' are paid memberships. Username |Customer id|Membership -------------------------------- testuser1|cust_id1 |Free testuser2|cust_id2 |Monthly testuser3|cust_id3 |Yearly When a user has a Stripe trial, I have to manually go into my database and change the user's 'Membership' column value to a paid membership value ('Monthly', 'Yearly') to give them temporary access to paid content. But there is no way to automatically change the database value from either 'Monthly' or 'Yearly' back to 'Free' as soon as the trial ends for that user. There are 2 scenarios where I would give a customer a trial. When they are already paying member and they want to pause payment on their account temporarily (where I do not want to change them back to 'Free' after their trial ends and instead keep them at 'Monthly' or 'Yearly'). Or they are a 'Free' customer and they want to try out the paid service temporarily (where I do want to change them back to 'Free' when their trial ends). I would like it to be done … -
DRF Validation: Unclear Generic Errors
I occasionally get this very generic DRF validation error that doesn't seem to be attached to a particular field. Does anyone know how to debug it, or make it more specific? In more complex serializers it becomes almost impossible to find the root cause. { "required": "This field is required.", "null": "This field may not be null.", "invalid": "Invalid data. Expected a dictionary, but got {datatype}." } -
Form as template tag using ModelChoiceField doesn't populate
I have a problem with a form a created with Django. Actually, it display but isn't populated by any data. I suppose there's some workaround with form.media but I don't know how to do. form displayed class SearchForm(forms.ModelForm): produit = forms.ModelChoiceField( empty_label='Produit', queryset=Product.objects.all(), widget=autocomplete.ModelSelect2(url='product-autocomplete') ) class Meta: model = Product fields = () I made a view class ProductAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): query_set = Product.objects.all() if self.q: query_set = query_set.filter(product_name_fr__istartswith=self.q) return query_set.order_by('product_name_fr') And his url urlpatterns = [ path( 'product-autocomplete/', ProductAutocomplete.as_view(model=Product), name='product-autocomplete' ), ] I want to make it a template tag to use it through all my template. So I made: class NavbarSearchNode(template.Node): def __init__(self): self.form = SearchForm() def render(self, context): return self.form @register.tag(name='navbar_search') def navbar_search(parser, token): return NavbarSearchNode() And inserted in HTLM base file like that base file But the only data in my form is the one in empty_label property. Any idea? -
Django Heroku raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
I am getting 500 server error because there seems to be an issue with my static files: my project folder name is register and I have different setting files for production and development: register --live-static --register ----settings ------__init__.py -----common.py -----production.py -----development.py --live-static --static In my production.py file I have: from register.settings.common import * STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'live-static', 'media-root' I have already ran: python manage.py collect static heroku run python manage.py collectstatic and I got the following result: 1626 static files copied to '/app/live-static/static-root', 4464 post-processed. However, after I visit my website I get an error: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) 2020-09-07T19:46:28.324481+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'css/main.css' in my template I have {% static 'css/main.css' %} I do not know why i am still getting an error as my collect static has already worked properly. I'd appreciate any help. -
error : 'Processus' object has no attribute 'outil_set' - django
hello I want to show the 'outils' in my 'Processus' so in my views I did something like that : def processus(request, pk_test): processus = Processus.objects.get(id=pk_test) outils = processus.outil_set.all() total_outils = outils.count() context={ 'processus':processus, 'outils':outils, 'total_outils':total_outils, } but it doesn't work it show an error 'Processus' object has no attribute 'outil_set' this is my models.py class outil(ressource): nom_outil = models.CharField(max_length=250) proprieté = models.CharField(max_length=250) technique_id = models.ForeignKey(technique, on_delete = models.CASCADE) def __str__(self): return self.nom_outil class Processus(models.Model): nom = models.CharField(max_length=250) proprieté = models.CharField(max_length=250) outils = models.ManyToManyField(outil) def __str__(self): return self.nom -
jQuery Datatables rendered with django ordering not working
I can't seem to get this table to order on click. The app is retrieving a table from Django and rendering it successfully. But when I go ahead and click the arrows at the top of the table columns, a box says 'processing' but no reordering happens. When I disable serverSide programmatically so that it should only happen the first time, the ajax call happens anyway. $(document).ready( function () { $.fn.dataTable.ext.errMode = 'throw'; var table = $('#{{ grid_id }}').DataTable({ "paging": {{paging}} ,"searching": false ,"info": true ,"stateSave": false ,"orderable": true ,"ordering": true ,"processing": true ,"serverSide": true {% if ajax_url is not None %} ,"ajax": { /* "type": "POST", */ "url": "{{ ajax_url }}", "dataSrc": "results", "data": function (d) { d.customParam = "custom"; } }{% endif %}{% if column_list is not None %} ,"columns": [ {% for col in column_list %} { "title":"{{ col.title }}", "data": "{{ col.data }}" {% if col.href is not None %}, fnCreatedCell: function (nTd, sData, oData, iRow, iCol) { $(nTd).html("<a href='{{col.href}}"+oData.{{ col.href_data_attr }}+"'>"+oData.{{ col.data }}+"</a>");}{% endif %} },{% endfor %} ] {% endif %} }); }); -
DJANGO. form not working, button action is null
I am working on the checkout for an ecommerce site and everything is set but the form to choose the shipping and billing addresses before filling the credit card info. I have no clue why the form is not working, its not passing any data nor performing any action. The 3 data fields that I am passing are saved to an existing order model which already contains info like price, products, etc. The order model works perfectly fine as well as everything else in the site. This is the form in my template: <form method="POST" name="check_address"> {% csrf_token %} <div> <h4 class="mb-3">Dirección de envío</h4> {% if shipping_addresses %} <div class="list-group form-group mb-2"> {% for address in shipping_addresses %} <a class="list-group-item list-group-item-action flex-column align-items-start"> <div class="d-flex w-100 justify-content-between"> {% if request.user.defaultaddresses.shipping.id == address.id %} <input type='radio' name="shipping_address" form="check_address" value="{{address.id}}" checked> {% else %} <input type='radio' name="shipping_address" form="check_address" value="{{address.id}}"> {% endif %} <h5 class="mb-1">Dirección</h5> </div> <p class="mb-1">{{address.street_address}}{% if address.apartment_address %} {{address.apartment_address}}{% endif %}</p> <small class="text-muted">{{address.get_city}}</small> </a> {% endfor %} </div> <div id="collapseTwo" class="collapse mt-3 mb-3"> <h5 class="mb-3">Nueva dirección de envío</h5> {% include 'snippets/addressform.html' %} </div> {% else %} {% if address_form %} {% include 'snippets/addressform.html' %} {% endif %} {% endif %} … -
I am using celery beat in django to schedule periodic tasks. Django ==2.0
File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django_celery_beat/models.py", line 567, in save super(PeriodicTask, self).save(*args, **kwargs) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/base.py", line 769, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in send for receiver in self._live_receivers(sender) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in for receiver in self._live_receivers(sender) File "/home/yash/Desktop/er/erp_back/erp/erp/middleware/middleware.py", line 132, in create_user_profile if not 'LogRecord' in str(instance): File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django_celery_beat/models.py", line 581, in str if self.interval: File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 158, in get rel_obj = self.field.get_cached_value(instance) File "/home/yash/Documents/erp_notify/env/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] AttributeError: 'PeriodicTask' object has no attribute '_state' -
Django channels username sender
i new to django channels , i followed the documentation tutorial and i made a django chat room , so far i can send and recieve messages , but the probleme here the sender is unknown , i tryied to send the username but its not working , i get the username printed in the server but in the front i get the actual login username?? i am confused ? consumer.py : class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name self.user = self.scope["user"] # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] print(self.user.username) # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username' : str(self.user.username), })) room.html : <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <div style="width:800px; margin:0 auto;">username : <a id="username" href="">{{ user.get_username }}</a> <textarea id="chat-log" cols="100" … -
How to add @property auto calculation part in django to mysql
In django I created some auto calculation parts using @property function. While I was connected to dbsqlite3 it showed the calculated amounts. But when I change the database to mysql database it is not adding the calculation part in database. class leave(models.Model): leave_id = models.CharField(max_length=20, primary_key=True, default="") emp_det_id = models.ForeignKey( 'emp_details', models.DO_NOTHING, default="") l = ( ("Paid", "Paid"), ("Non-Paid", "Non-Paid") ) leave_type = models.CharField(max_length=50, choices=l, default="Non-Paid") m = ( ("January", "January"), ("February", "February"), ("March", "March"), ("April", "April"), ("May", "May"), ("June", "June"), ("July", "July"), ("August", "August"), ("September", "September"), ("October", "October"), ("November", "November"), ("December", "December") ) month = models.CharField(max_length=10, choices=m, default="January") year = models.CharField(max_length=4, default=2021) s = ( ("Accepted", "Accepted"), ("Pending", "Pending"), ("Canceled", "Canceled") ) status = models.CharField(max_length=10, choices=s, default="Pending") def __str__(self): return self.leave_id class salary(models.Model): sal_id = models.CharField(max_length=10, primary_key=True, default="") emp_det_id = models.ForeignKey('emp_details', models.DO_NOTHING, default="") dept_id = models.ForeignKey('department', models.DO_NOTHING, default="") basic_sal = models.IntegerField(default=0) extra_hours = models.IntegerField(default=0) bonus = models.IntegerField(default=0) @property def Extra_Payment(self): return self.extra_hours * 350 @property def get_leave_count(self): leaves = salary.objects.filter(emp_det_id=self.emp_det_id, emp_det_id__leave__month=self.month, emp_det_id__leave__year=self.year, emp_det_id__leave__status='Accepted').aggregate(leave_count=Count('emp_det_id__leave')) return leaves['leave_count'] @property def leave_amount(self): return self.get_leave_count * 500 @property def Total_Payment(self): return self.Extra_Payment + self.basic_sal + self.bonus - self.leave_amount m = ( ("January", "January"), ("February", "February"), ("March", "March"), ("April", "April"), ("May", "May"), ("June", "June"), ("July", … -
Django ORM. Joining subquery on condition
I have a table TickerStatement, which contains financial statements about companies class Statements(models.TextChoices): """ Supported statements """ capital_lease_obligations = 'capital_lease_obligations' net_income = 'net_income' price = 'price' total_assets = 'total_assets' short_term_debt = 'short_term_debt' total_long_term_debt = 'total_long_term_debt' total_revenue = 'total_revenue' total_shareholder_equity = 'total_shareholder_equity' class TickerStatement(TimeStampMixin): """ Model that represents ticker financial statements """ name = models.CharField(choices=Statements.choices, max_length=50) fiscal_date_ending = models.DateField() value = models.DecimalField(max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES) ticker = models.ForeignKey(Ticker, on_delete=models.CASCADE, null=False, related_name='ticker_statements') And now I'm trying to calculate a multiplier. The formula looks like: (short_term_debt + total_long_term_debt) / total_shareholder_equity I wrote a raw SQL query SELECT "fin_tickerstatement"."fiscal_date_ending", t2.equity AS "equity", value AS "debt", short_term_debt AS "short_term_debt", (value + short_term_debt) / t2.equity AS "result" FROM "fin_tickerstatement" JOIN (SELECT "fin_tickerstatement"."fiscal_date_ending", fin_tickerstatement.value AS "equity" FROM "fin_tickerstatement" WHERE ("fin_tickerstatement"."ticker_id" = 12 AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03' AND "fin_tickerstatement"."name" = 'total_shareholder_equity') GROUP BY "fin_tickerstatement"."fiscal_date_ending", fin_tickerstatement.value ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC) t2 ON fin_tickerstatement.fiscal_date_ending = t2.fiscal_date_ending JOIN (SELECT "fin_tickerstatement"."fiscal_date_ending", fin_tickerstatement.value AS "short_term_debt" FROM "fin_tickerstatement" WHERE ("fin_tickerstatement"."ticker_id" = 12 AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03' AND "fin_tickerstatement"."name" = 'short_term_debt') GROUP BY "fin_tickerstatement"."fiscal_date_ending", fin_tickerstatement.value ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC) t3 ON fin_tickerstatement.fiscal_date_ending = t3.fiscal_date_ending WHERE ("fin_tickerstatement"."ticker_id" = 12 AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03' AND "fin_tickerstatement"."name" = 'total_long_term_debt') GROUP BY "fin_tickerstatement"."fiscal_date_ending", equity, debt, short_term_debt ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC; and … -
Is it possible to let a user choose how many fields to be filled?
I am planning to do an application with Django where the user shall inform how many columns and which data types will be submitted through a CSV file. I know I can define, in the views.py, formats, create MultiValueFields, and have the CSV content into a JSONField in the database. But the ideal would have to have individual tables for each informed CSV, in the database, because I will need to access specific parts of that data many times and I fear eventually extracting a lot of JSON dictionaries and processing the whole data chunck to pick parts of it will not scale well. As for what I know, a Model you write on models.py, is a role model for Django to create specific columns on the database table, through makemigrations and migrate commands. As it is a pretty static and reliable way on functioning, it really is bugging me if it is not possible to dynamically allocate data. I have already thought on two ways of doing it, while still using Django: To create a model with a lot of ModelFields, each of them not being required to be filled and NULL as default value; The JSONField solution. But … -
querying my objects from db using profile id
` class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) full_name = models.CharField(max_length=200, null=False) image = models.ImageField(default='default.jpg', upload_to='profile_pics') date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class Course(models.Model): title = models.CharField(max_length=200, null=False) description = models.CharField(max_length=200, null=False) tutor = models.ForeignKey(Tutor, on_delete=models.CASCADE) students = models.ManyToManyField(Student) def __str__(self): return self.title def Courses(request): current_user = request.user print(current_user.id) courses = Course.objects.filter(students__id=current_user.id) return render(request, 'e-learning/courses.html', {'courses':courses}) `I have a model student that is related to a model course via many to many relationship. i want to query all the courses related to the current logged in user, who is a student. -
Heroku Connection increase unreasonably
I am new to Heroku. I am currently using the free tier which has limited to 20 connection. I deployed a wsgi (postgres) and redis app (Django back-end) to Heroku. I am facing a weird issue where there is only one user using it but the connection keep increasing and even the app is killed, the connection is still there. May i know what is the root cause of this problem? The connection increases even the chat is not perform but just using simple API.