Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access the 'Action' field in django-simple-history?
I'm using django-simple-history to record changes in my models. I cannot find a way to access the "Action" in history model. DATE/TIME USER ACTION invoice.history_date invoice.history_user invoice. ____ ? I have not found a working solution. I have tried : invoice.action, invoice.actions, invoice.history_action/s, etc and they don't work. I want to show what exactly was changed. -
Django authentication function returning None even though user exists
When ever i try to authenticate a user in django it returns None even though user exists. my code: Login function: def login_(request): if request.method == "POST": username = request.POST["name"] password = request.POST["password"] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("index") else: return error.error("102", "username or password is invalid!", request) else: return render(request, "login.html") login.html: {% extends 'template.html' %} {% block body %} <section class="bg-gray-50 dark:bg-gray-900"> <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0"> <div class="w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700"> <div class="p-6 space-y-4 md:space-y-6 sm:p-8"> <h1 class="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white"> Sign in to your account </h1> <form class="space-y-4 md:space-y-6" action="/login" method="post"> {% csrf_token %} <div> <label for="name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your Name</label> <input type="text" name="name" id="name" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="name..." required=""> </div> <div> <label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Password</label> <input type="password" name="password" id="password" placeholder="••••••••" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" required=""> </div> </div> <button type="submit" class="w-full text-white bg-blue-600 mb-2 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium text-sm px-5 … -
add design to django form
i have form in Django but when i try to use it in HTML i tried to do this {{ form.as_p }} also {{ form.as_table }} also {{ form.as_u }} but it's not my design that i want it's just show the form without the design like website ... i want to make like this form and design https://www.m-icc.com/icc-en/Employment.php i tried to use {{ form.as_table }} and {{ form.as_p }} but it don't show this form and design -
having problem to use annotate in django to return nested list
I have a model in django named Courses and it has a ManyToManyField which is related to the teachers Model. now in the views file I'm gonna make an APIView to return a list of courses which each courses has a field that returns teachers names in String which is separated by comma. I wanna use annotate and I used Concat to return each courses and in this Concat I used an ArrayAgg to return a list of teachers name. it raises this error: django.core.exceptions.FieldError: Cannot compute None('Concat(ConcatPair(Value('{"uuid": '), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__pk)), ConcatPair(Value('",'), ConcatPair(Value('"title":'), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__course_title)), ConcatPair(Value('",'), ConcatPair(Value('"courseType":'), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__course_category__category_name)), ConcatPair(Value('",'), ConcatPair(Value('"rate":'), ConcatPair(Cast(F(courses__course_rate)), ConcatPair(Value(','), ConcatPair(Value('"price":'), ConcatPair(Cast(F(courses__course_price)), ConcatPair(Value(','), ConcatPair(Value('"discount":'), ConcatPair(Cast(F(courses__course_discount)), ConcatPair(Value(','), ConcatPair(Value('"isWishedList":'), ConcatPair(Value('"'), ConcatPair(Value('",'), ConcatPair(Value('"imageUri":'), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__course_main_image)), ConcatPair(Value('",'), ConcatPair(Value('"teachers":'), ConcatPair(StringAgg(F(courses__course_teacher__name), Value(', '), distinct=True), ConcatPair(Value(','), ConcatPair(Value('"institution":'), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__course_institution__name)), Value('"}'))))))))))))))))))))))))))))))))))))'): 'Concat(ConcatPair(Value('{"uuid": '), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__pk)), ConcatPair(Value('",'), ConcatPair(Value('"title":'), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__course_title)), ConcatPair(Value('",'), ConcatPair(Value('"courseType":'), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__course_category__category_name)), ConcatPair(Value('",'), ConcatPair(Value('"rate":'), ConcatPair(Cast(F(courses__course_rate)), ConcatPair(Value(','), ConcatPair(Value('"price":'), ConcatPair(Cast(F(courses__course_price)), ConcatPair(Value(','), ConcatPair(Value('"discount":'), ConcatPair(Cast(F(courses__course_discount)), ConcatPair(Value(','), ConcatPair(Value('"isWishedList":'), ConcatPair(Value('"'), ConcatPair(Value('",'), ConcatPair(Value('"imageUri":'), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__course_main_image)), ConcatPair(Value('",'), ConcatPair(Value('"teachers":'), ConcatPair(StringAgg(F(courses__course_teacher__name), Value(', '), distinct=True), ConcatPair(Value(','), ConcatPair(Value('"institution":'), ConcatPair(Value('"'), ConcatPair(Cast(F(courses__course_institution__name)), Value('"}'))))))))))))))))))))))))))))))))))))' is an aggregate I changed th code and replaced ArrayAgg with Subquery, it works good but I want a list of teachers name but it returns a dict like "{"value1", "value2"}" instead. this is my … -
My form isn't visible in the output - Django
views.py def post_pic(request): user = User.objects.get(id=request.user.id) form = PostPicForm() submitted = False form = PostPicForm(request.POST or None, request.FILES or None) if request.method == "POST": if form.is_valid(): form.save() return HttpResponseRedirect('post_pic?submitted=True') #messages.success(request, f'Posted') else: form = PostPicForm() if 'submitted' in request.GET: submitted = True return render(request, 'posts/post_pic.html', {'form': form, 'submitted': submitted, 'user': user}) urls.py from django.urls import path from . import views urlpatterns = [ path('post_pic', views.post_pic, name='post_pic'), ] models.py from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField class Post_Picture(models.Model): post_owner = models.ForeignKey(User, default=None, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField('Title', max_length=120) image = models.ImageField(blank=True, null=True, upload_to="images/") caption = RichTextField(blank=True, null=True) def __str__(self): return self.title forms.py from django import forms from django.forms import ModelForm from .models import Post_Picture class PostPicForm(ModelForm): class Meta: model = Post_Picture fields = ('title', 'image', 'caption') labels = { 'Title': '', 'Caption': '', } widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Title your post'}), 'caption': forms.Textarea(attrs={'class':'form-control', 'placeholder': 'Anything extra you want to add?'}), } post_pics.html {% extends 'main/base.html' %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Rock The Media - Post your Pictures! </title> </head> <body> <style> .div-1 { background-color: #ffffff; } </style> <div … -
Django request.COOKIES empty
Trying to get the request cookies with Django Rest Framework and corsheaders installed. Inside of my view, I have def post(self, request, *args, **kwargs): print(request.COOKIES) print(request.META) I'm using postman with to try and send the Cookie as a header. Not sure if its the CORS middleware that is erasing the Cookie, but even printing out request.META, I can't find any of my request cookies inside. Not sure exactly what is going on here. request.COOKIES returns {} -
Integration of Google, Facebook, and Twitter login functionality with Django Rest Framework encountering issues can you help me to fix this?
what's wrong? I've been trying to log in with Google Facebook, and Twitter for the past three days, but I'm still unable to find a better solution. I've generated a client_id and client_secret from the Google console as well, but it's not working.also, tell me how I test my API I do have not too much idea about google console too. Could you please help me understand what could be going wrong? Here's the code I've been using: settings.py INSTALLED_APPS = [ ...... 'allauth', 'allauth.account', 'allauth.socialaccount', .... ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'APP': { 'client_id': os.getenv('CLIENT_ID'), 'secret': os.getenv('CLIENT_SECRET'), 'key': '', }, 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, 'VERIFIED_EMAIL': False, 'REDIRECT_URI': 'http://localhost:8000/accounts/google/login/callback/', 'USE_SSL': False, } } urls.py path('social/login/google/', GoogleLogin.as_view(), name='google_login'), path('social/login/facebook/', FacebookLogin.as_view(), name='facebook_login'), path('social/login/twitter/', TwitterLogin.as_view(), name='twitter_login'), views.py for login with google API class CustomGoogleOAuth2Adapter(GoogleOAuth2Adapter): def complete_login(self, request, app, token, **kwargs): try: resp = requests.get(self.profile_url, params={'access_token': token.token}) resp.raise_for_status() extra_data = resp.json() provider_id = self.get_provider().id if provider_id in self.provider_map: login = self.get_provider().sociallogin_from_response(request, extra_data) # Get or create user and perform any additional logic user = login.user # Generate access token and refresh token access_token = user.access_token refresh_token = user.refresh_token # Return access token and refresh token in the … -
Can anyone help write the code for settings in Django to load staticfiles?
I am having an hard time rendering static files for my templates which are under hotel folder. Can anyone help write the static code inside settings and assist with static folder structure. enter image description here I have the templates files inside hotel folder and the staticfiles doesn't seem to respond much. I am also trying to use background image inside CSS code which doesn't render mostly. -
How to mock the default value of a property method in Django model during unit testing?
I have below model in Django and it has a property method. class Company(ExtendedModel): name = TruncatingCharField(verbose_name='Company Name', max_length=100, default="NewCo", blank=True) groupId = models.CharField(max_length=20) partner = models.ForeignKey('Partner', related_name='companies', null=True) parentCompany = models.ForeignKey( 'register_company.Company', related_name='linkedCompanies', null=True, blank=True ) @property def isLiveOnPayroll(self): from payroll.models import APCompany apCompany = APCompany.objects.filter(company_id=self.id).last() return bool( apCompany and all( [ self.isReal, self.isActive, self.isPayroll, apCompany.isOnboardedAndActive, ] ) ) In unittest when I read values from this model, I need to set the default value of property method isLiveOnPayroll default to True. In other words I need to mock the value of this method. Please assist how to set it. I tried to mock it using mocker, however could not find the any solution so far. -
Keep current SessionWizardView step when switch to another webpage
I use SessionWizardView (form-tools) to perform the files process function in Django: uploading-parse-validation-save to finalize steps and I created a threading inside the process_step method. So the files processing will still run and return result when I visit another pages inside the application. The issue is when I click the link back to the file process page, the processed result is showing current step information but the form and steps jumped to the first step, I know it might be the init reset the current view, so I used cache to store steps and get like this: Class myclassview(SessionWizardView): #...other settings def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filelist=[] self.orgbatch_id=None self.valLog=None if cache.get('vitek_process_step')==None: cache.set('vitek_process_step', 'upload_file') def process_step(self, form): cache.set('vitek_process_step', self.steps.next) step=cache.get('vitek_process_step') print(f"next step: {step}") current_step = self.steps.current #... print(current_step) if current_step == 'upload_file': #... if form.is_valid(): # some processing in threading else: return render(request, 'ddrug/importhandler_vitek.html', context) elif current_step == 'step1': # recheck and save to DB # same some processing.... return self.get_form_step_data(form) def done(self, form_list, **kwargs): cache.delete(self.request.session.session_key) cache.delete('vitek_process_step') return redirect(self.request.META['HTTP_REFERER']) def get_context_data(self, form, **kwargs): #set some context... return context def get(self, request, *args, **kwargs): # Check if a step was saved in the cache current_step =cache.get('vitek_process_step') print(f"current_step {current_step}") if current_step is … -
Web page won't show up when I run a Dockerized Django project
I'm trying to Dockerize a Django project but the webpage won't show up when I run the container. However, I don't get any errors in the terminal when I run "docker compose up --build" and I've confirmed on Docker Desktop that my container is present and running. The error I get is ERR_ADDRESS_INVALID which says the site can't be reached. Here is what my Dockerfile looks like: FROM python:3 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y libpq-dev WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I tried adding the "0.0.0.0:8000" to CMD but that didn't work either. Here's my docker-compose.yml file: version: "3" services: web: build: context: . dockerfile: Dockerfile ports: - "8000:8000" And lastly here is my requirements.txt file: asgiref==3.6.0 Django==4.2.1 djangorestframework==3.14.0 psycopg2==2.9.6 pytz==2023.3 sqlparse==0.4.4 tzdata==2023.3 After looking up the problem online and on YouTube, I'm not sure what the problem is because it seems like I have everything I need. -
Confused with django urls
i was trying to define routes in django app, but it keeps showing me error like this:- Using the URLconf defined in gptclone.urls, Django tried these URL patterns, in this order: chat [name='home'] about [name='about'] api [name='chatAPI'] The empty path didn’t match any of these although i have already defined routes in my app urls.py like this : from django.contrib import admin from django.urls import path from home.views import home, about, chatAPI urlpatterns = [ path('chat',home,name='home'), path('about', about, name = 'about'), path('api', chatAPI, name ='chatAPI'), ] and in my projects urls.py I already have: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('home.urls')) ] can you please tell me what am i doing wrong here ?? -
Django Channels : WebSocket connection failed
WebSocket connection to 'ws://127.0.0.1:8000/room/ws/tech' failed I am trying to learn about creating a real time Django application using channels and following this tutorial. However, when I am trying to create a websocket, it is throwing me this error in console : WebSocket connection to 'ws://127.0.0.1:8000/ws/tech/' failed This is how I am trying to create a websocket - console.log("roomname: "+roomName); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); Rest assurred that url is getting built correctly. When I replace the url part with 'ws://127.0.0.1:8000/room/ws/tech' and run manually in a browser console, it is throwing me the same error. -
Djongo isn't using my explicitly set primary key in Django models
Djongo using "id" as primary_key even though it is already explicitly set in model below is my model, where ive explicitly set a primary key for each model. class searchPlayers(models.Model): name = models.CharField(max_length=200,default='') playerId = models.CharField(max_length=200,primary_key=True) LP = models.IntegerField(default=0) add_date = models.DateTimeField('date') class Matches(models.Model): matchID = models.CharField(max_length=200,primary_key=True) otherParticipants = models.CharField(max_length=200, default='') placement = models.IntegerField(default=0) game_time = models.CharField(max_length=20, default='') game_length = models.CharField(max_length=20, default='') searchedPlayer= models.ForeignKey(searchPlayers, on_delete=models.CASCADE,default=None) class Traits(models.Model): matchID = models.CharField(max_length=200,primary_key=True) traitname = models.CharField(max_length=100, default='') currenttier = models.IntegerField(default=0) tierunits = models.IntegerField(default=0) associatedMatch = models.ForeignKey(Matches,on_delete=models.CASCADE,default=None) class Champions(models.Model): matchID = models.CharField(max_length=200,primary_key=True) Name = models.CharField(max_length=20, default='') Star = models.IntegerField(default=1) Items = models.CharField(max_length=100, default='') #will have to delineate with commas Rarity = models.IntegerField(default=0) associatedMatch = models.ForeignKey(Matches,on_delete=models.CASCADE,default=None) and yet when i view on Mongo compass: Mongocompass the primary key is still the "id" field. ive tried deleting all my migrations, django.migrations and completely dumped my entire model. Any ideas for why the primary key isnt being properly set? -
gremlinpython submit async query returns ClientConnectorCertificateError in Django
I have a module that manages Azure Cosmosdb Gremlin queries. When I call it from jupyter notebooks like this, it works fine. However, when calling it from the Django app I get a ConnectionError: Cannot connect to host graph-exodestiny.gremlin.cosmos.azure.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)')] I think this is simply a library version issue, but I can't figure out the reason. Both are importing the same cmdb_graph.py connector module here. Both are running on the same local environment. I also have the same application running here on an Azure Web App and it's working fine. From this environment. The closest related issue is this one, however I'm unable to draw a connection. They seem to be totally different connector types. -
Django LocaleMiddleware redirect not working
what is the reason for not redirecting to site.ai/en/ or site.ru/ru/ when I make a request to site.ai? when requesting site.ai I get a 500 error. When I turn on the debug in django, everything works out. Where can I look for the reason? MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.security.SecurityMiddleware", "django.middleware.locale.LocaleMiddleware", "wagtail.contrib.redirects.middleware.RedirectMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", ] nginx upstream botto_django { server web:8000; } server { listen 80; server_name servername; location / { proxy_set_header Accept-Language $http_accept_language; return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name sitename; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; ssl_certificate /etc/letsencrypt/live/botto.ai/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/botto.ai/privkey.pem; location / { proxy_pass http://botto_django; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto https; proxy_set_header Accept-Language $http_accept_language; } location /media/ { alias /usr/src/app/media/; } location /static/ { alias /usr/src/app/static/; expires 30d; } client_max_body_size 64M; gzip on; gzip_disable "msie6"; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript; } -
CSRF token still giving error after having middleware, html tag and csrf_protect
I'm trying to get the view to redirect the user to the index page if they type in a page that does not exist. After rendering the 404 error and pressing on the button, the 403 CSRF verification failed. Request aborted. comes up. I've checked and the middleware was installed in settings.py, I routed the urls correctly(probably), added {% csrf_token %} in the html and also added @csrf_protect for the view. 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', ] def title(request, title): entry = util.get_entry(title) if entry == None: code = '404' message = 'Page not found' return render(request,'encyclopedia/error.html',{ 'message': message, 'code': code }) elif entry != None: return HttpResponse(title) @csrf_protect def redirect_to_page(request): if request.method == 'POST': return redirect('/') return render(request, 'error/') {% extends "encyclopedia/layout.html" %} {% block title %} Errors {% endblock %} {% block body %} <h1>{{ code }} {{ message }}</h1> <form action="{% url 'redirect' %}" method="POST"> {% csrf_token %} <button type="submit">Redirect</button> </form> {% endblock %} Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - https://acpanda1408-code50-103527608-pjqw44gw727jvj-8000.preview.app.github.dev does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or … -
How to write Django query expression to convert unix time to datetime?
I am writing a function to generate a report from a Django database. My production database is PostgreSQL but my test database is SQLite, so I need to support both. I need to compare two times, but one is stored in the database as a unix time stamp, and the other is a datetime object. I do not have the freedom to update these models to make this calculation simpler. Initially I did this calculation in Python but there are a large number of messages and it takes too long, so I set about doing the operations server side. I have written a custom Django Query expression. I found an online example for PostgreSQL, which works. I can't find the equivalent for SQLite, and I don't have any experience in SQL so I'm finding it tricky to understand what to do from the SQL documentation. message_delivery__sent is a datetime, base_time_received_s is a float. What I have so far is this: from datetime import timedelta from django.db import models from django.db.models import F, Func from .models import Message class UnixToDatetime(Func): template = None output_field = models.DateTimeField() def as_sqlite(self, compiler, connection, **extra_context): self.template = "???" return super().as_sql(compiler, connection, **extra_context) def as_postgresql(self, compiler, … -
Django DRF and React Native
I have a React Native app that uses data it takes from a Django DRF backend. My client asked that there be no user on the app so I don't know how to restrict API access since there is zero user management nor password. I'd like to restrict at the very minimum the API access to people who are using the mobile app but is there a way in DRF to do that? Would it require the mobile app itself to have some sort of constantly changing token? Many thanks for your help -
Django get id of the selected checkbox on CheckboxSelectMultiple widget in Javascript
I have checkboxes in Django from a form : testrever = forms.MultipleChoiceField(required=False,widget=forms.widgets.CheckboxSelectMultiple()) I would like to return only the ID (and then the value) of the last selected checkbox on .change event only when it's checked (when it's unchecked I don't want anything to happen). I managed to do so with the following (thanks to this answer) : Django How to get value of CheckboxSelectMultiple in Javascript in Template $('#id_testrever_0').on("change", function() { var testrever =[] if ($('#id_testrever_0').is(':checked')) { testrever = $('#id_testrever_0').val(); console.log(testrever) } }) $('#id_testrever_1').on("change", function() { var testrever =[] if ($('#id_testrever_1').is(':checked')) { testrever = $('#id_testrever_1').val(); console.log(testrever) } }) }); But I would like to achieve it in a more elegant way to minimise the code lenght and avoid the repetitions. maybe by using $("input:checkbox[name=testrever]").on("change", function() $("input:checkbox[name=testrever]:checked").each(function() if it's possible. -
Microservices architecture with Django
I have some questions about creating microservices with Django. Let's say we have an online shop or a larger system with many database requests and users. I want to practice and simulate a simple microservice to learn something new. We want to create a microservices-based system with the following components: A Django-based microservice with its admin panel and full functionality (excluding DRF). One or more microservices with a React/Angular frontend. Several additional microservices to separate functionalities. I'm unsure about the architecture. Let's assume we want to manage data using the Django admin panel. The simplest solution would be to add DRF to the first microservice and extend its functionality (REST app) - instead of creating different services (3.). But what if we want to separate functionality into different microservices? Should the microservices in point 3 be connected to the same database and treated as different Django projects (with DRF)? Can we use GoLang, FastAPI, or Java Spring for the third microservice? If yes, should all models be duplicated and registered in the first microservice? Alternatively, is there a better way to approach this? It would be great to hear your perspective and methods on how to proceed with this. Have … -
django crontab schedule not being executed
Trying to run django crontab in docker-compose when running the command manually using python manage.py crontab run some-hash, it works otherwite it's never executed, here's my compose version: '3.8' services: django: build: . container_name: django command: bash -c "service cron start && python manage.py crontab add && crontab -l && gunicorn -w 2 -b 0.0.0.0:8000 project.wsgi:application" restart: always env_file: - .env ports: - "8000:8000" volumes: - .:/code it shows the command being added but it's never executed settings.py: CRONJOBS = [ ('* * * * *', 'django.core.management.call_command', ['dumpdata_daily'], {}) ] CRONTAB_COMMAND_SUFFIX = '2>&1' also added django_crontab to installed_apps and cron is installed in Dockerfile using apt-get what am I doing wrong? -
How do I make an upsert using the drf serializer?
I am trying to find a clean way using DRF serializers strictly in order to perform an upsert, aka inserting when the object with an indexed column does not exist or updating if it does exist (on duplicate equivalent of sql). I have found other ways using django objects but it seems there is no clear way to do that using a serializer. -
Delete Django queryset in a concurrency-safe way
I want to delete a row with a zero quantity in a way that is concurrency-safe. It is conceivable that the row could become non-zero just before it is deleted. The models looks something like this: class Stock(models.Model): product = models.ForeignKey(Product) location = models.ForeignKey(Location) quantity = models.IntegerField() To delete it, I am using: Stock.objects.filter(product=product, quantity=0).delete() I want the SQL to be: DELETE FROM app_stock WHERE product=product AND quantity=0 But it is being optimized to: DELETE FROM "app_stock" WHERE "app_stock"."id" IN (5) This optimization is quite reasonable in a sense as the ID of the object to be deleted is 5 and this is more efficient. Unfortunately it is not going to be safe as the stock could be increased by another process at anytime. I can fix this with raw SQL. I have also tried trying other queries but it is always optimized the same way. -
Simulating __subclasses__() behavior in one-to-many relationship in Django
I have situation similar to this, in which I have different levels in the hierarchy and every child in the hierarchy is in one-to-many relationship with its parent. # class from parent level. class Fookth: pass # classes from the child level. class Bar1: foo = models.ForeignKey(Fookth, on_delete=models.CASCADE) class Bar2: foo = models.ForeignKey(Fookth, on_delete=models.CASCADE) . . . class Barn: foo = models.ForeignKey(Fookth, on_delete=models.CASCADE) Now, my requirement is to find all the Bar-ith model which have Foo-kth as ForeignKey. Note, that if I have something like this, class Barith(Fookth) I could have used Fookth.__subclasses__() but that is not the case here. I wanted to ask is there a way to achieve this behavior? I have read through the docs but it only suggests to use related_name to use it in reverse query, but if I have lot of models it'll become tedious to keep track of each of them individually, I want something similar to __subclasses__().