Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to automatically generate a field based on the choice of a previous field
I have a model and some serializers in Django Rest Framework. I would like to have choices for the "service_interval" field and then based on what they choose it generates the date correctly in the database. How would I do this? Here's my code. class Snippet(VIPSnippet): title = models.CharField(max_length=100, blank=True, default='') service_interval_choices = [ (3, '3 Months'), (6 , '6 Months'), (9, '9 Months'), (12, '1 Year'), ] service_interval = models.IntegerField(choices=service_interval_choices) next_service = models.DateTimeField() Serializers class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: model = Snippet fields = ['url', 'service_interval'] next_service = datetime.datetime.now() + datetime.timedelta(3*365/12) When I do it this way I get the following error NOT NULL constraint failed: snippets_snippet.next_service I plan to replace the '3' in datetime.timedelta(3*365/12) with service_interval or whatever variable I would need so that it generates the date however may months in the future as needed. -
View.py won't get ajax but I can update the database by passing JSON directly in the url, Django
I'm following this tutorial https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json I'm trying to update my database with the CreateCrudUser class, but when I click submit the data goes to the end of the url and it doesn't update the databse. If i add the word "create" in front of the JSON it puts in the url it will update the database. View.py class CrudView(ListView): model = models.CrudUser template_name = 'newsfeed/crud.html' context_object_name = 'users' class CreateCrudUser(View): def get(self, request): name1 = request.GET.get('name', None) address1 = request.GET.get('address', None) age1 = request.GET.get('age', None) obj = models.CrudUser.objects.create( name = name1, address = address1, age = age1 ) user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age} data = { 'user': user } return JsonResponse(data) url.py from django.urls import path, include from social_method.apps.newsfeed import views app_name = "newsfeed" urlpatterns = [ #path('observation-feed/', views.ObservationFeed, name='observation-feed'), path('', views.ObservationFeed, name='observation-feed'), path('observation/<str:pk>/', views.ObservationThread, name='observation'), path('new-social-method/<str:pk>/', views.SocialMethod, name='new-social-method'), path('crud/', views.CrudView.as_view(), name='crud_ajax'), path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'), ] models.py class CrudUser(models.Model): name = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=100, blank=True) age = models.IntegerField(blank=True, null=True) html <div class="container"> <h1>Django Ajax CRUD</h1> <h2>{% url "newsfeed:crud_ajax_create" %}</h2> <div class="row"> <div class="col-md-4 "> <h3>ADD USER</h3> <form id="addUser" action=""> <div class="form-group"> <input class="form-control" type="text" name="name" placeholder="Name" required> </div> <div class="form-group"> <input class="form-control" type="text" name="address" placeholder="Address" required> </div> <div class="form-group"> <input … -
Django Form: django-autocomplete-light is showing empty dropdown
I am building a web app in Django trying to use django-autocomplete-light(v.3.8.2) to create an auto-complete field. I have form that allows users to create a Trade record. I'm trying to add an auto-complete field for Trade.owned_game (a lookup field). I am just getting an empty dropdown field for the auto-complete field (screenshot attached at bottom of this post) Below is my code: models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Game(models.Model): name = models.TextField() # Unrestricted text platform = models.CharField(max_length=100) # character field created_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name # return game name when game.objects.all() is called class Trade(models.Model): name = models.TextField() # Unrestricted text created_date = models.DateTimeField(default=timezone.now) is_trade_proposed = models.BooleanField(default=False) user_who_posted = models.ForeignKey(User, on_delete=models.CASCADE) owned_game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='owned_game', db_column='owned_game') def __str__(self): return self.name # return game name when game.objects.all() is called urls.py: from django.urls import path from django.conf.urls import url from .views import ( PostListView, TradeListView, PostDetailView, TradeCreateView, GameAutoComplete, PostUpdateView, PostDeleteView, UserPostListView ) from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('post/new/', views.trade_new, name='trade-create'), url( r'^game-autocomplete/$', GameAutoComplete.as_view(), name='game-autocomplete') , ] views.py: from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, … -
django AuthenticationForm how to remove error messages
I created a custom error message for auth form, however, I'm not sure how to remove the error message from django AuthenticationForm? Any help is appreciated, thank you! form: class CustomAuthForm(AuthenticationForm): class Meta: model = UserCreationForm fields = ['username','password'] def __init__(self, *args, **kwargs): super(CustomAuthForm, self).__init__(*args, **kwargs) self.fields['username'].widget = forms.TextInput(attrs={ 'placeholder': 'email'}) self.fields['username'].label = False self.fields['password'].widget = forms.PasswordInput(attrs={ 'placeholder':'password'}) self.fields['password'].label = False -
DRF - render SerializerMethodField in serializers.Serializer
I have a little problem with getting value from SerializerMethodField when using serializers.Serializer views.py: class StaticDataView(generics.RetrieveAPIView): serializer_class = serializers.StaticDataSerializer def retrieve(self, request, *args, **kwargs): serializer = self.get_serializer() return Response(serializer.data) serializer.py class AnimatorStaticDataSerializer(serializers.Serializer): data = DataSerializer(data=Data.objects.all(), many=True) user = serializers.SerializerMethodField() def get_user(self, obj): return UserSerializer(self.context['request'].user).data When I call to my API view, at the response I get only data key, user isn't rendered. I found that could be because SerializerMethodField is read_only=True and for this reason get_initial() from rest_framework/serializers.py doesn't render it. But how can I write it differently when I need to pass context with the user as an instance to UserSerializer. DataSerializer is also using request from context. -
Django How can I solve NoReverseMatch error?
I'm making the website using Django. I have a problem for url. I tried to access the website, but an error occurred. Error is NoReverseMatch. Reverse for 'add' with no arguments not found. 1 pattern(s) tried: ['purchase/order/(?P<CAT_ID>[^/]+)/$'] How can I solve this problem? # urls.py {% for value in object_list %} <tr> <form action="{% url 'purchase_order:add' value.CAT_ID %}" method="get"> <td scope="row">{{ value.CAT_ID }}</td> <td scope="row">{{ value.INFOR }}</td> <td scope="row"> <input type="submit" value="CREATE" class="btn btn-outline-secondary btn-sm"> </td> </form> </tr> {% endfor %} # urls.py app_name = 'purchase_order' urlpatterns = [ # CREATE URL path('order/<str:CAT_ID>/', views.Order_add_View.as_view(), name='add'), ] # views.py class Order_add_View(LoginRequiredMixin, CreateView): model = Purchase_Request # template_name = 'purchase_order/add.html' fields = ['CAT_ID', INFOR] def get(self, request, *args, **kwargs): CAT_ID = self.kwargs['CAT_ID'] return render(request, 'purchase_order/add.html', {'CAT_ID':CAT_ID}) def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) -
Dynamically end div class=row/start new div row HTML using mako template
I am trying to display a list of courses using a Mako for loop on my HTML page. Each course has it's own card, and I'm trying to end the row once there are three cards. I tried to use this loop % if (loop.index % 3): </div> <div class="row"> % end if But it would put two cards on the row, then one card on the next row, then 2, then 1, etc. I would like to use a loop because the number of courses to be displayed can change as more courses are added to the database. Here's my template file: (Technically, the language I'm using for my app is Django-Mako-Plus, so maybe this is a Django problem?) <div class="container"> <!-- TODO if using this style, figure out how to dynamically start/end bootstrap rows or similar solution --> <div class="row"> % for a in allcourses: <div class="col-md-4"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="${ STATIC_URL }homepage/media/courseimg/${a.coursephoto}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">${a.coursetitle}</h5> </div> <ul class="list-group list-group-flush"> <li class="list-group-item" style="text-align: center; font-style:italic; text-size:small;"><strong>${a.instructorid.instructorname} - Instructor</strong><br>${a.credithours.normalize()} Training Hours / 0.${a.credithours.normalize()} CEU</li> </ul> <div class="card-body"> <p class="card-text">${a.coursedescription|truncatewords:15}</p> <a href="/homepage/checkout/" class="btn btn-primary stretched-link">Learn More</a> </div> </div> </div> % if (loop.index % … -
Best approach to enrich User model in Django pluggable app
I am currently working on expanding https://github.com/suutari/drf-jwt-2fa, which provides two-factor authentication over jwt for rest-framework. I would like to make the two-factor auth non-enforced; that is, users should be able to choose if they want this extra security. For that purpose, I would like to add a boolean field (lets call it two_auth) to the user model. What is the best approach to add this field? I am currently thinking on some possibilities, but none of them seems to be neat enough: Create a relation table (user_id, two_auth) without foreign-key enforcement: I should use signals for user deletion Create a relation table (user_id, two_auth) with foreign-key enforcement: The foreign key should point to the model specified at settings.AUTH_USER_MODEL. I generally like model declaration parameters to be explicit, not patchable. -
Generate a random time for model queryset every ten minute
I am trying to generate random time beetween 20 hours a go and now, and assign it to a all queryset pass 24H. here what i make: from faker import Faker fake = Faker() from blogs.models import Post from django.utils import timezone import datetime def rotate_time(): now = timezone.now() day_pass = now - datetime.timedelta(hours=24) qs = Post.objects.filter(created__lt=day_pass) number = qs.count() lst = [] for _ in range(number): for t in [fake.date_time_between(start_date='-20h', end_date='now')]: lst.append(t) for i in lst: print(i) # this work fin until now <== x = 0 while x < len(lst): time = i[x+1] if qs.exists(): for item in qs: item.pud_date_rotation = time item.save() TypeError: 'datetime.datetime' object is not subscriptable -
Django vs Opencart, etc
What are advantages of using Django instead E-commerce/CMS systems on php? I want to make an e-commerce site for a clothing store with Django, but I'm interested to know why should I use the framework -
Dynamically update table when creating new enty using HTMX
After recent success in some simple HTMX tasks I wanted to extend adamchainz django-htmx example by a modal field that updates a table dynamically. I am not sure if I am returning the right thing in render ... but my problem is, the table is not being updated. Only when I hit reload. view: class CreateProductView(TemplateView): template_name = "app/product_create.html" form_class = OrderForm def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': self.form_class()}) def post(self, request): Product.objects.create(name = request.POST["name"], price = request.POST["price"]) part_template = "app/partial-rendering.html" return render(request, part_template, {"base_template": "app/_partial.html"}) urls.py: path("create/", views.CreateProductView.as_view(), name = 'create'), This is my index.html with the table in it: <div class="..."><button class="btn btn-primary" id="showButton" hx-get="/create" hx-target="#modal-create">create</button</div> <main role="main" id="main">{% include "app/orders_table.html" %}</main> <div id="modal-create"></div> I also have a partial-rendering.html in place: {% extends base_template %} {% block main %} {% include "app/product_table.html" %} {% endblock %} and a _partial.html: <main id="main"> {% block main %}{% endblock %} </main> I will not post the whole product_table.html here, I guess it is straight forward ... mainly: <table class="table table-striped table-hover"> <thead> <tr> <th>product name</th> <th>price</th> </tr> </thead> <tbody> {% for product in page.object_list %} <tr> <td>{{ product.name}}</td> <td>{{ product.price }}</td> </tr> {% endfor %} </tbody> </table> The … -
How to set X-FRAMES_OPTIONS to any other value than deny for Django media files embedding purposes?
I am developing a procedure where an already uploaded/generated file gets displayed in the user's dashboard through embed/iframe HTML tags. These files are HTML divs generated by plotly (Python, server-side generated). So when I try to view these files through iframe like this: <iframe width="100%" height="100%" frameBorder="0" src="http://127.0.0.1:8000/media/plots/20/plot-x-a-1.html" /> I get the following error through developers tools: Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'. As you are aware that usually it is solved by either disabling the XFramesOptions middleware entirely or to set it as ALLOWALL. The issue is, neither disabling this middleware nor adding these lines: X_FRAME_OPTIONS = 'ALLOWALL' XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE'] helped prevent the error. My guess is, media stream requires x_frames_options to be set to AllowAll or sameorigin but there is no documentation about how to do that. Is my reasoning correct? why would the browser still reject my iframe requests after such changes? Note: development is totally local at the moment. -
How to send a second (distinct) model instance to a template
Problem - I am displaying a form allowing a user to add a comment regarding an existing post. I also want to display the existing post (instance) on this same page (rendered template). The model for the template is the one accepting the comment (distinct from the post). How do I pass a model instance for the post data to the template so I can display the post too? Note - I also need the post instance because in order to store the comment in the database, it needs to be linked to the specific post id. This is probably easy and I'm missing something obvious - pointers to the right documentation welcome. I am just learning Django so I'm still learning my way around. Details: I have my model as follows (models.py): class Post(models.Model): type = models.ForeignKey( PostType, on_delete=models.PROTECT, related_name='posts', default=1 ) title = models.CharField(max_length=100) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.PROTECT, related_name='posts' ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments', ) body = models.TextField(max_length=1000) author = models.ForeignKey( get_user_model(), on_delete=models.PROTECT, ) def __str__(self): return f'{self.body[:75]}...' def get_absolute_url(self): return reverse('post_detail', args=[str(self.post.id)]) I have my URL routing in urls.py: urlpatterns … -
Django perform actions after oauth callback
I have a project and I want to enable users the option to use their Google/Facebook account in order to sign up/in. Also whenever a new user signs up another model (Account) is created and connected with that user. All of that works fine, but now I have a problem. When users who use the Continue with Google sign up they should be redirected to the view where I will create an Account with the user that was just created (probably not the best way to do it but I can't find any examples for better ones) Now this is where the problem occurs: If the email already exists in Users table then the user is not being transferred to the redirect url where I will perform the checks and if the account with that email exists I will show the warning back on the login/register page but rather they get redirected to allauth's ...accounts/social/signup/ url This is what I have: settings.py LOGIN_REDIRECT_URL = "/account_user/checkouath/" views.py def checkouath(request): user = request.user oauthUser = SocialAccount.objects.get(user=user) # Actions to create new Account and check if User exists are going to be here return redirect(reverse("homepage")) And this is redirect that I have set … -
What is the best way to dynamically add fields to my SearchIndex (django-haystack)?
Currently I see two possibilities, with using locals() and using setattr() after definition of SearchIndex class: 1. class TestIndex(indexes.SearchIndex, indexes.Indexable): for name in fields: locals()["attr_%s" % name] = DescriptionSearchField(boost=3, **{"d_attr": name, "name": "attr"}) locals()["slug_%s" % name] = DescriptionSearchField(**{"d_attr": name, "name": "slug"}) 2. class TestIndex(indexes.SearchIndex, indexes.Indexable): pass for name in fields: setattr(JobTestIndex, "attr_%s" % name, DescriptionSearchField(boost=3, **{"d_attr": name, "name": "attr"})) setattr(JobTestIndex, "slug_%s" % name, DescriptionSearchField(**{"d_attr": name, "name": "slug"})) I am using Django-haystack with ElasticSearch. I know that using locals() is not the best practice. What then is the correct approach to my issue? Any suggestions are greatly appreciated. Thanks. -
Secure file upload in Django - CSV/Excel files
Similar question: File upload security in Django-2.x I'm new to Django in particular, and to web development in general. I'm developing a web application in Django, which lets the user upload files. The files that are supposed to be supported are only Excel and CSV. But I concern about the security of this feature - I wonder if someone can somehow exploit this feature to remotely execute code, or causing another damage to the server running the app? Notice: the path of the uploaded files is at the level of the virtual-environment directory, that is, above the project directory itself (which contains all the Python files, etc). In case you think there are some counter-measures available to protect this kind of feature, I'd be glad to see it. -
Django: return value and not key when serialize a foreign field in DRF
I'd like to ask how I can get the ForeignKey (or ManyToMany) text value to show up in a GET request. Below will produce a JSON with keys referring to either choices or ForeignKey [ { "album_name": "Album_1", "grade": "1", "artist": 2 } ] but I'd like it to display [ { "album_name": "Album_name_NN", "grade": "Bad", "artist": "Artist_name_NN" } ] Those examples I find related to ForeignKey, either on Django Rest Framworks own site or at SO or through various blog posts are not very clear cut and tend to complicate an explanation/solution by also using indirect relationships, as such example is given on the DRF site. At least I cannot implement them into below. I am looking for a minimum viable solution for values to come up in a GET request given below setup. ## Models.py class Artist(models.Model): artist_name = models.CharField(max_length=100) comment = models.CharField(max_length=100) def __str__(self): return (self.artist_name) class Album(models.Model): GRADE = ( ("1", "Bad"), ("2", "Average"), ("3", "Good"), ) album_name = models.CharField(max_length=100) grade = models.CharField(max_length=100, choices=GRADE) artist = models.ForeignKey(Artist, blank=True, on_delete=models.CASCADE) def __str__(self): return (self.album_name) ## views.py class AlbumViewSet(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = AlbumSerializer ## Serializers.py class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = ['album_name', 'grade', … -
django DateField is charfield
I'm using django.forms ModelForm. I have DoB which is 'datefield', however, when I display the form the DoB it is displaying like charfield. What should I do so the user be able to select date? Any help is appreciated. Thank you model: dob = models.DateField(validators=[MinValueValidator(18), MaxValueValidator(70)],blank=True, null = True, verbose_name="Day of birth") HTML: <form method = 'POST' > {{ edit_profile | crispy}} {% csrf_token %} <button type = 'submit' name = 'submit' class = 'btn-edit'>Save</button> </form> -
Celery not taking advantage of all CPUs
We have recently moved a monolith app into a microservice architure. We have 10 different micro services using AWS Beanstalk, Aurora serverless, SQS queues and Elastic Cache Redis. We communicate between services with queues, and we send everything to celery on each microservice, so that all request can be handled multi threading. The main problem that we have is that celery is not taking 100% of the cpu resources, we tried to move from 2cpu to 4cpu and now to 8cpu and each cpu never goes over 20%. I using python and django. The way I create the celery services in AWS beanstalk is as follows: On postdeploy hooks, we create 3 different services with 3 different queues, high priority, default and low priority: Default: #!/usr/bin/env bash # Create the celery systemd service echo "[Unit] Description=Celery service for My App After=network.target [Service] Type=simple Restart=always RestartSec=10 User=root WorkingDirectory=/var/app/current ExecStart=$PYTHONPATH/celery -A saul worker -l INFO -Q default,celery,saul --autoscale 4,2 -n worker@%%h -f /var/log/celery.log EnvironmentFile=/opt/elasticbeanstalk/deployment/env [Install] WantedBy=multi-user.target " | tee /etc/systemd/system/celery.service # Start celery service systemctl start celery.service # Enable celery service to load on system start systemctl enable celery.service High Priority: #!/usr/bin/env bash # Create the celery systemd service echo "[Unit] Description=Celery … -
Can i use Django urls and Vue routes in the same project?
I added VueJS to my Django app using django webpack loader, but now i don't understand how to handle routes in my project. I already built the authentication part of my app using Django templates, but since now i added Vue, does it mean that i have to remake authentication in Vue? Or is it possible to keep the authentication page rendered by a django template and using my urls.py and then, once the user is logged in, the routes are handled by Vue (so it becomes a SPA)? So basically i have: from django.urls import path, include from . import views from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('login/', LoginView.as_view(), name='login'), ... path('', views.index, name='index') ] So after logging in, the other urls should be handled by a Vue router (that i still haven't created). What happens if i do this? If the route is handled by Vue, will the user still be logged and can i still use logout? -
Populate db.sqlite in Django: localhost AND production
A newbie-type of question. I have a new website with a database that holds some objects (let's say cars) plus user session data (device, username). When I was developing it, whenever I needed to add more cars, I would simply add them either with a local script or in localhost/admin. Then I would just copy db.sqlite file to production that was in test phase yet. Now that I will have some users this action would delete their data obviously. And it feels a bad practice anyway. So what is the simplest way to add a number of records programmatically to production? I could run my script directly on the server and add data this way - straight into production. Or could add one by one via www.website.com/admin . But in this case, I will not have those entries in my development environment (I'd like to keep data mirrored so that it is easier and quicker to debug things). I could probably copy db.sqlite file from production back to development, but I guess it is also a wrong way. Any advice or links are highly appreciated. -
When new row inserted to database table, django can detect it
I am working on Django web application project. I am interested, if there is any tool or technique that When new row inserted to database table, django can detect it Use case is: User A inserts some data in Shop Stock table, and all other users knows there is a change in stock. -
Troubleshooting mysql database connections in django python when using multiprocessing
OS: CentOS 8 4.18.0-240.15.1.el8_3.x86_64 Python: 3.8 Django: 3.1.7 Apache: 2.4.37-30 Mariadb: 3:10.3.27-3 I have a website built in django and served via Apache via wsgi. The application makes use of multiprocessing. I wrote a decorator with which I decorate all of my views. Decorator: def counterDecorator(view_func, **kwargs): def wrapper(request, **kwargs): if not request.session.session_key: request.session.save() device_type = 'Unknown' if request.user_agent.is_mobile: device_type = 'Mobile' elif request.user_agent.is_tablet: device_type = 'Tablet' elif request.user_agent.is_pc: device_type = 'Desktop' elif request.user_agent.is_bot: device_type = 'Bot' keywords = {'s_key': request.session.session_key, 'ip_addr': request.META['REMOTE_ADDR'], 'browser': request.user_agent.browser.family, 'browser_version': request.user_agent.browser.version_string, 'operating_system': request.user_agent.os.family, 'operating_system_version': request.user_agent.os.version_string, 'device': request.user_agent.device.family, 'device_type': device_type, 'view_uri': request.path } p = Process(target=count, kwargs=keywords) p.start() return view_func(request, **kwargs) return wrapper Now as you can see this decorator prepares the data and then starts a new process, where a count function is called def count(s_key, ip_addr, browser, browser_version, operating_system, operating_system_version, device, device_type, view_uri): try: conn = create_connection() print(conn) except Exception as e: f = open(BASE_DIR + "/LOG.txt", "a") f.write(e) f.close() if UniqueUserModel.objects.filter(session_key=s_key).exists(): UUM = UniqueUserModel.objects.filter(session_key=s_key).get() UUM.viewsmodel_set.create(user_model=UUM, view=view_uri, view_time_stamp=datetime.datetime.now()) else: UUM = UniqueUserModel() UUM.session_key = s_key UUM.ip_addr = ip_addr if ip_addr != '127.0.0.1': UUM.country = GeoIP2().country(ip_addr).get('country_name') else: UUM.country = 'localhost' UUM.time_stamp = datetime.datetime.now() UUM.browser = browser UUM.browser_version = browser_version UUM.operating_system = operating_system UUM.operating_system_version = … -
How to save Parent django model in related model save
Have two models - Program and Segments. I need to calculate the total times in the program entry from the fields within the associated Segments. I attempted to do that by overriding the save methods, but when entering a new segment it won't update the program model entries unless I go directly into the program form and save/update it. I am missing how to get the segment Update to cause the Program Save/Update to happen. How do I give it the context to call the program save method within the Segment update (After the segment has been saved). Code of the models is: from django.db import models from django.urls import reverse from datetime import datetime, timedelta class Program(models.Model): air_date = models.DateField(default="0000-00-00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default=timedelta) running_time = models.TimeField(default="00:00:00") running_time_delta = models.DurationField(default=timedelta) remaining_time = models.TimeField(default="00:00:00") remaining_time_delta = models.DurationField(default=timedelta) title = models.CharField(max_length=190) locked_flag = models.BooleanField(default=False) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=190,blank=True) mc = models.CharField(null=True,max_length=64) producer = models.CharField(null=True,max_length=64) editor = models.CharField(null=True,max_length=64) remarks = models.TextField(null=True,blank=True) audit_time = models.DateTimeField(null=True) audit_user = models.CharField(null=True,max_length=32) def calculate_time(self): total_run_time_delta = timedelta(minutes=0) for segs in self.segments.all(): total_run_time_delta += segs.length_time_delta self.running_time_delta = total_run_time_delta self.running_time = f"{self.running_time_delta}" hold_time = self.block_time.strftime("%H:%M:%S") t = datetime.strptime(hold_time,"%H:%M:%S") self.block_time_delta … -
multiple independent websockets connections
I have been playing around with django channels + angular. I have created an app that simply sends notifications to front end with a counter 1,2,3,4. It works fine, except if I open the page in multiple tabs. I am also not able to disconnect from the websocket, I can use unsubscribe but it does not really close the connection but that's more kind of a angular question. Anyways how can I make my socket multithread, So if I make multiple requests from the same computer but from different tabs it will work and 2 different instances of the consumer will be created therefore, If I load 2 pages in the same computer the counter should be different independently increasing counter. Do I need redis for that ?