Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create a working production build for my django-rest site?
I've been running yarn build, but when I visit index.html I see not only <noscript>You need to enable JavaScript to run this app.</noscript>, but when I click a link on that page, I find that the pathing does not work. For example, when I click a link that would take me to a sign up page, I just get Your file was not found. The URLs are clearly different between the two pages, one being file:///C:/Users/icant/GitProjects/moodzaic/moodzaic_django/assets/bundles/index.html and the other just being file:///C:/signup. I want to say that something in production_settings.py needs to be changed, but some pointers would be appreciated~ -
How to parse request.body into json in django
When I use Postman to send a post request to my django server, I receive request.body like user=abc&pwd=123, not like a json And when I use my android app to send a post request to my django server, I also receive the request.body like user=abc&pwd=123 How can I parse this kind of format like user=abc&pwd=123 into json in python? -
django remote user (trusted connection on IIS)
I set up django for a trusted connection (remote user) on IIS but on the client side, it is always asking for the user to type the username and password on a pop up alert from browser. Does anyone knows how can I solve it? See the screenshot from the browser below: -
How to use Facebook's picture api in django template?
I got back {"picture": {"data": {"height": 50, "is_silhouette": false, "url": "https://platform-lookaside.fbsbx.com/platform/profilepic/foo", "width": 50}} from facebook api call but in my template for django I tried using <img src = "{{object.picture.data.url}}"> And nothing is showing up. The other fields works fine for the first_name and last_name but I couldn't get why it doesn't work D: -
django error cannot import name 'RemovedInDjango30Warning'
Guys im fairly new to Django and I just started working on a personal project and decided that ill-use pycharm (i think its related to the error, or not). when I run python manage.py runserverI get the error posted below. I did a bit of googling and looks like its caused by inconsistency with Django versions. I currently have Django 3.0 and I checked both globally and in the venv. I tried to start a project outside of py charm and im running into the same issue. idk what I need to do to start using Django again. Did anyone run into this? Is this because of pycharm? If so what can I do to fix the issue? (venv) aiden@aiden-XPS-15-9570:~/PycharmProjects/NewsAggregator$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/aiden/.local/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/aiden/.local/lib/python3.6/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen … -
Django + VueJS: POST 403 Forbidden - CSRF token missing or incorrect
I am running Django + Django REST framework in the backend and Vue.js in the frontend. GET requests work fine, POST requests via Postman/Insomnia also do, but POST requests via the Vue.js frontend return an error in the Browser console: POST http://127.0.0.1:8000/api/questions/ 403 (Forbidden) {detail: "CSRF Failed: CSRF token missing or incorrect."} This is how I get the CSRF token and then fetch a POST request: File: csrf_token.js: import Cookies from "js-cookie"; var CSRF_TOKEN = Cookies.get("csrftoken"); export { CSRF_TOKEN }; File: api.service.js: import CSRF_TOKEN from "./csrf_token.js"; async function getJSON(response) { if (response.status === 204) return ""; return response.json(); } function apiService(endpoint, method, data) { const config = { credentials: "same-origin", method: method || "GET", body: data !== undefined ? JSON.stringify(data) : null, headers: { "content-type": "application/json", "X-CSRFToken": CSRF_TOKEN } }; return fetch(endpoint, config) .then(getJSON) .catch(error => console.log(error)); } export { apiService }; MyComponent.vue: ... methods: { onSubmit() { apiService(endpoint, method, { content: this.content }) .then(response_content => { console.log(response_content) }); } } ... -
Can't install mysqlclient via pip on macOS Mojave 10.14.6
There are several related questions and answers on this topic. One would think I'd have found a solution in the several hours I've been trying to resolve this, but no luck. Installs fine in Ubuntu and WSL. Starting from scratch, this is what I've done (in a Python 3 venv): pip install mysqlclient As expected, this generates a lengthy error that can be abbreviated as: OSError: mysql_config not found brew install mysql so the mysql_config is "foundable" export PATH=$PATH:/usr/local/mysql/bin source ~/.bash_profile Try pip install mysqlclient again Another lengthy error where it isn't quite as clear to the cause, but it looks like it has to do with ld: library not found for -lssl: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/work/Projects/current/testapp/testappclient/.venv/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/df/092qy_7d0tdd_gg_l0wdj_vc0000gp/T/pip-install-0_hdtx9z/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/df/092qy_7d0tdd_gg_l0wdj_vc0000gp/T/pip-install-0_hdtx9z/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/df/092qy_7d0tdd_gg_l0wdj_vc0000gp/T/pip-wheel-91u90oa5 --python-tag cp37 cwd: /private/var/folders/df/092qy_7d0tdd_gg_l0wdj_vc0000gp/T/pip-install-0_hdtx9z/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-x86_64-3.7 creating build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.14-x86_64-3.7/MySQLdb copying … -
settings.Database improperly configured. switching to psql from sqlite
Getting this error - ImproperlyConfigured at /boards/ settings.DATABASES is improperly configured. Please supply the NAME value. DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'localhost', 'NAME': '', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': ''}} I'm using dj_database_url, DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } I was having some errors when my production db is psql and my dev is sqlite - so i figured i'd make it all psql. I copied my .env from prod to the local, and i think i messed up there. it currently looks like: DATABASE_URL=postgres://test:test@localhost:5432/test ALLOWED_HOSTS=.localhost,127.0.0.1 No idea what to do from here. I'm definitely missing something that's probably obvious. -
Django Rest Framework TypeError a bytes-like object is required, not 'str'
I have created a Rest Api with DRF. Everything works fine, but one resource (shoppingListItems) always throws this error: TypeError at /v1/shoppingListItems/ a bytes-like object is required, not 'str' Request Method: GET Request URL: http://localhost:8000/v1/shoppingListItems/ Django Version: 2.2.7 Exception Type: TypeError Exception Value: a bytes-like object is required, not 'str' The problem only occurs, if one or more items are matched. If the resultset is empty there is no error. Here's my views.py: class ShoppingListViewSet(viewsets.ModelViewSet): queryset = ShoppingList.objects.all() serializer_class = ShoppingListSerializer class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer class ShoppingListItemViewSet(viewsets.ModelViewSet): queryset = ShoppingListItem.objects.all() serializer_class = ShoppingListItemSerializer Here's my models.py: class Item(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) def __str__(self): return self.name class ShoppingList(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) members = models.ManyToManyField(User, through='Membership') items = models.ManyToManyField(Item, through='ShoppingListItem') def __str__(self): return self.name class ShoppingListItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) shoppinglist = models.ForeignKey(ShoppingList, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) amount = models.IntegerField() price = models.FloatField(null=True) status = models.BinaryField() Here's my serializers.py: class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item fields = ['id', 'name'] class ShoppingListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ShoppingList fields = ['id', 'name', 'members'] class ShoppingListItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ShoppingListItem fields = ['id', 'shoppinglist', 'item', 'amount', 'price', … -
Django: trouble adjusting stock when an order is cancelled
So in my website when a user cancels an order I want the stock of the products that the user has bought to be brought back up, but whenever I test it the stock remains the same (But successfully decreases when a user buys something). The function I am trying to do this with is adjust_stock in order/views.py as follows: from django.shortcuts import render, get_object_or_404, redirect from .models import OrderItem, Order from cart.models import Cart, CartItem from cart.views import _cart_id from shop.models import Product from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.decorators import login_required from datetime import datetime, timezone from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, InvalidPage import stripe @login_required() def order_create(request, total=0, cart_items = None): if request.method == 'POST': cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart) for item in cart_items: total += (item.quantity * item.product.price) print('Total', total) charge = stripe.Charge.create( amount=str(int(total*100)), currency='EUR', description = 'Credit card charge', source=request.POST['stripeToken'] ) if request.user.is_authenticated: email = str(request.user.email) order_details = Order.objects.create(emailAddress = email) order_details.save() try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart) for order_item in cart_items: oi = OrderItem.objects.create( product = order_item.product.name, quantity = order_item.quantity, price = order_item.product.price, order = order_details) total += (order_item.quantity * order_item.product.price) oi.save() #Reduce stock when order is placed or saved … -
getting error while running django==1.11 in atom text editor
the following error it is throwing (newenv) PS C:\Users\priyaratnam\Desktop\example\protwo> py manage.py startapp apptwo Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\core\management__init__.py", line 363, in execute _from_command_line File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module> File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\options.py", line 12, in <module> from django.contrib.admin import helpers, widgets File "C:\Users\priyaratnam\Desktop\example\newenv\lib\site-packages\django\contrib\admin\widgets.py", line 151`enter code here` '%s=%s' % (k, v) for k, v in params.items(), ^ SyntaxError: Generator expression must be parenthesized -
Nginx 502 Bad Gateway after a Site Update - How to Resolve?
I updated my site, which is on a DO droplet, restarted gunicorn and nginx, and now I'm getting a 502 bad gateway error. I ran sudo tail -30 /var/log/nginx/error.log and here is the output: 2019/12/02 22:01:32 [crit] 24429#24429: *1 connect() to unix:/home/jake/mysite-main/mysite.sock failed (2: No such file or directory) while connecting to upstream, client: 198.85.222.158, server: 165.22.38.243, request: "GET / HTTP/1.1", upstream: "http://unix:/home/jake/mysite-main/mysite.sock:/", host: "www.mysite.com" 2019/12/02 22:02:44 [crit] 24466#24466: *1 connect() to unix:/home/jake/mysite-main/mysite.sock failed (2: No such file or directory) while connecting to upstream, client: 198.85.222.158, server: 165.22.38.243, request: "GET / HTTP/1.1", upstream: "http://unix:/home/jake/mysite-main/mysite.sock:/", host: "www.mysite.com" What are the best next steps? Thanks for any advice, I've been Googling and still haven't found the solution. -
Django Auto generate 10 digit unique number
So i been trying to generate 10 digit unique random number in django model without making it my primary key. My model is Class Transaction(models.Model): Referrence_Number = models.Charfield(max_lenght = 10, blank=True, editable=False, unique=True) I know that Django has special feature inside it to generate random string that i came to know after reading documentation. from django.utils.crypto import get_random_string get_random_string(10).lower() But my problem is how can i incorporate this get_random_string function inside my django transaction model in my Transcation_number Instance. I m actually new to django and cant able to figure it that out. -
Django modelformset prefix does associate data with particular modelformset
In a budgeting app, modelformsets for two project types are displayed, two modelformsets for each project type for a total of 4 modelformsets. To distinguish the modelformsets for different projects, each modelformset has its project_type as prefix. In the post method, when I try to receive the modelformset instances for each project type, the prefix seems to be not working, so I am getting all the data from all the modelformses inside each modelformset! class AddProFormaRates(DevelopmentView): ''' Adds budget rates for the budget in the kwargs 1) Given the budget, find the project types for the budget 2) For each project type, create a modelformset from ServiceRate ''' template_name = 'project/budget.html' # Create modelformset for the_project_type: RateForms = modelformset_factory(ServiceRate, formset = BaseRateFormSet, form = RateForm, extra = 0) def dispatch(self, *args, **kwargs): return super(AddProFormaRates, self).dispatch(*args, **kwargs) ... def post(self, request, *args, **kwargs): context = super(AddProFormaRates, self).get(request, *args, **kwargs) # 1) Get the project types for the budget budget_id = kwargs.get('pk', None) if budget_id: the_budget = budget.objects.get(id = budget_id) else: the_budget = context.get('budget', None) the_project = request.user.project the_project_types = the_budget.budget_project_types.all() # 2) Create modelformsets for each project type rate_formsets = [] formsets_errors = {} the_forms = [] formsets_data = {} expense_rate_forms_errors … -
Django Models: Notfied on Datetimefield
I have an event model that has a datetime field. What are some suggestions on implementing notifications whenever that datetime arrives? I would like to notify related users that the event is about to happen, is currently happening, or has passed. -
How to use UDP to send data to client in Django?
I have read that Django uses HTTP request response architecture to process user requests. And we all know HTTP is an application layer protocol designed within the framework of the Internet protocol suite. Its definition presumes an underlying and reliable transport layer protocol, and Transmission Control Protocol (TCP). So my question is id django uses tcp to establish connection and suppose I want to serve videos or some other file using UDP. How can I achieve this? -
Filter nested query if no results in Django
I have three basic nested serializers that are currently returning a nested data structure (shown below) when I use this query: queryset = Regulation.objects.all() serializer_class = RegulationSerializer(queryset, many=True) data: [{ name: "2019-final" versions: { 0: { name: "2019-01", iterations: (25) [{…}, {…}, {…}] } 1: { name: "2019-02", iterations: [] } } { name: "2020-final" versions: { 0: { name: "2020-01", iterations: [] } 1: { name: "2020-02", iterations: [] } }] My question is how do I NOT return the versions which have no iterations/empty set, and also not return the regulations which do not have any versions/or nested iterations. In the above dataset, I would not want to return '2020-final', because none of its versions have iterations. I would also not want to return version '2019-02', because it has no iterations. // serializers.py class IterationSerializer(serializers.ModelSerializer): class Meta: model = Iteration list_serializer_class = FilteredIterationSerializer fields = ('id', 'team', 'version', 'name', 'date_created', 'created_by_user') class VersionSerializer(serializers.ModelSerializer): iterations = IterationSerializer(many=True, read_only=True) class Meta: model = RegulationVersion fields = ('name', 'iterations') class RegulationSerializer(serializers.ModelSerializer): versions = VersionSerializer(many=True, read_only=True) class Meta: model = Regulation fields = ('name', 'versions') depth = 2 -
'User' object has no attribute '_committed'
Im making a simple app that authenticates users and lets them upload files. Im having a problem where when i try to add a model with user as a foreign key to my database I get this error: 'User' object has no attribute '_committed' models.py fs = FileSystemStorage(location='/media/uploads') class FileInstance(models.Model): file = models.FileField(storage=fs) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) views.py def upload_file(request): if request.method == 'POST': file = FileInstance(request.FILES['file'], request.user) file.save() else: form = UploadFileForm() return render(request, 'upload.html') upload.html {% extends 'commons/base.html' %} {% block title %} Dodaj plik {% endblock %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <button type="submit">Upload</button> </form> {% endblock %} Stacktrace: Internal Server Error: /storage/upload/ Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jch/PycharmProjects/2019Z_PAMIW_git_gr4/pamw2/storage/views.py", line 36, in upload_file file.save() File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 848, in _save_table for f in non_pks] File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 848, in <listcomp> for f in non_pks] File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/files.py", line 286, in pre_save … -
Django channels Error during WebSocket handshake: Unexpected response code: 500
I'm completely stumped and I have spent hours researching what is causing this error. I used the following tutorial (https://channels.readthedocs.io/en/latest/tutorial/part_1.html) to understand Django channels to swap out ajax short-polling in a current project. I have inserted everything into my project and it should run fine except the websocket disconnects. The browser says WebSocket connection to 'ws://localhost:8001/ws/members/vote/2/' failed: Error during WebSocket handshake: Unexpected response code: 500. Terminal output: 2019-12-02 19:44:23,543 ERROR Exception inside application: 'room_name' File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/asgiref/sync.py", line 244, in __call__ return await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/db.py", line 14, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/asgiref/sync.py", line 277, in thread_handler return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/consumer.py", line 105, in dispatch handler(message) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/generic/websocket.py", line 39, in websocket_connect self.connect() File "./vote/consumers.py", line 10, in connect self.room_name = self.scope['url_route']['kwargs']['room_name'] 'room_name' 127.0.0.1:54775 - - [02/Dec/2019:19:44:23] "WSDISCONNECT /ws/members/vote/2/" - - Here's my code snippets Vote.html <script> var questionID = … -
How to add task to asyncio loop inside of a django view?
I have middleware that sets up the get_response method as a coroutine so that another task can be run together: class AsyncMiddleware: def __init__(self, get_response): self.get_response = asyncio.coroutine(get_response) def __call__(self, request): tasks = [self.get_response(request), <OTHER_ASYNC>] response, *other_response = asyncio.run(self.gather(tasks)) return response async def gather(self, tasks): return await asyncio.gather(*tasks) Inside of my django view, I need to use django channels to send a task to a worker on a PATCH request. When I try to add the task to my loop, the response completes, my model is updated, but the task is never sent to my worker. loop = asyncio.get_event_loop() channel_layer = get_channel_layer() result = loop.create_task(channel_layer.send( 'model-update', { 'type': 'update', 'data': {} }, )) I've tried many different variations of this code. If I remove the async code from my middleware and use async_to_sync from asigref, everything works as expected (this is not a real option because async_to_sync cannot be used inside a run loop) -
How to set up sub-domains on Apache
I am trying to get a site I have to work with sub-domains but nothing seems to be working. A quick overview of what I am doing.. The stack: -Django (using django-tenants/django-tenant-schemas for multi-tenancy) -Apache2 -Postgresql -Linode (Cloud Hosting) DNS settings: A/AAAA Record Hostname: www IP Address: XXX.XXX.XXX.XXX CNAME Record Hostname: * Aliases to: mysite.com etc/hosts file: 127.0.0.1 localhost XXX.XXX.XXX.XXX myhostname According to the Django-tenant docs this is how my VirtualHost should be set up... VirtualHost config: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/david/my_project/static <Directory /home/david/my_project/static> Require all granted </Directory> Alias /media /home/david/my_project/media <Directory /home/david/my_project/media> Require all granted </Directory> <Directory /home/david/my_project/config> <Files wsgi.py> Require all granted </Files> </Directory> ServerName mysite.com ServerAlias *.mysite.com mysite.com WSGIScriptAlias / /home/david/my_project/config/wsgi.py WSGIDaemonProcess django_app python-path=/home/david/my_project python-home=/home/david/my_project/venv WSGIProcessGroup django_app </VirtualHost> When I ping www.mysite.com it returns a response. When I ping www.main.mysite.com it returns a response as well (which should be a tenant). When I visit www.main.mysite.com I get a Bad Request(400) error which I assume is a good thing as the server is being reached. But no other tenants will even return a response like that. I get a This site can't be reached error for others. What settings … -
Annotate count of multiple values by week with Django ORM or combine based on shared keys
I'm trying to annotate the count of values and group by week/year. Here's what I attempted: activity = Activity.objects.filter(user=request.user)\ .annotate(year=ExtractYear('date'), week=ExtractWeek('date'))\ .values('year', 'week', 'activity')\ .annotate(count=Count('pk'))\ .order_by('-year', '-week') Which groups based on year, week, and activity: <QuerySet [{'activity': 'a', 'year': 2019, 'week': 48, 'count': 2}, {'activity': 'ac', 'year': 2019, 'week': 48, 'count': 4}, ... ]> What's the best way to group based on the week/year so the outcome is something like: [{'year': 2019, 'week': 48, {'activity': 'a', 'count': 2}, {'activity': 'ac', 'count': 4}, ... }] Is there a way to combine based on the shared keys of each item? -
How can I capitalize the first letter of a string in Python, ignoring HTML tags?
I would like to capitalize the first letter of a string, ignoring HTML tags. For instance: <a href="google.com">hello world</a> should become: <a href="google.com">Hello world</a> I wrote the following, which works, but it seems inefficient, since every character of the string is being copied to the output. Is there a better way to do it? @register.filter def capinit(value): gotOne = False inTag = False outValue = '' for c in value: cc = c if c == '<': inTag = True if c == '>': inTag = False if not inTag: if c.isalpha() or c.isdigit(): if not gotOne: cc = c.upper() gotOne = True outValue = outValue + cc return outValue Note that this ignores initial punctuation. It will capitalize the first letter it finds, unless it finds a number first in which case it doesn't capitalize anything. -
django computed coloumn with lookup from same table and if class
I am new to programming.I am trying to create a project management site. I created a model as follows class boqmodel(models.Model): code = models.IntegerField() building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) duration = models.IntegerField() linkactivity = models.CharField(max_length=300) #contains code (same as code field) which this specific code is linked to linktype = models.CharField(max_length=300)# only two choices start or finish linkduration = models.IntegerField() plannedstart = models.DateField() plannedfinish = models.DateField() The problem is i need my palnned start as a computed coloumn The planned coloumn should be as follows if linkactivity is null then it should take a default value 01-01-2019 if else then it should look the linkactivity in code field and then if linktype is start then it should specify the start date of code activty +duration or if linktype is finish plannedfinish+duration Example say first entry code=1 building=A-1 Level=L-1 Activity=Activity-1 Subactivity-Subactivity-1 duration=2 linkactivity=null linktype=null linkduration=null planned start=01-01-2019(as linkactivity=null) plannedfinish=03-01-2019(planned start+duration) second entry code=2 building=A-1 Level=L-1 Activity=Activity-2 Subactivity-Subactivity-2 duration=3 linkactivity=1 linktype=start linkduration=1 planned start=02-01-2019(as linkactivity=1,it searches code1 ,as linktype=start,it searches startdate of code 1 it is 01-01-2019 ; finally 01-01-2019+link duration(1)=02-01-2019) plannedfinish=05-01-2019(planned start+duration) Any help would be … -
Django SmartFields 'ImageFieldFile' object has no attribute 'is_static'
We are currently using Django 1.11, Python2.7 & django-smartfields 1.0.9. It used to work perfect, but for any update (I suppose) we are now getting this error everytime we update a record using ModelForms. 'ImageFieldFile' object has no attribute 'is_static' We trace the bug and it happens when SmartFields tries to delete an image /home/herosuite/lib/python2.7/smartfields/fields/__init__.py in delete self._committed = True if save and instance_update: self.instance.save() save.alters_data = True def delete(self, save=True, instance_update=True): # prevent static files from being deleted if self.is_static or not self: ... return if hasattr(self, '_file'): self.close() del self.file self.storage.delete(self.name) self.name = None ▼ Local vars Variable Value instance_update False save True self <ImageFieldFile: company/images/products/TM_105_AZUL.jpg> Even sometimes we just edit other fields in the record (not the image field) Has anyone faced this situation also????