Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A Select Widget with fields as checkboxes with multiple options possible
I have the following model: class Owner(models.Model) country = models.CharField(max_length=255, choices=COUNTRIES, default=COUNTRIES_DEFAULT) COUNTRIES is compose of tuples: COUNTRIES = ( ('afg', 'Afghanistan'), ('ala', 'Aland Islands'), ('alb', 'Albania'), ('dza', 'Algeria'), ('asm', 'American Samoa'), ....... ) For FrontEnd, I need to show a Widget, and for each country to have a checkbox. A Person/User can select multiple Countries. I presume I need to use a custom widget, but I don't know where to start inherit for Field/Widget and make the query in the database. -
Django query with multiple foreign keys does not seem to work
I am trying to get a record from the table Answer that corresponds to the foreign keys Learner and Problem. The Problem foreign key though is not given; Outcome is available instead. I cannot seem to make my query work. Can anybody point to me what I am doing wrong? #Model classes: class Answer(models.Model): problem = models.ForeignKey('Problem', on_delete=models.CASCADE, blank=False, help_text="Problem ID") learner = models.ForeignKey('Learner', on_delete=models.CASCADE, blank=False, help_text="Learner ID") try_count = models.IntegerField(blank=False, default=0, help_text="Number of times the problem was attempted") correct = models.CharField(max_length=1, blank=False, default='0', choices=Constant.CORRECT, help_text="Indicator whether the problem was answered correctly or not") ... class Problem(models.Model): outcome = models.ForeignKey('Outcome', on_delete=models.CASCADE, blank=False, help_text="Outcome ID") ... class Outcome(models.Model): name = models.CharField(max_length=32, blank=False, unique=True, help_text="Outcome name") ... class Learner(models.Model): anonymous_id = models.CharField(max_length=32, blank=False, help_text="Anonymous ID") ... # Query answer = Answer.objects.filter(learner=learner, problem__outcome=outcome).order_by('correct', 'try_count')[0] Thank you! -
How to properly get data from Django with Ajax
I can't seem to get this very simple connection to work. There are no errors, but the alert never comes up when the button is pressed. Any help would be incredibly appreciated. template: {% extends 'navbar.html' %} {% load static %} {% block content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <h1>jkkk</h1> <button id="butt">Get Data</div> </body> <script type="text/javascript"> $(document).ready(function(){ $("#butt").click(function(){ $.ajax({ type: "GET", url: "{% url 'test' %}", datatype:'json', success: function(data) { if (data['success']) alert("success!") } }); }); }); </script> Views from django.shortcuts import render, redirect from django.core import serializers from .models import Comments from .forms import CommentForm from django.contrib.auth.decorators import login_required from users.models import Contact from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.http import HttpResponse from django.http import JsonResponse import json def explore(request): return render(request, 'explore.html') def happening(request): return render(request, 'happening.html') def test(request): if request.method=='GET': data = {'success': 'success'} return JsonResponse(data) URL from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.explore, name='explore'), path('happening/', views.happening, name='happening'), path('<user__name>/', views.home, name='home'), path('test/', views.test, name='test'),] All I want is for the data from django to go into the template. I think my problem is with the URL linking, but I'm not certain. When I press … -
How to read Django template input values in Django views
I cannot read Django input type textarea value i tried message = request.post['message'] but it is throwing multiValuedictkey error 'message i expecting to read this text area value in django view -
Django : TemplateDoesNotExist at /catalog/ error
I am a beginner at django and python and i am currently stuck at Creating our home page of the Django tutorial. I am getting a "TemplateDoesNotExist at error" error. I am also using windows. What am I doing wrong? Settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) import os SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag') DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog.apps.CatalogConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'locallibrary.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'locallibrary.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Chicago' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' StackTrace: TemplateDoesNotExist at /catalog/ index.html Request Method: GET Request URL: http://127.0.0.1:8000/catalog/ Django Version: 2.1.5 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\AjitGoel\Envs\my_django_environment\Scripts\python.exe Python Version: 3.7.2 Python Path: ['C:\\Users\\AjitGoel\\django-projects\\locallibrary', … -
Google Sign In for Android: Cannot sign in when I pass server's client id to requestIdToken
I'm trying to connect my mobile app to server side. I was successful in signing in and signing out from Google on mobile app. So I was trying to authenticate the user. However, I cannot sign in when I pass my web client id to requestIdToken. There is no error but nothing happens even when I push sign in button. When I didn't pass it to requestIdToken, I can connect to API but it returns 405. My code is here GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .requestServerAuthCode(getString(R.string.server_client_id)) .build(); mGoogleSignInClient = GoogleSignIn.getClient(this, gso); mSignInButton = findViewById(R.id.sign_in_button); mSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signIn(); } }); mSignOutButton = findViewById(R.id.sign_out_button); mSignOutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signOut(); } }); @Override protected void onStart() { // Check for existing Google Sign In account, if the user is already signed in // the GoogleSignInAccount will be non-null. GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); updateUI(account); super.onStart(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { // The Task returned from this call is always completed, no need to attach // a listener. Task<GoogleSignInAccount> … -
Highcharts with json from django query not rendered
I'm following this article to render highchart with json data from django query. However chart is not rendered but I'm not getting any errors from Django or by the client when inspecting source. Appreciate if anyone can point the mistakes. Thank you in advance. I'm using django 2.0 and python3.5 models.py PLATFORM = ( ('ipcore','IPCORE'), ('metro','METRO E'), ('edge','EDGE'), ('access','ACCESS'), ('voice','VOICE'), ('system','SYSTEM'), ('iptv','IPTV')) class Contract(models.Model): vendor_name = models.ForeignKey(Vendor, on_delete=models.CASCADE) name = models.CharField(max_length=500) contract_no = models.CharField(max_length=100, blank=True) partner_name = models.CharField(max_length=200, blank=True) value = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True) platform = models.CharField(max_length=100, blank=True, choices=PLATFORM) views.py def json_example(request): return render(request, 'app/json_example.html') def chart_data(request): dataset=Contract.objects.all().values('platform'). exclude(platform='').annotate(Sum('value')).order_by('value__sum') platform_name = dict() for platform_tuple in Contract.PLATFORM: platform_name[platform_tuple[0]] = platform_tuple[1] chart = { 'chart': {'type': 'pie'}, 'title': {'text': 'Contract Value for Every platform'}, 'series': [{ 'name': 'Platform', 'data': list(map(lambda row: {'name': platform_name[row['platform']], 'y': row['value__sum']}, dataset)) }] } return JsonResponse(chart) urls.py url('json_example/', views.json_example, name='json_example'), url('json_example/data/', views.chart_data, name='chart_data'), json_example.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>Contract Inventory Highcharts Example</title> </head> <body> <div id="container" data-url="{% url 'chart_data' %}"></div> <script src="https://code.highcharts.com/highcharts.src.js"></script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $.ajax({ url: $("#container").attr("data-url"), dataType: 'json', success: function (data) { Highcharts.chart("container", data); } }); </script> </body> </html> This is the json data from dataset. [{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", … -
django django-oauth-toolkit issuing jwt instead of random strings
I understand that django-oauth-toolkit is using oauthlib and oauthlib provides an example on the implementation of using jwt instead of random strings. however i don't understand how i can get django-oauth-toolkit to issue jwt instead of random strings. can anyone give and example implementation or git repo on how we can do this? path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), im not sure how we can change the views in that import lines to customize it to allow jwts -
Possible to change password in DRF without the previous password?
Say I had a setup that was similar to an office with a system admin. But instead of using email to reset passwords, the system admin did it himself, and then got the password to the user through some other fashion. Is this possible to do in Djanog? Can I use the hash of the previous password somehow? Is there possibly a way to overwrite the rest-auth in the serializer and view? Please let me know if you guys have any methods for this. I haven't really come across anything that isn't email or Django front end stuff. Thanks all, -
what is the difference between 2 function?
I am getting date/time info from ajax to django. I am using 2 different functions. "event_edit" is working fine, but "event_edit_new" does not work. it says 'Enter a valid date/time.' My question is what is making difference. They are getting exactly same information but one is ok while other one is not. Thank you in advance *********ajax code var ajax_test = function(event){ $.ajax({ url: '/scheduler/event/' + event.eventId + '/edit2/', method: 'POST', // 'POST' or 'PUT' data: { 'Note': event.title, 'OpNum': event.resourceId, 'StartTime' : event.start.format(), 'StopTime' : event.end.format(), 'ScheduleNum': event.eventId, } }).done(function(res) { console.log("done", res) }).fail(function(error) { console.error("error", error) console.log(event.start.format()); }); } *******2 different codes def event_edit(request, pk): schedule = get_object_or_404(Schedule, pk=pk) schedule.OpNum = request.POST.get('OpNum') schedule.Note = request.POST.get('Note') schedule.StartTime = request.POST.get('StartTime') schedule.StopTime = request.POST.get('StopTime') schedule.ScheduleNum =request.POST.get('ScheduleNum') schedule.save() return HttpResponse('ok') def event_edit_new(request, pk): schedule = get_object_or_404(Schedule, pk=pk) if request.method =='POST': form = ScheduleForm(request.POST, request.FILES, instance = schedule) if form.is_valid(): form.save() return HttpResponse('ok') else: return HttpResponse('error') else: return HttpResponse('done') -
One field of a table, exclusive to another in Django Tables
I have two models here, related to each other. What I am trying to do here is to avoid repetition. For example in grade 9, their can only be one rollno = 32 (cannot have two) but two same roll numbers in different grades are possible. Example: name= Mark, grade=9, rollno = 32 and name = Shub, grade = 9, rollno = 32 shouldn't be possible but name= Mark, grade=9, rollno = 32 and name= Mark, grade=10, rollno = 32 should be possible. class Grade(models.Model): grade = models.CharField(max_length=255, primary_key=True) class Student(models.Model): name = models.CharField(max_length=255) grade = models.ForeignKey(grade, on_delete=models.CASCADE) rollno = models.BigIntegerField() I am not quite sure how to add this functionality. Thanks! -
Django Inner Join on Derived Query
I have two models shown as follows. I want to be able to execute this query through the django ORM, essentially giving me the CustomUser class alongside two derived fields: max(message.sent_at) and max(case when read_at is null then 1 else 0 end). Those two fields would enable me to sort threads of messages by usernames and latest activity. Here are my classes: class CustomUser(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() username = models.CharField(_('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={'unique': _('A user with that username already exists.'),},) email = models.EmailField(_('email address'), blank=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'),) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'),) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) bio = models.TextField(max_length=500, null=True, blank=True) location = models.CharField(max_length=30, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) phone_number = PhoneNumberField(default='+10000000000') gender = models.CharField(max_length=32, choices=[(tag.name, tag.value) for tag in GenderChoice], default=GenderChoice.UNSPECIFIED.value) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: ordering = ['username'] verbose_name = _('user') verbose_name_plural = _('users') and class … -
Django site on Ubuntu 18.04 with Apache2 not working after installing SSL
I'm trying to deploy my Djang(1.10) application on Ubuntu 18.04 with Apache2 using mode_wsgi, the site was working perfectly well before setting up the SSL, but when I install the SSL certificate from Let'sEncrypt using certbot the is not loading anymore. Here's my configurations: Project folder path: /home/abdul Http configuration: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName www.orderfetchers.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it … -
Djngo/Nginx docker image returning Bad Request (400)
I followed this guide to dockerize my django blog, so after I got it running I decided to test it on my VPS. However, as soon as I try to access my app from a browser I get "Bad Request (400)". I've check lsof -i :1337 to check if the app was listening, at it seems to be working fine. Here are my configuration files: docker-compose.yml version: '3' services: web: build: ./app command: gunicorn ASSB.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 volumes: - ./app/:/usr/src/app/ - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media ports: - 8000:8000 nginx: build: ./nginx volumes: - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media ports: - 1337:80 depends_on: - web volumes: static_volume: media_volume: nginx.conf upstream assb { server web:8000; } server { listen 80; location / { proxy_pass http://ASSB; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /usr/src/app/static/; } location /media/ { alias /usr/src/app/media/; } } Any idea what could I be doing wrong? Sorry for the lack of experience, I'm new to docker and nginx, but I still wanted to give it a shot... -
django rest framework email verification using generic view
I am done with the registration as you can see. Now I want to send email verification so users can confirm. So once a user register, he/she gets a mail for confirmation. how do I send email verification using "ListCreateAPIView"? Do I need a third party package? Can someone help me out? Thanks Here is my view class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer My serializer.py class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) username = serializers.CharField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField(min_length=8, style={'input_type': 'password', 'placeholder': 'Password'}) def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user class Meta: model = User fields = ('id', 'username', 'email', 'password') -
Api response is null when consumed, in Django Rest
Im using my api from the rest framework, when I got to the URL from the api it shows's it correct. But when I consume it the response seems to be null. Im hosting both project (front vuejs and back django) in diferents ports (8080 and 8000, respectively). CORS are allowed. I've tried with another tools like fetch or jquery and seems to be the same. Js: export class APIService { contructor() {} get_user_id(){ const url = `http://localhost:8000/api/v1/user-id/`; r use axioseturn axios.get(url).then(function (response) { console.log(response); // For testing return response.data; }); } Django api view, for that url: class UserIdLoggedView(APIView): def get(self, request): user = request.user return Response({ 'id': user.id, }) For this case I didn't need a serializer. This is how the django rest shows it: { HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "id": 1 } And this is the output of the response from the console (just the data part) data: id: null Instead of return id=1 as expected it return null. -
Django Messages Framawork is not shown with index
Django Messages Framawork is not shown with index. The error message is displayed normally, however I need to get the status of the message before the array. I tried using the index of the message array, but it did not display. Would anyone know where I'm going wrong? Thank you. {% if messages %} <script> Swal.fire({ type: {{ messages.0.tags }}, <-------- Is not shown title: 'Title', html: '<ul class="messages" style="list-style: none;padding: 0;">\n' + ' {% for message in messages %}\n'+ ' <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>\n'+ ' <div class="notification is-{% if message.tags == 'error' %}danger{% else %}success{% endif %}">\n'+ ' {{ message }}\n'+ ' </div>\n'+ ' </li>\n'+ ' {% endfor %}\n' + ' </ul>' }) </script> {% endif %} -
How to run celery periodic task from a date in future?
I know how to run a task periodically. But, instead of starting the task immediately, I would like the task to run periodically from tomorrow at 10:48 PM every 5 minutes. How would you do it? And also additionally, if I want this periodic task to stop day-after-tomorrow at 04:05 AM. How would you do it? -
"python -m django --version" 1.11.18 Cannot update to 2.1
I'm new to Python and Django, I watched a tutorial that requires me to have Django 2.1. When I type in "python -m django --version" - my Ubuntu terminal says 1.11.18 But, when I type "django-admin --version" - terminal says 2.1 This didn't bother me until I reached part 6 of this series, I'm balls deep now with a serious problem I can't figure out. I even completely reinstalled my OS, (I was running linux mint, thought it'd be easier if I ran Ubuntu) I ran through a myriad of different "fixes" I found online, but nothing seemed to fix this. The main issue that I ran into from the tutorial is the urls linking, I'm not sure if that helps, but it's there. Thanks -
Invalid schema when trying to display cryptocontrol api data on webpage
I am trying to get a news feed going on my site. I'm using the cryptocontrol.io API to get the data. I was trying to sort the tags I need from the resulting JSON output I got. However after spending 2 days on this I cannot figure out how to get the webpage to display what I want. Request Method: GET Request URL: http://192.168.0.5:8000/news/ Django Version: 2.1.5 Exception Type: InvalidSchema Exception Value: No connection adapters were found for '[{'_id': '5c60a311b39d87001ad7e62c', 'hotness': 71751.83108878958, 'activityHotness': 0.11988508587451652, 'primaryCategory': 'General', 'words': 254, 'similarArticles': [], 'coins': [{'_id': '59d21e9b83a0523906a45dc5', 'name': 'EOS', 'slug': 'eos', 'tradingSymbol': 'eos'}, {'_id': '5a7b931102ac032bc99781f1', 'name': 'DATA', 'slug': 'data', 'tradingSymbol': 'dta'}], 'description': 'A little over a week ago, Lumeos, a social survey blockchain platform that allows users to post and answer polls for token rewards, announced that it is officially live on the EOS (EOS) mainnet. We’ve been busy! Check out our latest updates from VC funding to #EOS mainnet launch and a sneak peak on…', 'publishedAt': '2019-02-10T22:16:02.000Z', 'title': 'Social Dapp Lumeos Launches on the EOS (EOS) Mainnet', 'url': 'https://cryptocontrol.io/r/api/article/5c60a311b39d87001ad7e62c? ref=5c40adf1b7c4df0010a2f1c8', 'source': {'_id': '5ae36dc38f09a0000f8c9719', 'name': 'SludgeFeed', 'url': 'https://sludgefeed.com'}, 'thumbnail': Traceback: File "C:\Users\Ace\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\Ace\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\base.py" in _get_response … -
Django vs JS Frameworks
How powerful are the frontend features of Django compared to heavy JS frameworks like React and Vue.js? If I plan to develop a bold web app with including a CRM module, and for an example with a Kanban Board, is that something achievable with Django alone or would I need another JS framework to back it up? -
Django Restframework with YearArchiveView?
I want to get all possible list of years or months of my models with DateTime Field in RestFramework , is it possible to do so? I know that django has a YearArchiveView for listing all the possible years of my model, but it use django templates, I need to get REST api with my frontend React JS based apps. -
Django: Set ImageField from media file
I'm trying to create a manage script to quickly populate some models after creating a fresh db and I want to set an ImageField from a relative image path. Apologies if this is a duplicate, I couldn't find anything with this specific use case. I got the model creation to succeed, but then the admin view image url wasn't correct. current_dir = os.path.dirname(os.path.abspath(__file__)) base_dir = os.path.dirname(os.path.dirname(os.path.dirname(current_dir))) images_dir = os.path.join(base_dir, 'static/media/images') image_path = os.path.join(images_dir, 'some-picture.png') with open(image_path, mode='rb') as image: MyModel.objects.create(image=File(image), ...) class MyModel: ... def image_tag(self): return mark_safe(f'<img src="{self.image.url}" />') image_tag.short_description = 'Image' image_tag.allow_tags = True in admin.py: class MyModelAdmin(admin.ModelAdmin): ... fields = ('image_tag',) readonly_fields = ('image_tag',) -
How to efficiently utilize celery to execute multiple tasks under 1 second?
I am working on a web application which is hosted on a "DigitalOcean" server: 4GB RAM 2 vCPUs 25GB SSD I have 20+ tasks. Each task takes 0.2 to 1 second. I want all these 20+ tasks to execute parallelly i.e, they must all complete execution under 1 second. I am using celery to execute these tasks periodically every 1 second(24/7). The application is designed such if a task is not executed under 1 second from its previous execution, the task is removed. (Another task task_remover checks regularly and removes tasks.) I'm using eventlet and 2 workers with -c 20. So, I start with 20+ tasks to be executed every second under 1 second. This runs for a while. But after a few hours, all tasks are being removed(not at once). So, my questions with the above server configuration are: Are these tasks actually executed in parallel? 0.2*20 tasks = 4.0 seconds/2 vCPUs = 2.0 seconds for the completion of all tasks? Should I continue with eventlet or use prefork? Should I go for parallelism or concurrency? how? What configuration would you recommend? How many vCPUs and How much RAM? The target is I need these 20+ tasks running 24/7 … -
What are the alternatives to using django signals?
I am working on a project where I need to recalculate values based on if fields changed or not. Here is an example: Model1: field_a = DatetimeField() calculated_field_1 = ForeignKey(Model2) Model2: field_j = DatetimeField() If field_a changes on model1 I have to recalculate the value for field calculated_field_1 to see if it needs to change as well. The calculations that are done require me querying the database to check values of other models and then determining if the value of the calculated field needs to change. Example) field_a changes then I would have to do this calculation result = Model2.objects.filter(field_j__gte=Model1.field_a) If result.exists(): Model1.field_a = result.first() Model1.save(update_fields=(‘field_a’,)) This is the most basic example I could think of and the queries can be much more complicated than this. The project started out with one calculation when a field changed so I decided the best approach was to use django signals. Months later the requirements have changed for the project and now there are several other calculations that I had to implement that are very similar to the example above. I have noticed that my post_save function is getting out of hand and I am just wondering what alternatives there are to using …