Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to count new data before executing a function again
I have this function that do automatic execution of send_sms function when certain conditions are met. That it will execute if the count for specific levels are detected. I'm using celery to automatically execute it when needed. But my problem now is like this. if the responses.count() >= 50: then it will execute send_sms function. but when it reaches 51 after the first execution it is still executing and it must not. I want it to recount again another NEW 50 for another execution. How can I do it? Thanks! def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=3), ) if responses.count() >= 50: send_sms(request) return HttpResponse(200) -
Auth0 on Heroku: Infinite redirect loop on login
I am attempting to set up a django app on heroku that uses auth0. Previously I have not had an issue with any of these things and it all worked fine locally. However they seem to have come together to make a perfect storm of an issue. Upon submitting a login with auth0 using the google oauth, the page redirects back to the login. This is an infinite loop. Previously when it was remembering the user it would do this infinitely. If it is not remembering it will simply take you back to the initial login page at domain.com/login/auth0. Here is how the server handles it locally, and here is the loop on heroku. Everything on the django end is boilerplate, and as mentioned, works fine locally. The auth0 redirects are set up properly, as is the google-oauth setup with auth0. Independently all these things work fine, but for some reason they are breaking down on heroku. It is worth mentioning that when the user was being remembered and the infinite loop cycled through, eventually it hit an error page that mentioned this may be caused by disabling or refusing cookies. It is also worth noting that the auth0 site … -
Get JS notification when django form fails client-side validation
I have a django template showing a form. I added a "loading" image when hitting the submit: <input type="submit" value="Search" name="search" onclick="show_loading();"/> In case of a validation error (like not choosing any option in a multi-choice field), since the form does client-side validations, I see the loading AND the error tooltip, but the page is disabled (that's what my show_loading function does). How can I get a feedback from the form that there is a validation error, so I can remove the loading image? -
How to load a file from code instead of form field
As I don't have much experience with python and django I would like to ask about loading a file into a variable from code. Here is my scenario: User sends the data to my django backend with POST with some parameters like this: { templateName: exampleTemplate.html filename: instanceFileFromTemplate.pdf } The purpose of that request is to select appropiate html template and generate output pdf file with some specific data inside. So My Django backend function selects desired exampleTemplate.html template and with weasyprint generates a instanceFileFromTemplate.pdf file. Then I should prepare (programatically) a POST body/Form, where I will attach my newly generated file and save an instance into my Model { fileName: instanceFileFromTemplate.pdf, file: -here should be a file-, creationDate: 2020-01-07 } How to do load my file into a file variable ? When I print an example body, prepared in a POSTMAN it looks like this: {'filename': ['instanceFileFromTemplate.pdf'], 'creationDate': ['2020-01-07'], file': [<InMemoryUploadedFile: instanceFileFromTemplate.pdf (application/pdf)>]}> So basically I know i need to prepare Dict variable, but how to load into my Dist a file ? -
Can't save new objects in Django full-text search with PostgreSQL
I'm following this post on how to add full-text functionality to my Django app. I have the following model: class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) class Author(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete = models.CASCADE) name = models.CharField(max_length = 250) alternative_names = ArrayField(models.CharField(max_length = 250),blank=True,null=True) name_norm = models.CharField(max_length = 250,blank=True,null = True) slug = models.CharField(max_length = 250,unique = True) photo = models.ImageField(upload_to = 'imgs/users/%Y/%m/%d',blank = True) search_vector = SearchVectorField(null=True) def save(self, *args, **kwargs): self.search_vector = (SearchVector('name', weight='A') ) super().save(*args, **kwargs)`enter code here` And when I try to save a new author with save: autor = Author(user = utilizador,name = author_name,alternative_names = alternative_names,name_norm = name_norm,slug = slug) autor.save() I get the error: Traceback (most recent call last): File "populate_v2.py", line 140, in <module> autor.save() File "/home/mwon/NewArquivoOpiniao/webapp/colunadeopiniao/accounts/models.py", line 57, in save super().save(*args, **kwargs) File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 748, in save self.save_base(using=using, force_insert=force_insert, File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 785, in save_base updated = self._save_table( File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 890, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 927, in _do_insert return manager._insert( File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1393, in execute_sql for sql, params in self.as_sql(): File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1336, … -
How to order queryset by using SerializerMethodField?
How to order queryset by using SerializerMethodField? i need to sort by using serializermethodfields such as submissions, effectiveness. #models.py class Vendor(CreateModificationDateMixin): user = models.OneToOneField(User_Profile, on_delete=models.CASCADE, primary_key=True) job_title = models.CharField(max_length=100, default=None) phone_regex = RegexValidator(regex=r'^+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") is_prefered = models.BooleanField(default=False, editable=False, blank=True) number_of_employees = models.CharField(max_length=255, blank=True) company_regex = RegexValidator(regex=r'^+?1?\d{9,15}$', message="company number must be entered in the format: '+999999999'. Up to 15 digits allowed.") company_phone_number = models.CharField(validators=[company_regex], max_length=17, blank=True, null=True) fax_regex = RegexValidator(regex=r'^+?1?\d{9,15}$', message="fax number must be entered in the format: '+999999999'. Up to 15 digits allowed.") fax_number = models.CharField(validators=[fax_regex], max_length=17, blank=True, null=True) def __str__(self): return self.user.username class Meta: verbose_name_plural = "vendors" db_table = 'vendor' #serializers class AllVendors(DjongoModelSerializer): user = UserProfileSerilaizer(required=True) is_prefered = SerializerMethodField() submissions = SerializerMethodField(read_only=True) effectiveness = SerializerMethodField(read_only=True) hotlist_count = SerializerMethodField(read_only=True) lastupdated_at = SerializerMethodField(read_only=True) class Meta: model = Vendor fields = '__all__' depth = 1 def get_lastupdated_at(self,obj): candidate = list(CandidateList.objects.filter(vendor_id=obj.user_id).order_by('-modification').values_list('modification',flat=True)) if candidate: return candidate[0] else: return '' def get_hotlist_count(self,instance): return CandidateList.objects.filter(vendor_id=instance.user.id).filter(candidate_status='Candidate Available').count() def get_is_prefered(self, obj): try: client_id = self.context['request'].user.id is_prefered = PreferredVendors.objects.filter(user_id=client_id).filter(vendor_id=obj.user.id).values('is_prefered') if len(is_prefered)>0: return is_prefered else: return [{'is_prefered':False}] except: return [{'is_prefered':False}] def get_submissions(self,obj): return SubmittedCandidate.objects.filter(vendor=obj.user.id).count() def get_effectiveness(self,obj): confirm_candidates = SubmittedCandidate.objects.filter(vendor=obj.user.id).filter(interview_status='Selected Final').count() total_submissions = SubmittedCandidate.objects.filter(vendor=obj.user.id).count() onboarding = SubmittedCandidate.objects.filter(vendor=obj.user.id).filter(interview_status='OnBoarding').count() starts … -
How to make Searching functionality for whole database in django/DRF using single API?
How to make Search in whole database using django/DRF single API? For example we can do this for single model search using django/DRF API:- `class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['category', 'in_stock']` You can see the whole example in this:- https://www.django-rest-framework.org/api-guide/filtering/ Thank you in ADVANCE. -
Django Rest Framework: Connection not showing queries from custom permission class
I am using Django's Rest Framework, and am trying to assert the number of queries for an endpoint in a test case. I am using django.db.connection.queries to get the queries, but it doesn't include the queries from the permission_classes. I am using a custom permission class that implements has_object_permission. Is this expected behavior? Is the only way around this to test the has_object_permission function directly? -
Force maximum number of records with attribute in Django
In Django, is there a "Djangonic" way to ensure a model doesn't have more than n records with a certain value for an attribute? For instance, how to ensure on the example below that no more of two records for MyModel have my_attribute set to True? class MyModel(models.Model): my_attribute= models.BooleanField(default=False) -
Django Admin method returns multiple instances instead of one
I have a very simple model: class Product(models.Model): name = models.CharField("name", max_length = 128) def __str__(self): return self.name class Store(models.Model): store_id = models.PositiveIntegerField(unique = True) product = models.ForeignKey(Product, on_delete = models.CASCADE, null = True, blank = True) which is displayed in the admin by: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ["name", "get_stores"] def get_stores(self, obj): s = [s.store_id for s in Store.objects.filter(product = obj)] if s: print("store/product:", s, obj) return s and leads to the error, that I see every product in the list of products as often as I have stores for it. Output: store/product: [457, 1179383, 1179384] Cake store/product: [457, 1179383, 1179384] Cake store/product: [457, 1179383, 1179384] Cake (exactly the same in the admin product list). How can I avoid multiple appearances? -
Default User Model OneToOneField Attribute Error
I am trying to connect the default Django User model with another one I made to store extra info. but even after following all the proper steps, I am getting an error. I have spent way to much time trying to figure it out, hopefully, you guys can figure it out and help me. (you probably will you all are much smarter than me) here is the import command : from django.contrib.auth.models import User here is the integration with the premade model: class User_Info(models.Model): user = models.OneToOneField(User,null = True, on_delete = models.CASCADE) here is the view I am using : def userPage(request): _user_ = request.user.User_Info.all() trades = request.user.User_Info.trade_set.all() total_trades = trades.count() context = {"_user_" : _user_,"trades" : trades, "total_trades" : total_trades} return render(request, "accounts/user.html", context) This is the error I am getting: AttributeError at /user/ 'User' object has no attribute 'User_Info' Request Method:GET Request URL:http://127.0.0.1:8000/user/ Django Version:3.1.2Exception Type:AttributeError Exception Value:'User' object has no attribute 'User_Info' if you need any more information let me know I will be more than happy to help! Thank you for your time! :) -
a tag is not enter(Django)
I'm making website using Python Framework of 'Django'. I have some problems with Django about tags. If you click the Year-2021 a tag on the http://127.0.0.1:8000/blog/archive/ site, it will not enter the homepage. I'd like to know what's wrong and how to fix it. mysite/urls.py contains: """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from bookmark.views import BookmarkListView, BookmarkDetailView urlpatterns = [ path('admin/', admin.site.urls), path('bookmark/', include('bookmark.urls')), path('blog/', include('blog.urls')), ] blog/urls.py contains: from django.urls import path, re_path from blog import views app_name='blog' urlpatterns=[ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<str:month>/', views.PostMonthArchiveView.as_view(), name='post_month_archive'), # … -
How to leave content unaffected when changing pages Django
So I have a song player/bar that I want to implement into my Django project. It is a Django partial/template component that will give the user all the basic controls such as playing, pausing, volume, and skipping. When you changing pages and urls, obviously, everything in the HTML has to be re-rendered. This creates a problem for my music player since rendering would interrupt the processes of the music player (like playing music). What if there is a workaround to this? Where I can change pages without my player being affected and disrupted. I want my player to be similar to the players of Spotify or Soundcloud, where you literally have to exit the website or reload the page for the players to be interrupted. Thanks. -
Dealing with popups javascript and django
I'm currently struggling to deal with a javascript popup in django. That probably doesn't seem very clear! Let me illustrate. On the first image, i have a form to create a painting. However, i would like to add a new artist (an django model), and link that artist to the painting i'm trying to create. So, i created a popup, which can be seen on the second image. But when i hit the create button, not only does the popup not close, but after i closed it manually, i am forced to refresh the painting-form-page to see the newly created artist appear in the dropdown. First of all, do you see what i'm trying to do (sorry my english isn't very good :) ) ? Second, if you could give me some path to follow to build what i'm trying to do, that would be very much appreciated! Thank you very much! -
print nested inner data in python
I want to print the total_price data in this nested queryset. tried: print(data['quotes_description']['total_price']) but it's throwing me TypeError: list indices must be integers or slices, not str. If any help would be much appreciated. thank you so much in advance. "data": [ { "id": 35, "quotes_description": [ { "id": 51, "total_price": 0, }, { "id": 52, "total_price": 3000, } ], } ] -
Not ImplementedError: subclasses of BaseDatabaseOperations may require a date_trunc_sql() method
I was using Django to build a simple blog site, and tried to use context processors for the Monthly blog archive (such as 2020-12). in models.py class Article(models.Model): time_publish = models.DateTimeField() in context_processors.py def Side_Menu_Context(request): return { 'QS_YM_BlogCount':Article.objects.datetimes('time_publish','month',order='DESC') \ .values('time_publish')\ .annotate(num_of_article=Count('id')), } in setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"static")], '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', 'IoTSite.context_processors.Side_Menu_Context', ], }, }, ] in Base_Layout.html which is the base template inherited by all other templates. <aside> <div>Archive</div> <ul> {% for item in QS_YM_BlogCount %} <li><a href="#">{{item.time_publish.year}}-{{item.time_publish.month}} ({{ item.num_of_article }})</a></li> {% endfor %} </ul> </aside> When I run the server and try to access homepage, encountered below error: NotImplementedError at / subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method Request Method: GET Request URL: http://info.yanatm.fun/ Django Version: 2.2.17 Exception Type: NotImplementedError Exception Value: subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method Exception Location: C:\Users\yantian\Anaconda3\lib\site-packages\django\db\backends\base\operations.py in datetime_trunc_sql, line 141 Python Executable: C:\Users\yantian\Anaconda3\python.exe Python Version: 3.7.3 Python Path: ['Z:\\Documents\\IoT\\ec2-user\\IoTSite', 'C:\\Users\\yantian\\Anaconda3\\python37.zip', 'C:\\Users\\yantian\\Anaconda3\\DLLs', 'C:\\Users\\yantian\\Anaconda3\\lib', 'C:\\Users\\yantian\\Anaconda3', 'C:\\Users\\yantian\\Anaconda3\\lib\\site-packages', 'C:\\Users\\yantian\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\yantian\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\yantian\\Anaconda3\\lib\\site-packages\\Pythonwin'] Error during template rendering In template Z:\Documents\IoT\ec2-user\IoTSite\static\Base_Layout.html, error at line 37 subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method 27 </nav> 28 29 <main> 30 {% block main %} 31 {% endblock … -
Page-scope variables in Django
I'm new to Django and Python. What I'm trying to achive is so simple in other frameworks that I am familiar with. But I couldn't find an easy/quick way for it in Django on the internet. I wouldn't use templates for this very basic operation if unnecessary. {% for tweet in tweets.itertuples %} {% if tweet.sent == 'pos' %} {% with color_class='text-success' %} {% endwith %} {% with fa_class='smile' %} {% endwith %} {% elif tweet.sent == 'neg' %} {% with color_class='text-danger' %} {% endwith %} {% with fa_class='frown' %} {% endwith %} {% else %} {% with color_class='text-muted' %} {% endwith %} {% with fa_class='meh' %} {% endwith %} {% endif %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ tweet.unix }}</small> </div> <h2> <i class="fa fa-{% if true %} smile {% endif %} text-{% if true %} success {% endif %}"></i> <a class="article-title text-{% if tweet.sent == 'pos' %} 'success' {% endif %}" href="#"> {{ tweet.sentiment }} </a> </h2> <p class="article-content">{{ tweet.tweet }}</p> </div> </article> {% endfor %} the following part doesn't get rendered as I want. <i class="fa fa-{% if true %} smile {% endif %} text-{% if true %} success {% endif %}"></i> <a class="article-title … -
Django How to access the url "/admin" (SuperUser) skipping this path("<str:x>", views.xx) in urls.py?
Django How to access the url "/admin" (SuperUser) skipping this path("str:x", views.xx) in urls.py ? -
Django Form not saving for Custom User Model
I have a register user form which is doing all the validation as expected. However, it is not saving. I am not able to figure out the reason. How do I debug it ? Any help ? I am a newbie to forms and formviews any good document with example would really help me. class RegisterForm(forms.ModelForm): phone_number = forms.IntegerField(required=True) password1 = forms.CharField(widget=forms.PasswordInput()) password2 = forms.CharField(widget=forms.PasswordInput()) country_code = forms.IntegerField() #schools = school.objects.all() #school_name = forms.ModelChoiceField(queryset=school.objects.distinct()) MIN_LENGTH = 4 class Meta: model = User fields = ['username','country_code','phone_number', 'password1', 'password2', 'full_name' ] def clean_phone_number(self): phone_number = self.data.get('phone_number') print(phone_number) if User.objects.filter(phone_number=phone_number).exists(): raise forms.ValidationError( _("Another user with this phone number already exists")) if len(phone_number) == 10 and phone_number.isdigit(): pass else: raise forms.ValidationError( _("Invalid Phone Number")) return phone_number def save(self, *args, **kwargs): print("saving") user = super(RegisterForm, self).save(*args, **kwargs) user.set_password(self.cleaned_data['password1']) print('Saving user with country_code', user.country_code) user.save() return user Views.py class RegisterView(SuccessMessageMixin, FormView): template_name = 'register-2.html' form_class = RegisterForm success_message = "One-Time password sent to your registered mobile number.\ The verification code is valid for 10 minutes." def form_valid(self, form): full_name=self.request.POST["full_name"] user = form.save() print(user.id) username = self.request.POST['username'] password = self.request.POST['password1'] user = authenticate(username=username, password=password) kwargs = {'user': user} self.request.method = 'POST' print("User created") The print in clean_phone_number … -
VueJS - how can i edit my components in production?
I recently deployed a Django-VueJS application that uses django webpack-loeader to load Vue components in my Django template. I deployed the application to Digital Ocean and everything works. Now i edited the code in one of my components and once i saved, i expected to see the edited component, but instead i will still see the old version of the component before i edited it. I tried to clean my cache but it didn't work, so i guess there is something else i need to do. Here is my vue.config.js const BundleTracker = require("webpack-bundle-tracker"); const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; const pages = { 'main': { entry: './src/main.js', chunks: ['chunk-vendors'] }, } module.exports = { pages: pages, runtimeCompiler: true, filenameHashing: false, productionSourceMap: false, publicPath: process.env.NODE_ENV === 'production' ? 'static/vue' : 'http://localhost:8080/', outputDir: '../django_vue_mpa/static/vue/', chainWebpack: config => { config.optimization .splitChunks({ cacheGroups: { moment: { test: /[\\/]node_modules[\\/]moment/, name: "chunk-moment", chunks: "all", priority: 5 }, vendor: { test: /[\\/]node_modules[\\/]/, name: "chunk-vendors", chunks: "all", priority: 1 }, }, }); Object.keys(pages).forEach(page => { config.plugins.delete(`html-${page}`); config.plugins.delete(`preload-${page}`); config.plugins.delete(`prefetch-${page}`); }) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../vue_frontend/webpack-stats.json'}]); // Uncomment below to analyze bundle sizes // config.plugin("BundleAnalyzerPlugin").use(BundleAnalyzerPlugin); config.resolve.alias .set('__STATIC__', 'static') config.devServer .public('http://localhost:8080') .host('localhost') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({"Access-Control-Allow-Origin": ["*"]}) } }; I'm … -
django-tenant-schemas getting confused with default subdomain of url
The url of my application is stagging.domain.com in the database my default schema domain_url is stagging.domain.com and the domains for tenants are: tenant1.stagging.domain.com tenant2.stagging.domain.com But when I try to access the default schema I get this error: No tenant for 'stagging.domain.com' When i try to access the other ones works fine. My guess is that is thinking stagging is a schema -
Django + HTML: If and Else statement in template not working. it always goes to the if, even when user has no profile image, dummy image not shown
Correct me if I am wrong, but i am 99.99% sure that all my codes are correct. Basically in my template, I am trying to set a default image, if user has no profile image, they will be rendered the dummy image, but if they have a profile image, their profile image will show. But somehow, If I have a profile pic, yes my profile pic will show If I dont have a profile pic, nothing will show. There wont be any dummy image The static is loaded correctly, and the else also works, because I tried, but just somehow, the dummy image does not show up for someone that does not have a profile pic. Can anyone explain why? Thanks def account_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") try: account = Account.objects.get(pk=user_id) except: return HttpResponse("Something went wrong.") if account: context['id'] = account.id context['username'] = account.username context['email'] = account.email context['profile_image'] = account.profile_image.url context['hide_email'] = account.hide_email context['BASE_URL'] = settings.BASE_URL return render(request, "account/account.html", context) MODELS.PY class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image) def get_profile_image_filename(self): return str(self.profile_image)[str(self.profile_image).index('profile_images/' + str(self.pk) + "/"):] def get_profile_image_filepath(self, filename): return 'profile_images/' + str(self.pk) + '/profile_image.png' … -
How to implement real-time comment system in a django-react app with channel/celery/redis etc..?
I have a web-app with Django backend and react frontend where inside an organization or company, there are multiple users. Now, I am trying to implement real-time commenting system where if one user types any comment and posts it, another user will be able to see it without refreshing the page. I have seen some examples of asynchronous tasks using celery with redis but couldn't find any with react implementation. What would be a good approach towards achieving the real-time comment system in the react/django app? -
It's possible to perform db operations asynchronously in django?
I'm writing a command to randomly create 5M orders in a database. def constrained_sum_sample( number_of_integers: int, total: Optional[int] = 5000000 ) -> int: """Return a randomly chosen list of n positive integers summing to total. Args: number_of_integers (int): The number of integers; total (Optional[int]): The total sum. Defaults to 5000000. Yields: (int): The integers whose the sum is equals to total. """ dividers = sorted(sample(range(1, total), number_of_integers - 1)) for i, j in zip(dividers + [total], [0] + dividers): yield i - j def create_orders(): customers = Customer.objects.all() number_of_customers = Customer.objects.count() for customer, number_of_orders in zip( customers, constrained_sum_sample(number_of_integers=number_of_customers), ): for _ in range(number_of_orders): create_order(customer=customer) number_of_customers will be at least greater than 1k and the create_order function does at least 5 db operations (one to create the order, one to randomly get the order's store, one to create the order item (and this can go up to 30, also randomly), one to get the item's product (or higher but equals to the item) and one to create the sales note. As you may suspect this take a LONG time to complete. I've tried, unsuccessfully, to perform these operations asynchronously. All of my attempts (dozen at least; most of them using sync_to_async) … -
Django stream function prints live
I have a Django portal which run automation jobs and respond to the User with live output using Ajax. The current setup is, django is just the front end and we have a standalone Python tool to do the automation itself. So front end use Ajax call to Django. Django will run subprocess to execute the automation tool and return STDOUT live to Ajax call. Now we want to transform the automation tool to be an app inside Django so we can Unify many things. I manage to do all transformation so instead of calling a subprocess, you just call a function. I manage to grab the function STDOUT as well with the help of the below article (Generator from function prints)Generator from function prints) it is working fine except it is not live. it just iterate the STDOUT after the function is completed, not during execution. I want to know what is the best practice to do that.