Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, ReactJS, Webpack hot reload
I've been trying to setup a react component inside django with the help of webpack 4. To get me starting I went through and read: Using Webpack transparently with Django + hot reloading React components as a bonus Tutorial: Django REST with React (Django 2.0 and a sprinkle of testing) Both these walkthroughs are really good. At last I got it almoast working by following the second link even though I do user django 1.11. The problem I had after following 2nd link was that hot reloading does not work when using a webpack-dev-server. The problem is that django cannot read the output file of the webpack-dev-server (gives 404 error) while the main.js can be read. I've read that the dev-server files does only live in memory by default. To overcome the issue with error 404 on the hot reload files installed the package write-file-webpack-plugin to write out the file each reload. Then changed the webpack-config.js to (I deleted some lines to keep it shorter....): var path = require('path'); //webpack is not needed since I removed it from plugins //const webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var WriteFilePlugin =require('write-file-webpack-plugin'); module.exports = { module: { rules: [ { test: /\.js$/, … -
Django rest framework, Got AttributeError when create many to many
I try add order with product by overriding .create() method: class OrderCreateSerializer(ModelSerializer): product = PrimaryKeyRelatedField(queryset=Product.objects.all()) class Meta: model = Order fields = [ 'owner', 'product' ] def create(self, validated_data): product = validated_data.pop('product') order = Order.objects.create(**validated_data) order.product_set.add(product) return order But got this error: Got AttributeError when attempting to get a value for field product on serializer OrderCreateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Order instance. Original exception text was: 'Order' object has no attribute 'product'. Traceback: Traceback (most recent call last): File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/rest_framework/generics.py", line 192, in post return self.create(request, *args, **kwargs) File "/home/denis/Projects/lunch_order/apps/api/views.py", line 24, in create headers = self.get_success_headers(serializer.data) File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- packages/rest_framework/serializers.py", line 560, in … -
Building Celery container in Django app
I want to learn how to set up a Django app with Celery. I am using the following resource. I don't understand why we have to build the same image twice for both web and worker this example. For example, see: # Django web server web: build: context: . dockerfile: Dockerfile hostname: web command: ./run_web.sh volumes: - .:/app # mount current directory inside container ports: - "8000:8000" # set up links so that web knows about db, rabbit and redis links: - db - rabbit - redis depends_on: - db # Celery worker worker: build: context: . dockerfile: Dockerfile command: ./run_celery.sh volumes: - .:/app links: - db - rabbit - redis depends_on: - rabbit Does that mean that this docker-compose.yml will create two containers that are duplicates of each other? Seems a little excessive if I just need a celery worker for worker (why set up Django twice?). Maybe I am misunderstanding things. It feels like one option is to just replace command in web with ./run_web.sh; ./run_celery.sh and just set up proper links. This way you could remove worker altogether. Can someone enlighten me? Thanks for reading. -
Django messages: how to change html structure?
So I've got some really specific styling constraints for the messages, and I've pushed ::before and ::after as far as they will go. Beyond that what I really need is for the text of the message to be enclosed in a span tag, ideally with a settable class (it's just dumped in the div which is not great to begin with). Is there any setting in Django, or any place I can go to restructure the html? I can't find any documentation for this (surely this is not an uncommon thing to customise). The alternative is to use js, but I'd prefer to avoid cutting and pasting elements and content when it should be something that should be customisable. What I've got is: <div class="messages"> <div class="alert alert-success alert-dismissable fade show"> <a href="#" class="close" data-dismiss="alert" aria-label="close">x</a> [message text] </div> </div> What I want is: <div class="messages"> <div class="alert alert-success alert-dismissable fade show"> <a href="#" class="close" data-dismiss="alert" aria-label="close"> <i class="close-icon"></i> </a> <span>[message text]</span> </div> </div> -
Custom validator for nested field in serializer
In my BookSerializer, I have a nested field page: class PageSerializer(serializers.ModelSerializer): ... class BookSerializer(serializers.ModelSerializer): page = PageSerializer() and the page field validator expects an dictionary as value. But what I want is it should accept an integer as well (page's id). So in the BookSerializer, I tried to override the validate function for the page field but it didn't work: class BookSerializer(serializers.ModelSerializer): page = PageSerializer() def validate_page(self, value): if isinstance(value, int): return value # if value is not an integer, reuse the default validator # but django said that validate_page is not a function return super().validate_page() Seems like the validate_page function is never called because it's a nested field. Thanks ! -
How do you keep a ManyToMany relationship up to date?
I have the following classes: class Plugin(models.Model): pass class Instance(models.Model): plugins = models.ManyToManyField(Plugin, blank=True, null=True) My goal is to write a cron job which gets a list of plugins from this instance to reflect the instance_plugin relationship. This means that if a plugin is removed from the instance in real life then it must also be reflected here. for instance in Instance.objects.all(): url = 'http://{}/wordpress_plugins'.format(instance.ip_address) ... plugins = [] for path, dic in response.json().items(): plugin, created = Plugin.objects.update_or_create( ... ) plugins.add(plugin) instance.plugin_set = plugins I am getting TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use plugins.set() instead. What is the best approach to what I am doing? -
Django fixture loaddata into neo4j
My fixture is stored in myapp/fixtures/nodes.json [ { "model": "myapp.doctor", // "pk": 1, "fields": { "name": "will smith", "title": "chief resident", } }, ] But when I run Python3 manage.py loaddata nodes.json I get the following error: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 8 column 3 (char 120) Here is my settings.py I suppose if django fixtures is hooked up to this then I shouldn't expect it to work? I'm using django_neomodel. NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:PW@localhost:7687') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'orgdb', 'USER': 'laynetrain', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } } How can I fix this error or go about loading data into my neo4j db? I've tried tweaking the JSON, but I feel this might be deeper than that. -
Collectstatic done through Jenkins breaks gunicorn
I have a Jenkins shell script that runs whenever I deploy code to my Bitbucket repo. The script is as follows: #!/bin/bash echo "Beginning deployment" source /home/halsdunes/.bashrc cd /home/halsdunes/proj git pull echo "Begin django update" source /home/halsdunes/.virtualenvs/proj/bin/activate pip install -r requirements.txt python manage.py migrate python manage.py collectstatic --clear --noinput echo "Restart gunicorn server" sudo systemctl daemon-reload sudo systemctl restart gunicorn sudo systemctl status gunicorn echo "Done" However, when this is complete, the server just says Internal Server Error, which in this case seems to be referring to an issue with the collectstatic step. When I run just this part manually via terminal with no syntax changes: python manage.py collectstatic --clear --noinput sudo systemctl daemon-reload sudo systemctl restart gunicorn sudo systemctl status gunicorn It fixes the problem. Not sure why the same code causes a weird error when run through Jenkins vs. when run manually. Any ideas what might be causing this issue? -
Display external html file django
I am using Django 2.0.2 I wish to be able to display HTML files that are in another location on disk. These are FastQC reports, I don't want to copy them to templates or static folders, there is also no way to include them into DIRS. Any suggestions? Thanks! -
Django/Angular2 - CSRF token missing or incorrect
I have version 1.9 of django. My django-rest-framework settings are: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'scrumboard', ] REST_FRAMEWORK = { #'DEFAULT_PERMISSION_CLASSES': ( # 'rest_framework.permissions.IsAuthenticated', #), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } JWT_AUTH = { 'JWT_RESPONSE_PAYLOAD_HANDLER': 'scrumboard.utils.jwt_response_payload_handler', #app_name is name of the app which contains utils.py } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True i wanted to send POST requests wih RESTer through this API: class OffreViewSet(ModelViewSet): queryset = Offre.objects.all() serializer_class = OffreSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) urls.py: router.register(r'Offres', OffreViewSet) And I get an error { "detail": "CSRF Failed: CSRF token missing or incorrect." } Why this is happening? Thanks in advance. -
I want some advices while learning python
I learnt python basics and I am trying to do intermediate and advanced topics and I started to get unmotivated because it starts to be difficult, I feel like I am missing something while learning, Could you recommend me to take extra courses that will boost me up or what to do, Please help? -
How do I search for a user or id in django?
I am trying to make an add a user and I want it to be added by id or by user but I am getting an error every time I search to find out if the user exists in this way: try: user = User.objects.filter(Q(id=user_s['id']) | Q(username=user_s['username'])) except ObjectDoesNotExist: rest of the code error: ValueError: invalid literal for int() with base 10: 'Usuario1' -
Python/Django/verify email -- [Errno 11004] getaddrinfo failed
I followed this guide pretty closely and have run into quite a few errors I have managed to debug, but this one is proving more difficult. When I submit the signup form, I'm getting the following traceback and error: Environment: Request Method: POST Request URL: http://localhost:8000/accounts/signup/ Django Version: 1.11.11 Python Version: 2.7.14 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'concerts.apps.ConcertsConfig', 'articles.apps.ArticlesConfig', 'accounts.apps.AccountsConfig', 'tinymce'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users...\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users...\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users...\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users...\accounts\views.py" in signup_view 123. email.send() File "C:\Users...\lib\site-packages\django\core\mail\message.py" in send 348. return self.get_connection(fail_silently).send_messages([self]) File "C:\Users...\lib\site-packages\django\core\mail\backends\smtp.py" in send_messages 104. new_conn_created = self.open() File "C:\Users...\lib\site-packages\django\core\mail\backends\smtp.py" in open 64. self.connection = self.connection_class(self.host, self.port, **connection_params) File "c:\python27\Lib\smtplib.py" in init 256. (code, msg) = self.connect(host, port) File "c:\python27\Lib\smtplib.py" in connect 317. self.sock = self._get_socket(host, port, self.timeout) File "c:\python27\Lib\smtplib.py" in _get_socket 292. return socket.create_connection((host, port), timeout) File "c:\python27\Lib\socket.py" in create_connection 557. for res in getaddrinfo(host, port, 0, SOCK_STREAM): Exception Type: gaierror at /accounts/signup/ Exception Value: [Errno 11004] getaddrinfo failed I'm basically brand new to web development, and I did find this question on the same … -
Django annotation with model instances
I have a table of Measurements, with each Measurement referencing a Subject and an Attribute as well as a value. So, suppose I have a Subject named "Elmo" and an Attribute called "weight", I might have a few Measurements of the weight taken at different times, or using different measurement techniques, etc. And I might also have a "height" Attribute and a few measurements of that as well. I would like to get a summary of all of these attributes for a given subject. What I've figured out so far is q = elmo.measurements.values('attribute') \ .annotate(models.Avg('value')) this gives me a QuerySet that correctly contains the average values for the "weight" and "height" Attributes. However, instead of Attribute model instances, the QuerySet contains the IDs of the Attributes. This is apparently how .values() works. <QuerySet [{'attribute': 1, 'average': 20.65}, {'attribute': 3, 'average': 3.0}]> Is there an efficient way to convert these back to Attribute instances, through some sort of JOIN or otherwise, so I can access other properties on them, such as the Attribute name? -
Django Social Login: 'AsgiRequest' object has no attribute 'session'
Got an error when trying that was thrown when using social-app-django (2.1.0) 'AsgiRequest' object has no attribute 'session' Running with channels 1.1.8, Django 2.0.3, asgi-redis 1.2.0, python 3.6 Running via python manage.py runserver (development environment) not uwgsi or nginx. The occurs when trying to access /social/login/google-oauth2/ (authenticating with google account). I have read about changing MIDDLEWARE_CLASSES to MIDDLEWARE but we have been using Django >=1.9 for a while so it has already been changed. -
How do properly use queryset in a GenericAPIView in Django DRF?
I have started using GenericAPIView instead of APIView and I am confused about the use of queryset and serializer_class being defined at the top of the class. I understand these have to be defined, but I now have a query at the top of my class and another query inside GET. My question is can I use the queryset inside of my GET method so I am not making 2 unnecessary queries. class demo(GenericAPIView): queryset = Demo.objects.all() serializer_class = DemoSerializer def get(self, request, num, format=None): query = Demo.objects.filter(name=test, number=num) In other words, queryset = Demo.objects.all() is defined because it is required - but I am not really utilizing it so seems like an extra query... -
Display a different default value in Django CreateView according to current logged in user?
Long story short, I am creating a ModelForm which will be passed to a generic CreateView. This form will allow a user to post an event with a location. I have already collected the user's base address in my user creation form, and my Event model has a foreignkey to the author of the event. I would like to display the city and state of the currently logged in user as a default value on the event creation form. Since default values are set at the model level, I am not able to use the requests framework. Solution such as this one offer a way to save info from the request to the database upon submission but I would like to display this default when the user first navigates to the form page. How do I achieve this functionality? P.S. I can add code to the question if it's not clear what I'm asking or how I have set up the models and forms. Just let me know. -
Django - Edit custom user profile fields in two different forms
I have a really big headache. I've been searching informations for the whole week and yet I'm still stuck. I want to create two subpages with 2 different forms yet connected with the same user model: /account/register.html - I'm using Django generic UserCreationForm already /account/questionnaire.html - page for UPDATING additional information such as user city,website,phone etc. Registration form is working. I have problem with second one. Console output when I send the second form: [25/Apr/2018 17:29:11] "POST /accounts/edituserinfo/ HTTP/1.1" 302 0 [25/Apr/2018 17:29:11] "GET /accounts/profile/ HTTP/1.1" 200 1818 302 means redirect I guess... models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete='CASCADE') description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py from django import forms from accounts.models import UserProfile from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) field_order = ['username', 'email', 'password1','password2', 'first_name','last_name'] class Meta(): model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', } def save(self,commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.first_name = self.cleaned_data['last_name'] user.first_name = self.cleaned_data['email'] if … -
Push from local to heroku is failing when to instal dependencies
I try to deploy a Django App on Heroku pot always fails when I try to push from local to Heroku. I don't have any idea why. Installing python-3.6.4 -----> Installing pip -----> Installing dependencies with Pipenv 11.8.2… Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/pipenv/project.py", line 318, in parsed_pipfile return contoml.loads(contents) File "/tmp/build_e84ef21021d04400878a126a1cd85c3b/.heroku/python/lib/python3.6/site-packages/pipenv/patched/contoml/__init__.py", line 15, in loads elements = parse_tokens(tokens) File "/tmp/build_e84ef21021d04400878a126a1cd85c3b/.heroku/python/lib/python3.6/site-packages/pipenv/patched/prettytoml/parser/__init__.py", line 17, in parse_tokens return _parse_token_stream(TokenStream(tokens)) File "/tmp/build_e84ef21021d04400878a126a1cd85c3b/.heroku/python/lib/python3.6/site-packages/pipenv/patched/prettytoml/parser/__init__.py", line 32, in _parse_token_stream raise ParsingError('Failed to parse line {}'.format(pending.head.row)) prettytoml.parser.errors.ParsingError: Failed to parse line 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/bin/pipenv", line 11, in <module> sys.exit(cli()) File "/tmp/build_e84ef21021d04400878a126a1cd85c3b/.heroku/python/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/tmp/build_e84ef21021d04400878a126a1cd85c3b/.heroku/python/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 697, in main rv = self.invoke(ctx) In requirements.txt I have: amqp==2.2.2 billiard==3.5.0.3 celery==4.1.0 dj-database-url==0.5.0 Django==2.0.4 django-heroku==0.3.1 gunicorn==19.7.1 kombu==4.1.0 psycopg2==2.7.4 pytz==2018.4 vine==1.1.4 whitenoise==3.3.1 -
Extending django UserCreationForm
Well, I extended User: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sheba = models.DecimalField(max_digits= SHEBA_LENGTH, decimal_places = 0) mellicode = models.DecimalField(max_digits=11, decimal_places = 0) But the problem is that we have UserCreationForm for user signup. Now I need a new form to handle added fields. I like to create the form from model using ModelForm. Now the problem is that UserCreationForm itself uses ModelForm to create fields for User model. ModelForm has an inner class named Meta which have a field named model for specifying what model should be read for wanted field. I thought there should be a way to do so as it is an ordinary thing to do. What I have now which doesn't work for obvious reasons is this: class SignUpForm(UserCreationForm, ModelForm): class Meta(UserCreationForm.Meta): model = UserProfile fields = ['user','mellicode', 'birthdate','residentialaddress','postalcode','sheba','idpic'] -
Django trigger some code on all instances
I need to execute some code in all running instances of Django (eg. processes under uwsgi), but have no idea how to make it in a clear way. Non-working ideas: Celery executes code in the separate process. An adding some middleware which checks some data in the database looks ugly (in other words another caching layer). Restarting process looks ugly too and needs something which actually communicates and performs the restart. A bit of context, why I need it: have dynamic settings and some locally (in the scope of one process) cached vars in third-party libraries, so when these vars (values on which they depend) are changed I need to reread them in all "djangos". -
Problems pushing into Heroku a web app on django
hi i'm kinda new using heroku to upload python web apps, i think did enought to prepare my website to be upload to create heroku server but i get an error when trying to push. here: Counting objects: 519, done. Delta compression using up to 4 threads. Compressing objects: 100% (483/483), done. Writing objects: 100% (519/519), 7.55 MiB | 136.00 KiB/s, done. Total 519 (delta 247), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.4 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: Collecting aioredis==1.0.0 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/e6/15/79bc11213e1b918f152914e1de96e5610961da3709e3ca8cc650e00b8f4e/aioredis-1.0.0-py3-none-any.whl (59kB) remote: Collecting amqp==2.1.4 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 2)) remote: Downloading https://files.pythonhosted.org/packages/7e/4b/ac7afb11b57f237e3c1c64b5408c5d229bf5d4b42af6cb6e683c7690ca4f/amqp-2.1.4-py2.py3-none-any.whl (49kB) remote: Collecting asgi-redis==1.4.0 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 3)) remote: Downloading https://files.pythonhosted.org/packages/06/25/c1194af4c5599787cbdb11071bca584e4ccf683f0f97bdafc6a9deaedd6d/asgi_redis-1.4.0-py2.py3-none-any.whl remote: Collecting asgiref==1.1.2 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 4)) remote: Downloading https://files.pythonhosted.org/packages/ee/6d/67f79a9567de5ba4419c3e8d39622bed0d974d704075d09df765b5ddb5ce/asgiref-1.1.2-py2.py3-none-any.whl remote: Collecting asn1crypto==0.24.0 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 5)) remote: Downloading https://files.pythonhosted.org/packages/ea/cd/35485615f45f30a510576f1a56d1e0a7ad7bd8ab5ed7cdc600ef7cd06222/asn1crypto-0.24.0-py2.py3-none-any.whl (101kB) remote: Collecting astroid==1.6.1 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 6)) remote: Downloading https://files.pythonhosted.org/packages/cb/8c/18fefaf865c3e48ed31d60d53a8f85ba7e8b27fe9bd115cecae876a8d58e/astroid-1.6.1-py2.py3-none-any.whl (288kB) remote: Collecting async-timeout==2.0.1 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 7)) remote: Downloading https://files.pythonhosted.org/packages/1d/b9/213521db2918b5b7f7df333a33ea3d38ba70ba705d9db6c29f0343c213ea/async_timeout-2.0.1-py3-none-any.whl remote: Collecting attrs==17.2.0 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 8)) remote: Downloading https://files.pythonhosted.org/packages/cd/ff/2d0c4483443789477022d85ab467bc4c0f18c6d45cb02234ed64048cbb33/attrs-17.2.0-py2.py3-none-any.whl remote: Collecting autobahn==17.6.1 (from -r /tmp/build_9cc549609c727e83c7b487b43fec0a2e/requirements.txt (line 9)) remote: Downloading … -
Understanding Celery's architecture in the context of a Django application
I am currently learning about Celery and have been really curious about the internals and how it operates within a web application. Lets use Django for this example. I found the following diagram which really helps me see how task processing flows through a system. I have a general question, which is causing a lot of cognitive dissonance. Most of the code for both Django and Celery live in my Django app, but in this diagram they are shown to be separate entities. Why is this? Redis seems to operate within Django too, since configuration is set in Django but this is just a pointer to the redis box, so this feels like a fairly minimal relationship (between web app and redis db). For example: Example CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } My confusion is mainly around the following statement: Web and worker nodes are plain servers. The only difference is that Web nodes receive requests from the internet and place jobs to be processed asynchronously and Workers are the machines that pick these jobs, execute and provide a response. Despite this logic separation, you will commonly find … -
Alter SVG using Models in Django
I am new to Django, so apologise if the answer to this question is either 'it's impossible' or 'it's easy'. I have an SVG image, which I made in inkscape. It is made up of various circles and triangles. I want to alter the fill of these shapes based on data from a model. Each shape may be colored differently. I currently am importing the svg inside an image tag within a template. One possible solution I guess is to paste the raw SVG code into the html template and alter the colours that way? But perhaps there is a better solution. Let me know if I can give more information. I am not entirely sure how to display this question in an example yet. -
Updating timestamps of related models
I have the following two models: class Blog(TimeStampedModel): summary = models.TextField() status = models.CharField(max_length=255) class Entry(TimeStampedModel): author = models.CharField(max_length=255) text = models.TextField() blog = models.ForeignKey(Blog, models.CASCADE, related_name='entries') Both models sublass a commont meta-model that defines a timestamp for when each model was last updated: class TimeStampedModel(models.Model): last_changed = models.DateTimeField(auto_now=True) class Meta: abstract = True This works fine when saving each model individually. However, in my use case, when an Entry is updated, it should also reflect in the update of the last_changed timestamp of the associated Blog. Is there any easy way to tell Django to also bump the timestamps of related models?