Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding {% csrf_token %} to javascript insertion
All, I have a popup that is inserted via javascript when a button is clicked: function loadTypeManagement(existingDocTypes) { const typeManagementModalDiv = '<div class="modal fade" id="typeManagementModalDiv" >' + '<div class="modal-dialog" style="max-width: none;">' + '<div class="modal-content feedback_popup" style="height:100%; margin-top: 0vh;">' + '<form class="feedback_form" autocomplete="off" action="/" method="post" id="taskitem_form">' + '<h1 id="djangoInsert">Type Management</h1><br>' + '<hr>' + '<div class="autocomplete container justify-content-center">' + '<h3 style="margin-bottom: .5vw;">Add a Document Type</h3>' + '<hr style="width: 50% ;margin: auto; margin-bottom: .5vh;">' + '<div class="row">' + '<div class="col-3"></div>' + '<label class="col-6 admin_input_desc ">Document Type:</label>' + '<div class="col-3"></div>' + '</div>' + '<div class="row">' + '<div class="col-3"></div>' + '<input class=" text-center col-6 admin_input " id="addDoctypeId" type="text" name="addDocTypeName" placeholder="Document Type">' + '<div class="col-3"></div>' + '<div class="d-inline p-2 text-white ">' + '<p class="col-sm-4 admin_input_desc d-inline">Can this new type be an Authentication Source?</p>' + '<label class="">No</label>' + ' <input type="radio" id="date_newToOld" name="choice" value="date_newToOld" checked/>' + '<label class="float-right " style="margin-left: 1.25vw;">Yes</label>' + ' <input class="float-left" type="radio" id="date_newToOld" name="choice" value="date_newToOld" />' + '</div>' + '</div>' + '<input class="submit_button" name="submit" type="submit" value="Add Document Type">' + '</div>' + '</form>' + '<form class="feedback_form" autocomplete="on" action="/action_page.php">' + '<hr>' + '<div class="autocomplete container justify-content-center">' + '<h3 style="margin-bottom: .5vw;">Remove a Document Type</h3>' + '<hr style="width: 50% ;margin: auto; margin-bottom: .5vh;">' + '<div class="row">' + … -
Django-autocomplete-light - "No results found" in browser on startup - after doing one search in admin - results are found in browser again
I have a peculiar problem with Django-autocomplete-light. When I go to my browser and try searching for something I get "no results found" - but when I go to the admin panel and add a model, the results pop up as they should. When I have done this one time, I can go back to the browser and then the results show up as they should. I'm suspecting some caching issue, but not sure how to debug this. Maybe someone can take a look if there is something wrong with my set-up. models.py class DogBreeds(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Advertisement(SoftDeleteModel, TimeStampedModel): breed = models.ForeignKey(DogBreeds, on_delete=models.CASCADE, null=True, verbose_name='Hundras') views.py class BreedAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return DogBreeds.objects.none() qs = DogBreeds.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) return qs Form template {% extends '_base.html' %} {% load static %} {% block content %} <form method="post" enctype="multipart/form-data" id="adForm" data-municipalities-url="{% url 'ajax_load_municipalities' %}" data-areas-url="{% url 'ajax_load_areas' %}" novalidate> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Publish</button> </form> </body> {% endblock content %} {% block footer %} {% comment %} Imports for managing Django Autocomplete Light in form {% endcomment %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> <link rel="stylesheet" … -
Django rest_framework MVC structure
I'm currently working on a Django project, using the rest_framework. The project is built around API endpoints the client-side will use to send/retrieve data about features such as users, players, playerInventory etc etc. My question is, I'm struggling to structure this project and I'm not sure if i should be destructuring the data my front-side receives. The data I'm working with looks like API ENDPOINT Returns a single player inventory [GET] { "elementId": 1, "elements": [1, 2, 3 ,4] } API ENDPOINT Update a single player inventory [POST] from -> { "elementId": 1, "elements": [1, 2, 3 ,4] } (example) to -> { "elementId": 1, "elements": [3, 3, 3 ,1] } I'd like to be able to use a front-end 'model' concenpt that takes the data from my API fetches and constructs them for me so i can use that data in a better manor. Could someone give me a detailed Django project file structure and some Javascript model code design patterns possible? here's my models.py: class User(models.Model): userId = models.AutoField(primary_key=True) username = models.CharField(max_length=16) email = models.EmailField(max_length=30) isMember = models.BooleanField(default=False) class meta: db_table = 'app_users' app_label = "app" managed = True def __str__(self): return str(self.userId) class Player(models.Model): playerId = models.ForeignKey(User, … -
Django Admin upload image with foreign key
I have a model Product with a User and ProductImages as foreign key. models.py class User(AbstractBaseUser): ... class ProductImages(models.Model): image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to='images/', null=True, blank=True, default='magickhat-profile.jpg' ) class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) productimages = models.ForeignKey(ProductImages, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_description = models.CharField(max_length=255, default='product_description') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) product_view = models.IntegerField(default=0) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'pk': self.pk}) forms.py class ProductForm(ModelForm): productimages = forms.ImageField() CHOICES_STATUS = (('Pronto', 'Pronto'),('Em obras', 'Em obras'),('Lançamento', 'Lançamento'),) product_status = forms.ChoiceField(choices=CHOICES_STATUS) product_title = forms.CharField() product_description = forms.CharField() class Meta: model = Product fields = '__all__' admin.py class AdminProductModel(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(user_id=request.user) kadmin.register(User, UserAdmin) kadmin.register(Product, AdminProductModel) But in the admin Product model the field for image is redering as select field no ImageField My purpose is add a upload image field on django model administration. If i use ImageField direct on Product model the field is redering ok, but i need a external table to store that image becouse is a multimage upload, so i need a foreing key. How is the right way to that purpose. I see other questions about that, but the majority is old versions, and … -
How do I set up a nested URL pattern for /category/subcategory/post in Django?
I've looked through several answers and I cannot seem to figure out how to do this. My best guess is this has something to do with all of these answers are specific to writing function based views. The problem: I have a portal where I want the URL structure to be: /portal/engagement/engagement_name/finding/finding_name So I've tried several things and this is the closest I can get: urlpatterns = [ path('', login_required(CustomerDashboard.as_view()), name='portal_dashboard'), path('engagement/add', login_required(EngagementCreateView.as_view()), name='engagement_create'), path('engagement/<slug:slug>/', login_required(EngagementDetailView.as_view()), name='engagement_detail'), path('engagement/<slug:slug>/edit', login_required(EngagementUpdateView.as_view()), name='engagement_update'), path('engagement/<slug:slug>/finding/add', login_required(FindingCreateView.as_view()), name='finding_create'), path('finding/<slug:slug>', login_required(FindingDetailView.as_view()), name='finding_detail'), path('finding/<slug:slug>/edit', login_required(FindingUpdateView.as_view()), name='finding_update'), ] If I try to do something like engagement/<slug:slug>/finding/<slug:slug>/ it just errors. I've tried to follow some answers like choosing the slug field (i.e. slug:engagement_slug``` but none of it works. I'm using class based views. My models are: Company Engagement (FK to Company) Finding (FK to Engagement) I'm not sure what other code I can provide to help. I've read some other options on overriding the get_object method and passing the slug as a **kwarg. I'm just not sure what is the "right" way to do this. -
Django Update AbstractUser
IntegrityError at / NOT NULL constraint failed: pages_profile.username Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.9 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: pages_profile.username How do I update an abstractuser that's already signed in? from django.shortcuts import redirect, render from .forms import UserProfileForm from .models import Profile def index(request): context = {} if request.method == "POST": print(request.POST) form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): img = form.cleaned_data.get("avatar") obj, created = Profile.objects.update_or_create( username=form.cleaned_data.get('username'), defaults={'avatar': img}, ) obj.save() print(obj) return redirect(request, "home.html", obj) else: form = UserProfileForm() context['form']= form return render(request, "home.html", context) -
Django - Given time zone, month and year get all post created on that date in that time zone
So I have this Post model. I want to be able to retrieve all posts that were created in a month, year under a certain time zone. model.py class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN) So for example if a user creates 10 posts in November, 2 in December of 2021 in PST. Then I have a view that takes month, year and time_zone and let's say the url looks something like /post/<int:month>/<int:year>/<str:time_zone> and the user pings /post/11/2021/PST then it should return the 10 posts from November. How do I return all posts from a month and year in a time zone given time zone, month and year? Setup: Django 3.2.9 Postgresql -
Django pluralize person as people
trying to output the correct plural value in Django template when count is more than 1. <p>{{ review.markers.helpful.count }} person{{ reviews.markers.helpful.count|length|pluralize }} found this helpful</p> still returns 1 persons or 2 persons instead of 1 person and 2 people any help to fix this in the template? -
Django server does not start with docker-compose up
I dockerize my django backend app. I am using posgresql as db. After doing docker-compose up the last logs are: db_1 | 2021-12-21 18:39:58.213 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-12-21 18:39:58.213 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2021-12-21 18:39:58.310 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2021-12-21 18:39:58.476 UTC [42] LOG: database system was shut down at 2021-12-21 18:39:58 UTC db_1 | 2021-12-21 18:39:58.678 UTC [1] LOG: database system is ready to accept connections I am not getting any other logs after them,I don't know what the issue is maybe its due to postgresql. But django server is not starting. I did docker ps I got following results CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d92379ca89b7 prodlerbackend_prodler "python manage.py ru…" 20 minutes ago Up 20 minutes 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp prodlerbackend_prodler_1 3364c1cda344 postgres:11.2-alpine "docker-entrypoint.s…" 20 minutes ago Up 20 minutes 0.0.0.0:5432->5432/tcp, :::5432->5432/tcp prodlerbackend_db_1 I think the containers are up, still Django server is not started what can be the issue? docker-compose.yml version: "3.9" services: db: image: postgres:11.2-alpine volumes: - ./postgres-data:/var/lib/postgresql/data environment: - HOST=localhost - POSTGRES_DB=prodler - POSTGRES_USER=postgres - POSTGRES_PASSWORD=admin123 ports: - 5432:5432 prodler: build: context: … -
Error 415 on angular although the headers are up
I'm getting error 415 on angular api request but http header are set: login.service.ts: var httpHeaders = new HttpHeaders(); httpHeaders.set('Content-Type', 'application/json'); httpHeaders.set('Access-Control-Allow-Origin', '*'); return this.httpClient.post<any>(requestUrl, params, { headers: httpHeaders }) As backend i used django rest framework Any idea ? Thans in advance. -
Multiple concurrent requests in Django async views
From version 3.1 Django supports async views. I have a Django app running on uvicorn. I'm trying to write an async view, which can handle multiple requests to itself concurrently, but have no success. Common examples, I've seen, include making multiple slow I/O operations from inside the view: async def slow_io(n, result): await asyncio.sleep(n) return result async def my_view(request, *args, **kwargs): task_1 = asyncio.create_task(slow_io(3, 'Hello')) task_2 = asyncio.create_task(slow_io(5, 'World')) result = await task_1 + await task_2 return HttpResponse(result) This will yield us "HelloWorld" after 5 seconds instead of 8 because requests are run concurently. What I want - is to handle multiple requests to my_view concurrently. async def slow_io(n, result): await asyncio.sleep(n) return result async def my_view(request, *args, **kwargs): result = await slow_io(5, 'result') return HttpResponse(result) I expect this code to handle 2 simultaneous requests in 5 seconds, but it happens in 10. What am I missing? Is it possible in Django? -
Django background task like FastAPI
I have a requirement that I need to calculate hash of some images in background after the data inserted on DB tables. I saw FastAPI Vs Django implementation of background task and it seems very easy and feasible solution for background task implementation in FastAPI comparing to Django. So I need to know is there similar kind of implementation on Django available or not? because it's seems too much on Django for a simple background task. OR It would be better to use simple multiprocessing.Process For Django: I need to do these steps for achieve background task Installation I like [pipenv][1] so: > cd [my-django-project root directory] > pipenv install django-background-tasks Now add 'background_task' to INSTALLED_APPS in settings.py: INSTALLED_APPS = ( # ... 'background_task', # ... ) and perform database migrations to ensure the django-background-tasks schema is in place: > pipenv shell (my-django-project) bash-3.2$ python manage.py migrate Creating and registering a Task Any Python function can be a task, we simply need to apply the @background annotation to register it as such: from background_task import background @background(schedule=10) def do_something(s1: str, s1: str) -> None: """ Does something that takes a long time :param p1: first parameter :param p2: second parameter … -
How to run only the tests that are affected by the latest changes in a Django project?
We are running Django tests on a bitbucket pipeline and it takes a bit long. What I want to do is, get the diff between the current branch and the main branch and run the tests that are affected by this diff. How can I do that? -
what is the correct way to filter data from db in monthly and yearly basis for analytics?
I am making an analytics section for my client, where I need to display data in graphical form. For this I am using chart js. Now I have a model to store visitors of the website. Now I want to filter the data in monthly and yearly basis to put it in chart js and display it graphically. Now what I am doing is this monthly_visitor = VisitorCount.objects.all().filter(date_of_record__month = today.month).count() yearly_visitor = VisitorCount.objects.all().filter(date_of_record__year = today.year).count() Here, I am able to get the count for my current month and year. But making variables for each month and year is not the right to do it. So please suggest me what is the correct procedure to filter the data so that I can make the analytics. I have never before done this, so I do no the correct approach, please suggest me. Also the chart js code looks like this, which also perhaps no the correct way to do make the analytics const vismonth = document.getElementById('visitorMonthly').getContext('2d'); const visitorMonthly = new Chart(vismonth, { type: 'bar', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'Visitors Monthly', data: [12, 19, 3, 5, 2, 3], backgroundColor: … -
How to update page in django without page refresh?
So.I have prices in database django,when I change it,prices on website dont change and I have to restart django server.So..How Can I refresh page in django without restart django server? -
django.db.utils.ConnectionDoesNotExist: The connection prueba doesn't exist
I want migrate Django database to MongoDB with Djongo but i have this error. Traceback (most recent call last): File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 167, in ensure_defaults conn = self.databases[alias] KeyError: 'prueba' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 74, in handle connection = connections[db] File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 199, in __getitem__ self.ensure_defaults(alias) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 169, in ensure_defaults raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias) django.db.utils.ConnectionDoesNotExist: The connection prueba doesn't exist My settings.py looks like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'decide', 'PASSWORD': 'decide', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'prueba': { 'ENGINE': 'djongo', 'NAME': 'egc-sierrezuela-2', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'HOST': 'mongodb+srv://usuario:password@egc-sierrezuela-2.fxrpl.mongodb.net/egc-sierrezuela-2?retryWrites=true&w=majority' } } } I am using Django=2.0 and djongo=1.2.38 I have tried with many djongo versions and but the errors still arises. Also, upgrading django to the latest version is not possible as I'm using an old project. Any idea? -
Django's static() function to retrieve static file gives no such file -error
I'm doing a project with Django with the following structure: /project /cv /static /configuration configuration.json So a project with one app in it and a config.json file in the static folder. My settings.py (the most important settings for this): INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "cv", ] STATIC_URL = "/static/" BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, "cv/static") In my view I use the static() function to retrieve the static file def index(request): file_path = static("configuration/configuration.json") with open(file_path) as f: configuration = json.loads(f.read()) return render(request, "index.html", configuration) But when It keeps giving me the error: No such file or directory: '/static/configuration/configuration.json' I can fix it by explicitly parsing the path string to the index function: "./cv/static/configuration/configuration.json" But how do I do it with the static() function? The static() function uses the static_url variable, but no matter how I adjust it, it keeps giving me a similar error. Anyone an idea what I'm doing wrong here? -
Integration Pycharm, Docker Compose and Django Debbuger getting error: /usr/local/bin/python: can't find '__main__' module. in ''
I'm having a problem using Pycharm to run a Docker container to debug a Django project on MacOs. The Pycharm setup is working fine to run the Django project inside a Docker container. But when I try to do a debugger I'm having the following issue: /usr/local/bin/docker-compose -f /Users/claudius/Studies/Pycharm/test-api/docker-compose.yaml -f /Users/claudius/Library/Caches/JetBrains/PyCharm2021.2/tmp/docker-compose.override.1494.yml up --exit-code-from web --abort-on-container-exit web Docker Compose is now in the Docker CLI, try `docker compose up` mongo is up-to-date postgres is up-to-date Recreating test-api_web_1 ... Attaching to test-api_web_1 Connected to pydev debugger (build 212.4746.96) web_1 | /usr/local/bin/python: can't find '__main__' module in '' test-api_web_1 exited with code 1 Aborting on container exit... ERROR: 1 Process finished with exit code 1 To set up the Pycharm I did: Add a Python interpreter with docker-compose and the container of the web application (Django). Add a Django config for the project. Add a Run/Debugger config. Does someone have any suggestions? -
Django: How do I access a related object max value in html template
I am attempting to display a list of items for auction. For each item, I am wanting to also display the current bid price. The current bid price should be the max value or last added to the Bids class for each individual listing. How do I render in my HTML the max Bid.bid_price for each item in my Listing.objects.all() collection? Below are my models, views, and HTML. Models: class Listing(models.Model): title = models.CharField(max_length=65, default="") description = models.CharField(max_length=200, default="") category = models.CharField(max_length=65, default="") image = models.ImageField(blank=True, null=True, upload_to='images/') listed_by = models.ForeignKey(User, on_delete=models.CASCADE, default="") created_dt_tm = models.DateTimeField(auto_now_add=False, default=timezone.now()) class Bids(models.Model): bidder = models.ForeignKey(User, on_delete=models.CASCADE, default="") listing = models.ForeignKey(Listing, on_delete=models.CASCADE, default="", related_name="bids") bid_price = models.IntegerField(default=0) created_dt_tm = models.DateTimeField(auto_now_add=False, default=timezone.now()) Views: def index(request): return render(request, "auctions/index.html", { "listings": Listing.objects.all() }) HTML: {% for listing in listings %} <div style=display:flex;margin:30px;border:lightseagreen;border-style:solid;height:150px;border-width:1px;width:40%> <div style=width:25%;display:flex;> {% if listing.image %} <img src="{{listing.image.url}}" alt="Cannot display image" height="100px" style="margin-left:50px;"> {% endif %} </div> <div style=width:15%></div> <div style=width:30%> <div><a href="{% url 'listing' listing.title %}">{{listing.title}}</a></div> <div style=font-size:10pt;>Description: {{listing.description}}</div> <div style=font-size:10pt;>Category: {{listing.category}}</div> **<div style=font-size:10pt;>Current Price: ${{ listing.bids_object.bid_price }}</div>** <div style=font-size:10pt;>Created by:<br>{{listing.listed_by}}</div> </div> <div style=width:30%> <div style=margin:10px;> </div> </div> </div> {% endfor %} {% endblock %} -
Django How to insert into model with dynamic key value pairs?
I am obtaining Model instance from my applabel and modelname by the below mentioned format. target_model = django.apps.apps.get_model(app_label=appname, model_name=modelname) And Obtaining model instance like this model = target_model() Need to insert the row in db using this model. I am having key value pairs in variable I have tried below mentioning two ways. key = "model_id" value = "some_value" model[key] = value model.save() and setattr(model, key, value) model.save() Both are not working for me. Any Django (python) Engineers helps me to move further? -
first and last methods used excluded items
i used last() to get last item of queryset after exclude some items as below: holidays = HolidayModel.objects.all().values_list('date', flat=True) result = BorseExchangeLog.objects.exclude( hint_time__date__in=holidays ) # output 1 print(list(result.valuse_list('hint_time__date',flat=True).distinct('hint_time__date'))) #output2 print(result.last().hint_time.date()) but in output2 print item that not exists in output1 i test that by first() and problem was there too what is problem? my code is wrong or bug from django orm? using django2.2 and postgresql -
Django ORM query to update reverse many to many field
Models look like: class Book(models.Model): name = models.TextField(verbose_name='Book Name') class Author(models.Model): name = models.TextField(verbose_name='Author Name') Books = models.ManyToManyField(Book) Book can have many authors and Author can have written many books Now, There is a list like: [ {Book_id1:[Author_id1, Author_id2]}, {Book_id2:[Author_id2, Author_id3]}, ] This information is required to be updated in the DB. How can this be done in an efficient way using ORM? (Currently the DB may have Book_id1 linked with [Author_id1,Author_id3] so the update should be able to add author_id2 and delete author_id3 as well) -
Is there a way to convert HTML div to a video format (MP4 or any other) in Python/Django?
I am trying to render a HTML page and use a specific inside it to convert it to video format. Explanation: I know HTML is static content but it is necessary for me to convert it to a video format (it is a requirement). I need to know if there is a way which can render a page and export it to a video format. It can either be a direct HTML to MP4 conversion or capture rendered div (Not record canvas) as an Image and then convert that image to the video format. Technology Stack: Django Django templates HTML JAVASCRIPT Any help would be appreciated. -
Django and reactjs: How to create notification feature
I have django backend and reactjs frontend. I am running some tasks in celery on the backend. Now when the tasks are completed, I want to inform the user in real time, when the webapplication is open I have done the frontend in reactjs. I heard this can be done using polling or webhooks. I want to use webhooks. How to do this. What should i do on the backend side and also on the frontend side -
django: simulate a flags Field using BInaryField
So I'm trying to simulate a flags field in Django (4.0 and Python3) the same way I could do in C or C++. It would look like this: typedef enum{ flagA = 0, flagB, flagC } myFlags; Having a uint8 that by default is 00000000 and then depending on if the flags are on or off I'd do some bitwise operations to turn the three least significant bits to 1 or 0. Now, I could do that in my model by simply declaring a PositiveSmallIntegerField or BinaryField and just creating some helper functions to manage all this logic. Note that I DO NOT NEED to be able to query by this field. I just want to be able to store it in the DB and very occasionally modify it. Since it's possible to extend the Fields, I was wondering if it would be cleaner to encapsulate all this logic inside a custom Field inheriting from BinaryField. But I'm not really sure how can I manipulate the Field value from my custom class. class CustomBinaryField(models.BinaryField): description = "whatever" def __init__(self, *args, **kwargs): kwargs['max_length'] = 1 super().__init__(*args, **kwargs) For instance, if I wanted to create a method inside CustomBinaryField, like the following, …