Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get static files to work in Django | Favicon not getting loaded but appears when entering that directory
I'm having trouble trying to get my static files to work, I've already tried different answers for a long time and I'm getting confused what's the problem. I was trying to load my css with debug turned off, but I think its normal for the css not to appear since django doesn't load static files with debug turned off. My problem was when trying to put a favicon into my test website. I also think in the future I'll have complications with JS, etc.. main.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello, Django</title> <!-- load staticfiles--> <link rel="stylesheet" href="{% static 'main.css' %}"> <link rel="shortcut icon" href="{% static "favicon.ico" %}}" type="image/png"> </head> <body> </body> </html> urls.py from django.urls import path from f1trackerapp import views from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView urlpatterns = [ path("", views.f1trackerapp, name="f1trackerapp"), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('favicon.ico'))) ] settings.py (stackoverflow doesn't let me post full settings.py code) ... from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
How do I make Django add the plural of category as categories instead of categorys
In my Django project I have a category tables however the plural is showing at categorys is there a way to force categories instead? I tried renaming the table but that did not work I also tried manually changing this by changing my model however I receive the same -
HTML does not recognize CSS file - Django
I recently started working on my first python + django project and I'm working on some visual things, but I noticed that the HTML isn't recognizing my CSS file. I follow the documentation about How to manage static files but nothing worked. So, this is my settings.py #app definition INSTALLED_APPS = [ #personalizacao #'grappelli', #Configuraçoes principais 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] #statics configs STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', # 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9 ) In my HTML I have {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> And I can call the stuff that I have on the static/img folder with no problem So does anyone know what can it be? I don't know where to look anymore -
AWS EC2 Django Requests working from Public ipv4 address, but not Public ipv4 DNS address
Running a django project on an ubuntu 22.04 instance on a new account including a default VPC. Using a custom security group with 3 inbound rules: ipv6(http) on port 80, ipv4(http) on port 80, and ipv4(ssh) on port 22. Outbound rule is the same as default, ipv4(all) on all ports. No key pair was set. Running with gunicorn, nginx, and supervisor. sudo nginx -t shows no issues, supervisor err logs are empty. /var/log/nginx/access.log shows that the api is receiving requests from both sites with no difference in the logs besides codes 200 29 for the successful request from the public ipv4, and codes 404 197 for the failed request from the public ipv4 DNS. It's also worth noting that the public ipv4 DNS serves the default nginx page on the base url while the public ipv4 shows resource not found. There are no relevant errors in /var/log/nginx/error.log. -
Why is Heroku not updating my Django app's code?
I have a Django blog deployed by Heroku, statics served with S3 Bucket. A few days ago I realised that my changes are not shown in the actual code when I inspect it with Chrome's Inspector tool. I pushed them to the git repo and to heroku master. This project is for my thesis, so it would be really important to resolve this problem. Thank you very much to spend your time helping me in advance. This is one of my latest changes: Added a paragraph to a django signup form that the user can view my Privacy Policy before signing up to my blog. I attached the code from PyCharm: {% extends 'default.html' %} {% block content %} <h1>Signup</h1> <form class="site-form" action="/accounts/signup/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Signup"> </form> <!-- Privacy Policy Link --> <p>By signing up, you agree to our <a href="https://www.termsfeed.com/live/d0e2bb42-feca-4abe-8051-afccfe402f6a">Privacy Policy</a>.</p> {% endblock %} The code from the actual website with Google's Inspector tool: <form class="site-form" action="/accounts/signup/" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="1P17fSXi3R2ihBMd17GqUPmx2pIsL4c855BnGwrhTbenlx4sKQea1nJTuCK0Apei"> <label for="id_username">Username:</label><input type="text" name="username" maxlength="150" autofocus="" required="" id="id_username" data-siid="si_input_0"><br><span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span> <label for="id_email">Email:</label><input type="email" name="email" required="" id="id_email" data-siid="si_input_1"> <label for="id_password1">Password:</label><input type="password" name="password1" … -
AWS EC2 instance public ipv4 DNS address pointing to private ipv4 address instead of public ipv4 address
Running a django project on an ubuntu 22.04 instance on a new account including a default VPC. Using a custom security group with 3 inbound rules: ipv6(http) on port 80, ipv4(http) on port 80, and ipv4(ssh) on port 22. Outbound rule is the same as default, ipv4(all) on all ports. No key pair was set. Running with gunicorn, nginx, and supervisor. sudo nginx -t shows no issues, supervisor err logs are empty, and accessing the api through the public ipv4 address http://xx.xxx.xx.xxx works properly, serving content when requested, with the base url showing Not Found. Accessing through the private ipv4 address does not respond. The problem is that when accessing through the public ipv4 DNS address, http://ec2-xx-xxx-xx-xxx.us-east-2.compute.amazonaws.com, where the x values match the public ipv4 address, the site only serves the default nginx page. Running nslookup on the DNS address returns the private ipv4 address. Why doesn't the DNS address point to the public ipv4 address? And why does it serve content at all if it points to the private ipv4 address which doesn't respond? Here are the configurations I used for nginx: Changed nginx.conf user to root, and created/linked django.conf in /etc/nginx/sites-available and /etc/nginx/sites-enabled: `server{ listen 80; Server_name [public … -
Onion site not found - Ubuntu 22.04.3 LTS / Unicorn / nginx / ufw / Dango .. on tor
Django web site does not happen to be accessible .. this is the simple demo django website. As this an onion V3, i increased the bucket size torrc HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 80 127.0.0.1:8080 Django settings ALLOWED_HOSTS = ['localhost', 'hxzr2qtoxsmmoyywkgnp6ehf5afnqxhj7aeh5iw63hyxicxapiokbpyd.onion'] Local tests are ok file /run/gunicorn.sock sudo systemctl status gunicorn curl --unix-socket /run/gunicorn.sock localhost Config Nginx sudo nano /etc/nginx/sites-available/sooshee server { listen 80; server_name hxzr2qtoxsmmoyywkgnp6ehf5afnqxhj7aeh5iw63hyxicxapiokbpyd.onion; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/dj_test; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } cat /etc/nginx/nginx.conf server_names_hash_bucket_size 128; I just changed the bucket size to comply with onion length The only information i find, is this error message below sudo journalctl -u nginx кас 05 19:44:44 dave-MINI-S nginx[27984]: nginx: configuration file /etc/nginx/nginx.conf test failed кас 05 19:44:44 dave-MINI-S systemd[1]: nginx.service: Control process exited, code=exited, status=1/FAILURE кас 05 19:44:44 dave-MINI-S systemd[1]: nginx.service: Failed with result 'exit-code'. кас 05 19:44:44 dave-MINI-S systemd[1]: Failed to start A high performance web server and a reverse proxy server. кас 05 20:25:47 dave-MINI-S systemd[1]: Starting A high performance web server and a reverse proxy server... кас 05 20:25:47 dave-MINI-S nginx[28269]: nginx: [emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 64 кас … -
Django cripsy form with a custom template for button
I have a need for a <button> element for my form submit instead of the layout helper Submit() input with Django and django-crispy-form. If I use {{ my_form|crispy }} I'm able to do this. However, with this method all of the other layout elements in the form are ignored. If I switch back to {% crispy my_form %} I get the layout back, but then my custom HTML button is ignored. Is there any way to have a custom HTML submit button while using the Layout helper? Note: If I add the HTML button below the crispy tag the button renders outside of the form, and I cannot iterate through the form fields in the template because my Layout in the Django form is very complex. -
React chat app messages don't have different className
I am making a chat app with django channels and react. I save the messages in state. When a new message is made I want it to have the className of the current user. The problem is that all messages have the className of the user reading them even if they were written from other. For example I am sending messages from 2 different browsers. The one is logged as first and the other as second. If first sends a message it will appear with a className of first. But for second this message will appear with a className of second chatSocket.onmessage = function(e) { if (ran == true) { const data = JSON.parse(e.data); setMessages(old => [...old, <p ref={oneRef} id={currentUser[0]?.username} className={currentUser[0]?.username}>{data.message}</p>]) } } What can I do to solve this. -
Cannot reach Postgres Flexible Server from Web App
I have a Django app to deploy with a pipeline in azure DevOps and deploy To Azure cloud resources. The Django database is a Postgres Flexible Server in the same resource group. Also I have a virtual network resource in the Group. The pipeline install dependencies and then exec the tests from a command in a Makefile. In the tests step the Django app cannot reach the Database server, the name doesn't resolve to an IP, I try with the server Ip and get the same error. I didn't set any firewall rule neither private endpoints -
custom django signal receiver not being called wagtail code
We have a custom receiver connecting to the task_submitted signal in a project app. I have verified that the receiver is added to the dispatcher receivers Locally the receiver is invoked, however when deployed to our staging evnvironment in cloud foundry in a docker container the receiver is not invoked According to a log the self.receivers is None when invoking the dispatcher.send method ? -
how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5
how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 Not type it every time, just launch it with ctrl f5 how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 how to start ./manage.py runserver faster? Not type it every time, just launch it with ctrl f5 -
passenger output: /bin/sh: line 0: exec: python: not found
I am trying to run django app I followed https://support.plesk.com/hc/en-us/articles/12377516625559. on Plesk Obsidian Version 18.0.41 Centos when logged in with root or my user python is aliased and responding I tried adding python to any basrc Any idea Thanks in advanced bellow is a detailed of the log level 7 App 174090 output: + '[' -x /usr/bin/id ']' App 174090 output: + '[' -z 10008 ']' App 174090 output: ++ /usr/bin/id -un App 174090 output: + USER=shlomi App 174090 output: + LOGNAME=shlomi App 174090 output: + MAIL=/var/spool/mail/shlomi App 174090 output: + '[' 10008 = 0 ']' App 174090 output: + pathmunge /usr/local/sbin after App 174090 output: + case ":${PATH}:" in App 174090 output: + pathmunge /usr/sbin after App 174090 output: + case ":${PATH}:" in App 174090 output: ++ /usr/bin/hostname App 174090 output: + HOSTNAME=localhost.localdomain App 174090 output: + HISTSIZE=1000 App 174090 output: + '[' '' = ignorespace ']' App 174090 output: + export HISTCONTROL=ignoredups App 174090 output: + HISTCONTROL=ignoredups App 174090 output: + export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL App 174090 output: + '[' 10008 -gt 199 ']' App 174090 output: ++ /usr/bin/id -gn App 174090 output: ++ /usr/bin/id -un App 174090 output: + '[' psacln = shlomi … -
Is it normal that Django ORM makes a DB call on every object in a List View?
I'm facing a problem of extra DB calls to retrieve object's data. I have a model: class Post(models.Model): profile = models.ForeignKey(Profile, related_name="posts", on_delete=CASCADE) project = models.ForeignKey(Project, related_name="posts", on_delete=CASCADE) body = models.TextField(verbose_name="Content", max_length=1300) liked_by = models.ManyToManyField(Profile, related_name="post_likes", blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="Date published") date_modified = models.DateTimeField(auto_now=True, verbose_name="Date modified") is_active = models.BooleanField(verbose_name="Active", default=True) tags = TaggableManager(blank=True, related_name="posts") I am calling a View to list all Post objects (currently, there are 4) but getting 4 extra queries to posts_post for each entity. Is that normal behaviour to make an individual DB call on each entity in DB (not related entities but the root entities). My query : all_posts = ( Post.objects .select_related("profile__specialization", "project") .prefetch_related( "tags", Prefetch( "liked_by", queryset=Profile.objects.select_related("specialization").only( "id", "username", "first_name", "last_name", "photo", "specialization" ) ) ) .annotate( comments_count=Count("comments", distinct=True), likes_count=Count("liked_by", distinct=True) ) .defer("body") .order_by("-date_published") ) My query list as per DjDT: -
ModuleNotFoundError: No module named 'storages'
I no idea why this error kept occur in my terminal my current django version, 4.2.3 python version, 3.10.6 and my virtual environment is on, and I did downloaded these pip pip install boto3 pip install django-storages and my settings.py INSTALLED_APPS=[ ... 'storages', ] and DEFAULT_FILE_STORAGE='storages.backends.s3boto3.S3Boto3Storage' ok then, I try to run my server, python manage.py runserver it came out these error ** Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python latest\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python latest\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Python latest\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import … -
Django reloading a page without loosing user inputs in a form
I am working on translating my Project. I implemented a language Switch in my basetemplate: {% load i18n %} {% load language_tags %} <!-- imports all tags from templatetags/language_tags.py (see below) --> ... <div class="collapse navbar-collapse justify-content-end" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {% translate 'Language' %} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as langs %} {% for lang in langs %} <li><a class="dropdown-item" href="{% translate_url lang.code %}">{{lang.name_local}}</a></li> {% endfor %} </ul> </li> </ul> </div> ... The important part here ist the href={% translate_url lang.code %} It is a custom template tag (see templatetags/language_tags.py) in my projetc that i have from here: https://stackoverflow.com/a/17351858/21828018 It's usage ({% translate_url de %}) is to give back the url you are visiting in the given language e.g. if you are visiting en/product/product_id and you use {% translate_url de %} it returns de/product/product_id. In combination with i18n_patterns the translation works so far. templatetags/language_tags.py: """language_tags.py""" from django import template from django.urls import reverse, resolve from django.utils import translation from django.conf import settings register = template.Library() class TranslatedURL(template.Node): """gets current path and creates new url with passed … -
Django .aggregate() on prefetched element not filtering by date
I have a queryset that I am prefetching entries between a range of dates, I am trying to annotate the totals of the prefetched elements into the outer element. When I call .annotate() on the outer element the filtered date ranges do not pass through. How do I fix this? GLAccount.objects.prefetch_related( Prefetch('general_ledger', queryset=GeneralLedger.objects.select_related( ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__gte=start_date, date_entered__date__lte=end_date)), ).filter(account_identifier='1011.00').annotate(Sum('general_ledger__credit_amount')) The annotated value grabs all general ledger entries from the start of time. -
Master Ref ID is not working as expected in Details Table
I am getting this error message: {"status":400,"message":{"reason_items":[{"master_ref_id":["This field is required."]}]}} master_ref_id isn't supposed to be passed in postman(Details Table gets connected to Masters Table by master_ref_id which is autogenerated). But When I manually give master_ref_id, I get an obvious error: TypeError at /chargeback-reason/ django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() got multiple values for keyword argument 'master_ref_id' This is the data I am passing in postman for 'POST' request. { "name": "name3", "action_id": 1, "reason_items": [ { "attachement_format_id": 1, } ] } serializer.py file class ChargeBackReasonDetailsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = ChargeBackReasonDetails fields = '__all__' class ChargeBackReasonSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) reason_items = ChargeBackReasonDetailsSerializer(many=True) class Meta: model = ChargeBackReason fields = '__all__' def create(self, validated_data): item_row = validated_data.pop('reason_items') reason = ChargeBackReason.objects.create(**validated_data) for item in item_row: ChargeBackReasonDetails.objects.create(**item, master_ref_id = reason) return reason views.py file def create(self, request): with transaction.atomic(): data = dict(request.data) data['created_by'] = request.user.id data['updated_by'] = request.user.id data['updated_date_time'] = datetime.now(pytz.timezone(TIME_ZONE)) for item in data['reason_items']: item.update({'created_by':request.user.id,'updated_by':request.user.id,'updated_date_time':datetime.now(pytz.timezone(TIME_ZONE))}) serializer = ChargeBackReasonSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({STATUS: RECORD_CREATED}, status=status.HTTP_201_CREATED) else: return Response({STATUS: status.HTTP_400_BAD_REQUEST, MESSAGE: serializer.errors}, status=status.HTTP_400_BAD_REQUEST) models.py file class ChargeBackReason(models.Model): action_id = models.ForeignKey(ChargeBackAction, verbose_name="action_id", on_delete=models.PROTECT) name = models.CharField(max_length=100,verbose_name='name') class ChargeBackReasonDetails(models.Model): master_ref_id = models.ForeignKey(ChargeBackReason, verbose_name="Master Ref Id",related_name="reason_items",on_delete=models.PROTECT) attachement_format_id = models.ForeignKey(AllMaster,verbose_name="Attachement Format",on_delete=models.PROTECT)) -
Django Query loads for too long
i have an sqlite database for a cbt app and it is a small database with just over students registered. but when i query the database to get all the exams written, it takes over 2 minutes to load the query. i have used .select_related() but it's still so slow. i know sqlite is slow but i don't believe it's so slow def examination(request, id): courses = Course.objects.all().order_by('-pk') course = courses.filter(id=id).first() exams= Examination.objects.filter(course=course).select_related('student').order_by('-id') if (request.method == 'POST'): search = request.POST.get('search',None) if(search != None): return_url = return_url = reverse('user:examSearch', args=[id, search]) return redirect(return_url) paginator = Paginator(exams, 20) page = request.GET.get('page') try: exams = paginator.page(page) except PageNotAnInteger: exams = paginator.page(1) except EmptyPage: exams = paginator.page(paginator.num_pages) context ={ 'course': course, 'exams':exams, 'page': page, } return render(request, 'exam.html', context) Please what could be causing this performance issue? -
Django-MySql database error : png-config not found
/bin/sh: pkg-config: command not found /bin/sh: pkg-config: command not found Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 127. Traceback (most recent call last): I want to install mysqlclient package but when I do so I get this error -
Issue in Django Prefetching same objects, but with different dates
I know there has to be a simple way to get around this, but I am having an issue figuring it out. Overall I have a semi-complex Prefetch giving me general ledger entries between a specific date range. Works great, and gives me the data I need. However, now I need to figure out a calulation based on any date before the selected date range but I am unable to prefetch the items again, even while casting to_attr=... from those dates. The error I get is: lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups. So how would I take this query in the same queryset and filter by different dates? custom_report = AccountTree.objects.select_related().prefetch_related( 'account_tree_total', 'account_tree_regular', Prefetch('account_tree_header', queryset=AccountTreeHeader.objects.select_related( 'associated_account_from_chart_of_accounts', 'associated_total_account_tree_account__associated_account_from_chart_of_accounts' ).prefetch_related( 'associated_regular_account_tree_accounts', Prefetch('associated_regular_account_tree_accounts__associated_account_from_chart_of_accounts', queryset=GLAccount.objects.prefetch_related( Prefetch('general_ledger', queryset=GeneralLedger.objects.select_related( 'accounts_payable_line_item', 'accounts_payable_line_item__accounts_payable_entry', 'accounts_payable_line_item__property', 'accounts_payable_line_item__account', 'accounts_payable_line_item__book', 'journal_line_item', 'journal_line_item__journal_entry', 'journal_line_item__payment_id__code', 'journal_line_item__charge_id__code', 'journal_line_item__payment_id__balance', 'journal_line_item__charge_id__balance', 'journal_line_item__payment_id__balance__unit', 'journal_line_item__charge_id__balance__unit', 'journal_line_item__payment_id__balance__unit__building', 'journal_line_item__charge_id__balance__unit__building', 'journal_line_item__property', 'journal_line_item__account', 'journal_line_item__book', ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__gte=start_date, date_entered__date__lte=end_date).order_by('date_entered')), )), # duplicate query causing issue... Prefetch('associated_regular_account_tree_accounts__associated_account_from_chart_of_accounts', queryset=GLAccount.objects.prefetch_related( Prefetch('general_ledger', queryset=GeneralLedger.objects.select_related( 'accounts_payable_line_item', 'accounts_payable_line_item__accounts_payable_entry', 'accounts_payable_line_item__property', 'accounts_payable_line_item__account', 'accounts_payable_line_item__book', 'journal_line_item', 'journal_line_item__journal_entry', 'journal_line_item__payment_id__code', 'journal_line_item__charge_id__code', 'journal_line_item__payment_id__balance', 'journal_line_item__charge_id__balance', 'journal_line_item__payment_id__balance__unit', 'journal_line_item__charge_id__balance__unit', 'journal_line_item__payment_id__balance__unit__building', 'journal_line_item__charge_id__balance__unit__building', 'journal_line_item__property', 'journal_line_item__account', 'journal_line_item__book', ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__lt=start_date).order_by('date_entered'), to_attr='prior_general_ledger'), )), Prefetch('associated_total_account_tree_account__associated_account_from_chart_of_accounts', queryset=GLAccount.objects.prefetch_related( Prefetch('gl_manual_journal_entry', queryset=JournalLineItem.objects.select_related('property').filter( … -
Django serve static files e.g. favicon.ico without `{% load static %}`
I have successfully followed the popular solution for serving static files in Django: I have /myproject/myapp/static/favicon.ico I use <link rel="icon" href="{%static 'favicon.ico' %}" /> in my html template But if I omit the <link rel...> from html then the browser will by default try to GET /favicon.ico which predictably logs Not Found: /favicon.ico How can I tell Django "if anything in urlpatterns does not match the GET string, and that GET string matches a file within a certain directory, just serve that file"? (Then I would be able to write e.g. <script src="/script.js"> and have /myproject/myapp/static-or-wherever/script.js be served without using {% use static %} in a template -- e.g. if I browse to http://my-site.com/script.js manually.) -
how to change this thing in django
how to change this thing in django, then command manage.py runserver is executed. Add some information, for example the server's IP address, Server name, versions of the necessary programs, uptime, anything at all I don't know where to look -
How to add a ModelMultipleChoiceField to a model?
How can I display my model in ModelMultipleChoiceField I have models.py # Модель заказа class ProductsSet(models.Model): # Название набора id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID") name = models.CharField(max_length=200) products_set = models.ManyToManyField('ProductsInstance', related_name='sets') borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) created_date = models.DateField(null=True, blank=True) class ProductsInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID") product = models.ForeignKey('Products', on_delete=models.RESTRICT, null=True) И admin.py @admin.register(ProductsInstance) class ProductsInstanceAdmin(admin.ModelAdmin): list_display = ('product', 'price_for_client', 'borrower', 'coeff') list_filter = ('status','borrower',) fieldsets = ( (None, { 'fields': ('product', 'coeff', 'price_for_client', 'id') }), ('Availability', { 'fields': ('status', 'borrower') }), ) @admin.register(ProductsSet) class ProductsSetAdmin(admin.ModelAdmin): list_display = ('name', 'borrower', 'created_date', 'status', 'total_amount') fields = ['id', 'name', 'products_set', 'created_date', 'borrower', 'status', 'total_amount'] list_filter = ['borrower','created_date','status'] What does it look like for me now enter image description here And this is how I want it: enter image description here -
django if else template tag using object from with template tag
I have an if/else statement that determines which button will be displayed in my base.py template. From doing my research I think I am on the right path, but regardless of if the enddate field is null or populated, the endcast button displays. model: class Cast(models.Model): id = models.AutoField(db_column='Id') startdate = models.DateTimeField(db_column='StartDate') enddate = models.DateTimeField(db_column='EndDate') class Meta: managed = True db_table = 'Cast' verbose_name_plural = "Cast" get_latest_by = "pk" template block: <div class="top-button-container stickey-top"> {% with last=Cast.objects.latest %} {% if last.enddate %} <button type="button" class="btn btn-danger btn-lg btn-block"> <a class="nav-link" href="{% url 'caststart' %}">Start Cast</a> </button> {% else %} <button type="button" class="btn btn-danger btn-lg btn-block"> <a class="nav-link" href="{% url 'cast_end' %}">End Cast</a> </button> {% endif %} {% endwith %} </div> I was expecting the "start cast" button to render when the last objects enddate field is populated. The "end cast" button should render when the enddate field is none. It currently renders the "end cast" button regardless of the last objects enddate field value.