Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you write a Django ManyToMany Custom Cascade Delete?
I am using Django 3.1 with PostgreSQL. Here is an example setup: **Tables:** Batch (id, name) Data (id, Batch, Stuff(ManyToMany)) Stuff (id, name) Consider this scenario: If I add one record in Batch with the id of 1 and then I add 10,000 records in Data that is linking to Batch#1 and each item might reference some items in the Stuff table. Issue: If I delete Batch#1 it ends up creating a query like this for deleting the ManyToMany Relationships: DELETE FROM "data_stuff" WHERE "data_stuff"."data_id" IN (1, 2, 3 ... 9999, 10000) That is a lot of IDs listed out. I would prefer the query to be something like this: DELETE FROM "data_stuff" WHERE "data_stuff"."data_id" IN (SELECT U0."id" FROM "data" U0 WHERE U0."batch_id" = 1) Any ideas of how I can have it generate the SQL like my second example when deleting? -
Update multiple Django view variables
My Django app has several views dependent on the same input variables. In the example below, both my views depend on the 'animal' variable, which is set outside of each view. Now, the user needs the ability to change the 'animal' variable from 'Dog' to 'Cat' in the user interface. This essentially changes the universe of the app from "Dog" to "Cat", and the whole app pulls information based on the new variables. I can make this change manually from editing my views.py with no issues. However, I need the user to be able to switch back and forth themselves. I've read that SESSIONS is designed to handle this. But I had 2 primary questions... Since the views REQUIRE that variable to not be null, how to I set a default value for whenever a user logs into the application? Do I need to retype request.session.get() in every view? Or can I use sessions to update the 'animal' variable at the top of my views.py? Thanks in advance for all your help. animal = 'Dog' def index(request): animal_types = animals.objects.filter(type=animal) params = {'animals':animal_types,} return render(request, 'index.html', params) def summarypage(request): summarytypes = animailsummary.objects.filter(type=animal) params = {'animals':animal_types,} return render(request, 'summary.html', params) (additional … -
Django password reset fails on submitting email with error shared below
[Error Message][1] [1]: https://i.stack.imgur.com/N6Txl.png Exception Type: ProgrammingError at /accounts/password_reset/ Exception Value: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near ')'. (4145) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") -
Is there a way to implement a progress tracker in django or using js?
I have been trying to implement a user progress tracker like that used on online learning sites eg Udemy for tracking user progress on watching videos and increments automatically. How can I achieve the same thing using Django or JavaScript .Thank you -
order by method is not working on queryset
order by not working on queryset no working at all and i dont know where is the mistake seems everything is okay ! views.py class PostDetailView(DetailView): model = Post template_name = 'detail.html' #context_object_name = 'post' #form_class = CommentForm def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) post_comments = Comment.objects.filter(post=self.get_object()).order_by('-date_added') data['comments'] = post_comments if self.request.user.is_authenticated: data['comment_form'] = CommentForm(instance=self.request.user) return data def post(self, request, slug, *args, **kwargs): new_comment = Comment(comment=request.POST.get('comment'), name = self.request.user, post = self.get_object()) new_comment.save() return redirect('core:detail', slug=slug) models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.comment -
How to appropriately outline the path for django-duo-auth?
I am currently working on implementing Duo Two-Factor Authentication into my django project. Currently it looks like django-duo-auth is the best package for this. I installed the package and went through the basic instructions on their README: https://github.com/Elemnir/django-duo-auth/blob/master/README.rst However this has caused my project to continuously redirect to a nonexistent subdirectory of 'duo' which is what I named the path. For example my app is loaded in XX.XX.XX.XX:YYYY Going to that url auto redirects the page to: http://XX.XX.XX.XX:YYYY/duo/login/?next=/ Or, XX.XX.XX.XX:YYYY/admin auto redirects to: http://XX.XX.XX.XX:YYYY/duo/login/?next=/admin This simply will lead to django's generic base.html that duo_auth_form.html extends Here are some snippets of relevant code, though it doesn't differ to much from the package's README suggestions /urls.py urlpatterns = [ ... path('admin/', admin.site.urls), path('duo/', include('duo_auth.urls')), ] /settings.py INSTALLED_APPS = [ ... 'duo_auth', ] MIDDLEWARE = [ ... 'duo_auth.middleware.DuoAuthMiddleware', ] DUO_CONFIG = { 'DEFAULT': { 'HOST': '<api-host-url>', 'IKEY': '<integration_key>', 'AKEY': '<app_secret_key>', 'SKEY': '<secret_key>', 'FIRST_STAGE_BACKENDS': [ 'django.contrib.auth.backends.ModelBackend', ] } } The only difference anywhere from the read me is a slight redirection in the sample do_auth_form.html where I extend to a subdirectory of my templates i.e. {% extends "dir\base.html" %} at the top of the file. It appears like this package is fairly new and … -
How to simulate a POST to a URL using Django
I'd like to create a view function that simulates the user getting a form at url, setting one of the form's input variables (my_flag) and submitting that form. I've tried two different approaches and both have failed. Approach 1: use python requests to get and post to url def simulate_post(request): url = request.build_absolute_uri(reverse('my_app:form_view', args=[666])) response = requests.get(url) csrftoken = response.cookies['csrftoken'] print("TOKEN =", csrftoken) response = requests.post(url, data={'my_flag': True, 'csrftoken': csrftoken}, headers={'Referer': url}) return response This approach fails as follows. Obviously I'm not even passing on the CSRF token successfully: TOKEN = EXFI2xoKxHounDIRnqdrPwLpdXGe3zuZATErKINTuxJsgzV7Oj6lPP6kzsjQVc7z Forbidden (CSRF cookie not set.): /form_view/666/ [12/Feb/2021 16:44:02] "POST /form_view/666/ HTTP/1.1" 403 2868 Internal Server Error: /simulate_post/ Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/me/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "/Users/me/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'Response' object has no attribute 'get' Approach 2: use RequestFactory def simulate_post(request): url = request.build_absolute_uri(reverse('my_app:form_view', args=[666])) factory = RequestFactory() factory.user = request.user response = factory.get(url) response = factory.post(url, data={'my_flag': True}) return response This approach fails as follows: Internal Server Error: /simulate_post/ Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) … -
How to secure Django Rest API
I created custom survey with React and I want to send data once survey is complete to Drip (user managing platform) https://developer.drip.com/ I can't connect website with Drip API directly - it'll expose API Key. I decided to use Python Django with REST as proxy. My question - what's possible threats and how can I secure my Backend? Thanks! -
Django templates : <how to create a view like this>
{% if node.post_type == "photo" %} {% get_file node as files %} {% if files.count == 1 %} {% for file in files %} <img class="r-8 cover" src="{{file.file.url}}" width="100%" height="150px"> {% endfor %} {% else %} <div class="form-row"> {% for file in files %} <div class="col p mrn-2"><img class="cover mbn-2 rlt-8" src="img/ic_profile_test.png" width="100%" height="74px"> <img class="cover rlb-8" src="img/ic_profile_test.png" width="100%" height="74px"></div> <div class="col p"><img class="cover mbn-2 rrt-8" src="img/ic_profile_test.png" width="100%" height="74px"> <img class="cover rrb-8" src="img/ic_profile_test.png" width="100%" height="74px"></div> {% endfor %} </div> {% endif %} {% endif %} ** This is what i want to achieve ** https://i.stack.imgur.com/6q5hd.png ** But i keep getting this ** https://i.stack.imgur.com/2TS9H.png Please how can i do something like this If user post two pictures i only display row 1 If user post three pictures i display row 1 and row 3 and hide the last child If user post four pictures i display all child -
How can I use a singe test file django
For testing, I am currently using TemporaryUploadedFile for the file field on one of my models. The issue is each time I run a test, there is a new file created. Is there a way that I can point the file field to a pre existing file named something like txt.txt stored in a pre-defined directory? In the test I define the file as : self.example_file.file = TemporaryUploadedFile( "temp.txt", size="100kb", content_type="txt", charset=b"This is the content of the file!" ) In the mdoel the file is created using models.FileField: example_file = models.FileField( blank=True, null=True, upload_to=UploadToPath('files'), ) What I would like to be able to do is in the test is simply point to a one off pre existing file. I can not figure out how to do it. If this can not be done and anyone knows of a better alternative where I do not need to upload a new file each time I use the file field in testing it would be great to know how to do that as well! -
how to Pick Address from Google Maps and auto fill in user address form in django webapp?
how could the client pick delivery order address from google maps in my website and auto fill the address in client address form User can drag the map and place a marker therein and then user can select details address from that location and set to anywhere else. -
Converting postgres window function with condition into Django ORM
I need help converting following postgres sql into django ORM. with t as ( select ft.student_id , ftd.pending_amt ,row_number() over(partition by student_id order by ftd.created_dt desc) as max_id from fee_transaction ft inner join fee_transaction_detail ftd on ft.id = ftd.fee_transaction_id inner join student s on ft.student_id =s.id where fee_type_id = (select id from fee_type ft2 where id=1) and s.classes_id = 4 and s.faculty_id =3 ) select * from t where max_id=1 and pending_amt > 9000 ; There are 3 tables involved: Student - id,classes_id, faculty_id fee_transaction - id,student_id, fee_transaction_detail - id, pending_amt, created_dt, fee_transaction_id I did go through the django window_function Documentation but couldnt find a concrete example which would help me understand. -
could not connect to server: Connection refused Is the server running on host "database" (172.19.0.3) and accepting TCP/IP connections on port 5432?
I am trying to run Django tests on Gitlab CI but getting this error, Last week it was working perfectly but suddenly I am getting this error during test run django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "database" (172.19.0.3) and accepting TCP/IP connections on port 5432? My gitlab-ci file is like image: docker:latest services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 test: stage: test image: tiangolo/docker-with-compose script: - docker-compose -f docker-compose.yml build - docker-compose run app python3 manage.py test and my docker-compose is like : version: '3' volumes: postgresql_data: services: database: image: postgres:12-alpine environment: - POSTGRES_DB=test - POSTGRES_USER=test - POSTGRES_PASSWORD=123 - POSTGRES_HOST=database - POSTGRES_PORT=5432 volumes: - postgresql_data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -e \"SHOW DATABASES;\""] interval: 5s timeout: 5s retries: 5 ports: - "5432" restart: on-failure app: container_name: proj hostname: proj build: context: . dockerfile: Dockerfile image: sampleproject command: > bash -c " python3 manage.py migrate && python3 manage.py wait_for_db && gunicorn sampleproject.wsgi:application -c ./gunicorn.py " env_file: .env ports: - "8000:8000" volumes: - .:/srv/app depends_on: - database - redis So why its refusing connection? I don't have any idea as it was working last week :( . Kindly help -
how to connect production settings in django
i have changed this 'django_project.settings' to this 'django_project.settings.production' in wsgi.py , manage.py also in env - 'export django_project.settings.production' but i still get this error (venv) user@ip-172-31-59-68:/var/www/html/web$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/var/www/html/web/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/core/management/base.py", line 343, in run_from_argv connections.close_all() File "/var/www/html/web/venv/lib/python3.8/site-packages/django/db/utils.py", line 232, in close_all for alias in self: File "/var/www/html/web/venv/lib/python3.8/site-packages/django/db/utils.py", line 226, in __iter__ return iter(self.databases) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/var/www/html/web/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/var/www/html/web/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 970, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_project.settings.production'; 'django_project.settings' is not a package how can i change dirrection to read only production.py settings from .base import * SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = False SITE_ID = 1 INTERNAL_IPS = ['127.0.0.1',] ALLOWED_HOSTS = ['127.0.0.1','example.com','www.example.com'] STATIC_ROOT = '/var/www/html/web/blog/static/' MEDIA_ROOT = … -
Django - Filter based on nested sum of related values
I have 3 Django models like this Request is a donation request, RequestItem denotes how many instances of the name item are needed, Donation denotes how many donations have been done for the connected item class Request: pass class RequestItem: name request = ForeignKey(Request) needed = IntegerField() class Donation: item = ForeignKey(RequestItem) donated = IntegerField() I need to filter out the donation requests which aren't still complete The database is ensuring that the sum of the donated items for any RequestItem is never greater than the no of items needed. So my first thought was to get the sum of the needed items, via .annotate(needed=Sum('request_item_set__needed')) and similarly get the total no of donated items, via .annotate(needed=Sum('request_item_set__donation_set__donated')), but as the question suggests, I'm stuck at getting sum of items related to the related items of the entry. -
Django: Avoiding Multiple Queries When Aggregating A Queryset's Model Properties
I have my models.py set up like: class Garage(models.Model): garage_name = models.CharField(max_length=200, null=True, blank=True) class Car(models.Model): car_name = models.CharField(max_length=200, null=True, blank=True) garage = models.ForeignKey(Garage, on_delete=models.CASCADE, related_name="cars", null=True, blank=True) # Returns last service time. @cached_property def last_service(self): last_service = ServiceEvent.objects.filter(car_id=self.id, service_time__lte=timezone.now()).values('service_time').latest('service_time') return last_service.service_time # Returns True If Serviced Since Most Recent Hire. @cached_property def serviced_since_last_hire(self): last_hire = HireEvent.objects.filter(car_id=self.id, end_date__lte=timezone.now()).values('end_date').latest('end_date') if last_service() < timezone.now() and last_service() >= last_hire.end_date: return True else: return False # Returns True If Serviced Since Most Recent Hire. @cached_property def currently_available(self): current_events = HireEvent.objects.filter(car_id=self.id, end_date__gte=timezone.now(), start_date__lte=timezone.now()) if current_events.exists(): return False else: return True class ServiceEvent(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="service_events") service_time = models.DateTimeField(null=True,blank=True) class HireEvent(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="hire_events") start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) I am using the model properties to reduce code duplication as I use currently_available and serviced_since_last_hire elsewhere. My Views.py attempts to calculate for a given garage 4 aggregate metrics; how many cars are currently serviced how many are currently hired how many are serviced and available how many are not serviced but otherwise available Views.py def garage_test(request, garage_id): car_list = Car.objects.filter(garage_id = garage_id) total_currently_serviced = 0 total_currently_available = 0 total_serviced_and_available = 0 total_not_serviced_and_available = 0 for car in car_list: car_serviced_since_last_hire = car.serviced_since_last_hire … -
request.user on AbstractUser gives AnonymousUser TypeError
Calling request.user on AbstractUser model gives TypeError 'AnonymousUser' object is not iterable. I created an abstract user model as such: class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=30) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) I added JSON Web Tokens to my User model. I want to get the details of the current user when I go to a particular URL. To do this, I tried this in views.py: @api_view(['GET']) def getUserProfile(request): user = request.user serializer = UserSerializer(user, many=True) return Response(serializer.data) And this in serialisers.py from django.conf import settings User = settings.AUTH_USER_MODEL class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' Now, when I go to the url where this view is called from, I get TypeError 'AnonymousUser' object is not iterable. I think this is because request.user does not recognise my AbstractUser. This problem occurs even when I am logged in. How do I fix this? -
How to have multiple fields on a line in a django formset
Trying to build a Django formset. I have it working but here is the problem. I want the part of the form which is repeating to have several fields on 1 line - because screen real estate is an issue. The template code I used is: {% extends "base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} <h2>Program</h2> <hr> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <table class="table"> {{ segments.management_form }} {% for form in segments.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Save"/> <a href="{% url 'program_update' program.pk %}">back to the list</a> </form> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'formset/jquery.formset.js' %}"></script> <script type="text/javascript"> $('.formset_row').formset({ addText: 'add segment', deleteText: 'remove', prefix: 'segment_set' }); </script> … -
Object of type Venta is not JSON serializable - Error when modifying form and saving it in db
I am trying to modify a form, previously everything was fine, but when updating my model with a boolean value I get this error. File "C:\Python\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Venta is not JSON serializable Trackback: https://pastebin.com/VkChnU9s -
Djanog app quickbooks authorization page from client
need some help to understand how can I have a page in my app in which I ask my clients to authorize my app to have access to my clients quickbooks. I m ok to connect to quickbooks in my app but I add manually clients credentials. I would like to have template in my Django app that handle this. My client will use this template to authorize my app to have access to QBO? any help is kindly needed as I don't know how to do this... thanks -
Passing a Javascript variable to Django view using Ajax
I'm trying to pass a variable from Javascript to a Django view using Ajax. What I got so far is this: template <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> var Test="SomeValue" // This is the variable that I want to pass $.ajax({ url: '/MyTemplate', type: 'get', data: { test: Test, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(data) { alert("Success"); }, failure: function(data) { alert('Error'); } }); </script> In my view: def MyView(request): vrTest = request.GET.get('Test') // Here I tried to use Test, test, data on nothing seems to work print(vrTest) #Here I just want to print the value "SomeValue" But when I print vrTest it the console says None -
'Manager' has no attribute 'get_by_natural_key'
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have password") user = self.model( email = self.normalize_email(email) ) user.set_password(password) #change user password user.staff = is_staff user.admin = is_admin user.active = is_active user.save(using=self._db) return user def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) #can login staff = models.BooleanField(default=False) #staff user non superuser admin = models.BooleanField(default=False) #superuser timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' #username #email and password required by default REQUIRED_FIELDS = [] def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active I tried following a video on how to create a custom user model, but when I tried to create a superuser, I got the following error after entering my email: You have 1 unapplied migration(s). Your project may not work properly until you apply … -
Django Rest Framework Serializer - return related field
I have a model with a one-to-one relationship with a main model: class User(models.Model): id = models.BigIntegerField(primary_key=True) username = models.CharField(max_length=100, blank=True) class AggregatedStats(models.Model): user_id = models.ForeignKey('User', on_delete=models.DO_NOTHING, unique=True) followers_30d = models.BigIntegerField(blank=True) I have written the following serializers: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['id', 'username', 'followers'] class AggregatedStatsSerializer(serializers.HyperlinkedModelSerializer): username = UserSerializer(source='user.username') class Meta: model = AggregatedStats fields = ['followers_30d', 'username'] I am trying to return the username from the User model, but whatever I try to get it, the best I can do is get the hyperlinked related field from user, but not the actual "username" attribute. How would you return this? -
How to add different default values to Foreign Key in Django Models?
I have two models (Article and ArticleContent), in Article, three instances of ArticleContent, which should change only one attribute.I am doing this because each article will have its respective translation. These are my models: class ArticleContent(models.Model): class LANGUAGES(models.TextChoices): ES = 'es', 'Español' EN = 'en', 'English' PT = 'pt', 'Português' language = models.CharField(choices=LANGUAGES.choices, max_length=2) title = models.CharField(max_length=300) body = models.TextField() class Article(models.Model): content_es = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_es') content_en = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_en') content_pt = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_pt') cover_image = models.FileField(upload_to='uploads/') chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, related_name='articles') What I need to do is something like this, in my Article model: content_es = models.ForeignKey(ArticleContent(language=ArticleContent.LANGUAGES.ES), on_delete=models.CASCADE, related_name='article_es') content_en = models.ForeignKey(ArticleContent(language=ArticleContent.LANGUAGES.EN), on_delete=models.CASCADE, related_name='article_en') If I could do it this way, I could define a default value according to the language. Is there any way to do this? -
It's possible to set the m2m field without saving it in the database/create a database connection/query in Django?
I want to use bulk method to update m2m field, but not works, because .add and .set method create a database connection. These methods take a long time to execute, and the objective of the bulk is precisely to make the insertion be in bulk, and not one at a time Code sample: athletes = Athlete.objects.all() games = Game.objects.all() # objects to update in bulk games_objs_with_m2m = [] for game in games: athlete_related = athletes.get(id=game.athlete_id_ref) game.athlete.add(athlete_related) # here is the problem, .add or .set create a db connection for each instance games_objs_with_m2m.append(game) Game.objects.bulk_update(games_objs_with_m2m, ["athlete"]) Complete code, a script to populate data from csv file: https://pastebin.com/L1pMzBU4