Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting multiple textfield values - Javascript/Django
This is my code. I'm trying to get all the values from the dynamically generated textboxes so that I can average them and will use the value later. Is there any easy way to get all the values and their average? for(var i = 0; i < input_list.length -1; i++) { var label_input = document.createElement('label'); label_input.innerHTML = input_list[i+1]; document.getElementById("newElementId").appendChild(label_input); for(var j = 0; j < 5; j++) { $('#newElementId').append("<div><input type='textbox' id='"+ input_list[i+1] + j +"' /></div>"); } } -
Why do some model objects reset every time i redeploy and after a while of time passes in Django Heroku?
This is probably a really dumb question. Every time I redeploy my django app on heroku i get the same two instances of my object that were there before i deployed. I would like to change these. I would like to add some. I would like to delete some. But every time I redeploy, and after some time passes after I make changes, it always reverts back to what it was. It is horrible. Please let me know what I am doing wrong. NOTE: I AM ALREADY HOLDING MY FILES SOMEWHERE ELSE. I don't believe this has anything to do with the ephemeral file system, since I already am storing files somewhere else. But why is it that every time I redeploy the instances of the objects themselves (instances of the things inside Models) go away?? Thanks in advance. -
'TypeError' object has no attribute ''
I am using SendGrid with Django and I have two separate functions. One works using the SendGrid code (See below - Working Code) and then the other keeps getting the Error - 'TypeError' object has no attribute 'booking_message'. I imagine the issue is something small and I keep missing it. Appreciate any help I can get on this. (Note - I have taken out the template id's, From and to email addresses and SendGrid API App id and just let '') I did not have time to use an environment variable to hide the keys before posting. Working code class ASPBookingsCreateView(CreateView): form_class = ASPBookingsForm model = ASPBookings template_name = "vistours/asp.html" def post(self, request): # Save the new booking to the database. if request.method == 'POST': form = ASPBookingsForm(request.POST) if form.is_valid(): print(request.POST) form.save() # Get the data for the emails. asp_data = ASPBookings.objects.all() asp_data.contact_name = request.POST['contact_name'] asp_data.booking_email = request.POST['email'] asp_data.booking_date = request.POST['booking_date'] asp_data.booking_time = request.POST['booking_time'] asp_data.program_type =request.POST['program_type'] # Format Date and Time formatted_date = parse_date(asp_data.booking_date).strftime('%A %d %B %Y') print(formatted_date) # Add SendGrid Template ID's BOOKING_TEMPLATE_ID = '' UPDATE_TEMPLATE_ID = '' # Send confirmation email of the booking. booking_message = Mail(from_email='', to_emails=[asp_data.booking_email], ) # Add Template ID to booking message. booking_message.template_id = … -
how do I produce m2m model from sql schema?
I am new with django ecosystem where I want to create the following tables from SQL to django model syntaxis where I got stuck at how to produce this proxy table tools_x_techniques as m2m CREATE TABLE tools_x_techniques ( # m2m id INTEGER PRIMARY KEY AUTOINCREMENT, tool_id TEXT NOT NULL, technique_id TEXT NOT NULL, FOREIGN KEY (tool_id) REFERENCES tools (id), FOREIGN KEY (technique_id) REFERENCES technique (id) ); CREATE TABLE tools ( id INTEGER PRIMARY KEY AUTOINCREMENT, tool_id TEXT NOT NULL, ); CREATE TABLE techniques ( id INTEGER PRIMARY KEY AUTOINCREMENT, technique_id TEXT NOT NULL, ); django class Techniques(models.Model): technique_id = models.TextField() class Tools(models.Model): tool_id = models.TextField() -
ERROR: Command errored out with exit status 1: 'import sys, setuptools, tokenize; sys.argv[0]
how to solve this problem. I am tried to solve the error can't properly deploy my Django project on Heroku build logs: | ^~~~~~~~~~~~~~~~~~~~~ error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-zu1munoh/typed-ast/setup.py'"'"'; __file__='"'"'/tmp/pip-install-zu1munoh/typed-ast/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-s15khtlb/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/typed-ast Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed Procfile web: gunicorn My_Ecom_Project.wsgi -
Server Request Interrupted Heroku
I am using React Native and Django. Everything was working fine, until I made a request and I got the following error: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/api/obtain-img" host=notarealapp.herokuapp.com request_id=... fwd="..." dyno=web.1 connect=0ms service=22ms status=503 bytes=316 protocol=https Also, I don't know if this is useful information, but I got the following error too: <rest_framework.request.Request: POST '/api/obtain-img'> The fetch code I used is this: let token = await SecureStore.getItemAsync("token"); console.log(uri); let filename = uri.split("/").pop(); let match = /\.(\w+)$/.exec(filename); let type = match ? `image/${match[1]}` : `image`; let formData = new FormData(); formData.append("image", { uri: uri, name: filename, type: type }); // formData.append("cateogry", category); // formData.append("mission", value); console.log(formData); return await fetch("https://notarealapp.herokuapp.com/api/obtain-img", { method: "POST", headers: { "content-type": "multipart/form-data", Authorization: `JWT ${JSON.parse(token)}`, }, body: formData, }) .then((res) => res.json()) .then((json) => console.log(json)) .catch((error) => console.error(error)); And my Django code is the following: class ObtainImageUri(APIView): permission_classes = [IsAuthenticated] def post(self, request, format=None): print(request) return Response({"succes": "The receipt was stored successfully."}, status=200) I am open to any help. Thank you -
IntegrityError: UNIQUE constraint failed: auth_user.username - Django
I have a sample application that simply logs in and registers users. I am adding functionality for checking whether a username is already taken. For that, in the form code, I put a validation function as is usual in django. It's called clean_username. There are also functions like clean_email and clean to check the sanity of data. While the other two work just fine to weed duplicates, the clean_username function is particularly erroneous. Though I have added a line to check whether the username already exists, it still throws the same Integrity Error, which is exactly what I am trying to avoid. The clean_username function is of our concern here. Note: The print statements are only added for debugging purposes. Please find the code below (forms.py): from django import forms from django.forms.widgets import Widget from django.contrib.auth import get_user_model from email_validator import validate_email, EmailNotValidError from .constants import countries User = get_user_model() class RegisterForm(forms.Form): login = forms.CharField(label="Username:") password = forms.CharField(label="Password", widget=forms.PasswordInput()) confirm_password = forms.CharField(label="Confirm Password:", widget=forms.PasswordInput()) email = forms.EmailField(label="Email") def clean_username(self): print(f"Clean Username data: {self.cleaned_data}") username = self.cleaned_data.get("login") print("cleaning username...") existing_user_set = User.objects.filter(username=username) if existing_user_set.exists(): raise forms.ValidationError("Username is taken!!") return username def clean(self): data = self.cleaned_data print(f"\n\nData from cleaned data: {data}") password … -
Include a .html file in Django template that is located in a different directory
Let's say I have the following directory structure |-data |-include_this.html |-app |- templates |- app |- page.html In page.html, I'd like to include the include_this.html file contained in the data folder. I have tried the following: {% include '../data/papercups.html' %} {% include '../../data/papercups.html' %} {% include './../data/papercups.html' %} But none of them seem to work, and the second one throws the error: The relative path points outside the file hierarchy that template is in. What's the correct way to do this? -
axios wont retrieve data from django server
I try to retrieve data from my django server to render it with react but I encountered a probem: The data doesen't render. I have my django server running in localhost:8000 and react app running in localhost:3000 my App.js: import React from 'react'; import axios from 'axios'; class App extends React.Component { state = { details : [], } componentDidMount() { let data ; axios.get('http://localhost:8000/wel/') .then(res => { data = res.data; this.setState({ details : data }); }) .catch(err => {}) } render() { return( <div> {this.state.details.map((detail, id) => ( <div key={id}> <div > <div > <h1>{detail.detail} </h1> <footer >--- by <cite title="Source Title"> {detail.name}</cite> </footer> </div> </div> </div> ) )} </div> ); } } export default App; and my server page where I try to retrieve data from: localhost:8000/wel what's going on? -
Redis Error condition on socket for SYNC: Connection refused
Using celery with redis in my django app Everything was working fine until I ran into a problem. The location of the redis files was changed and redis could not access them. After searching, it turns out that this is due to random attacks on the Internet, and it is necessary to add confg After I added the file, they both worked fine for a while, and then this problem appeared 1:S 25 Jun 2021 00:48:12.029 # Error condition on socket for SYNC: Connection refused 1:S 25 Jun 2021 00:48:12.901 * Connecting to MASTER 194.38.20.199:8886 1:S 25 Jun 2021 00:48:12.902 * MASTER <-> REPLICA sync started 1:S 25 Jun 2021 00:48:13.034 # Error condition on socket for SYNC: Connection refused 1:S 25 Jun 2021 00:48:13.907 * Connecting to MASTER 194.38.20.199:8886 1:S 25 Jun 2021 00:48:13.908 * MASTER <-> REPLICA sync started 1:S 25 Jun 2021 00:48:14.041 # Error condition on socket for SYNC: Connection refused When I rebuild the Redis container it runs for a very short time and I get the same problem settings.py CELERY_BROKER_URL = os.environ.get("redis://redis:6379/0") CELERY_RESULT_BACKEND = os.environ.get("redis://redis:6379/0") docker-compose.yml redis: image: 'redis:alpine' restart: unless-stopped command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./docker/redis/redis.conf:/usr/local/etc/redis/redis.conf ports: - '6379:6379' celery: restart: unless-stopped build: … -
How to allow only a certain section of my code to reload in Django
So, I am using a Django application where I am using the google maps API as well. So this is the instance...when I submit a form... I only want my form div to reload and NOT the div where my map lies. So my code is... <section class="middleSection p-2"> <div class="HideOpenMiddleCont justify-content-center" onclick="HideOpenMiddleCont()"> <div class="px-4 rounded-pill bg-warning" id="arrowCont"> <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" class="bi bi-arrow-down-short text-dark" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M8 4a.5.5 0 0 1 .5.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5A.5.5 0 0 1 8 4z"/> </svg> </div> </div> {% if view == 'trip' %} {% include "app/passenger/trip.html" %} {% elif view == "upcomingRides" %} {% include "app/passenger/upcomingRides.html" %} {% elif view == "pastRides" %} {% include "app/passenger/pastRides.html" %} {% endif %} <div class="optionBarPull" data-bs-toggle="offcanvas" href="#offcanvasExample" role="button" aria-controls="offcanvasExample"> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-arrow-right-circle-fill" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z"/> </svg> </div> </section> <section class="rightSection" id="map"> <h3 class="font3 text-center p-2"><strong>Google Maps is here</strong></h3> <h4 class="font3 text-center … -
JavaScript variable doesn't loop through Django model
Topic is a CharField, summary is TextField within topic. For some reason, the JavaScript doesn't loop through summary TextField -- it just uses the very first summary TextField and simply ignores the rest. I want every summary TextField to looped through and displayed. Not just the first one. Does this make sense? Something is wrong with my JavaScript code. As you can see in the image -- second topic's (Bitcoin) summary is missing (highlighted in red) Image displaying the problem on the webpage {%for topic in topics%} <script> var i = 0; var txt = '{{topic.summary}}'; function typeWriter() { if (i < txt.length) { document.getElementsByClassName('js-typewrite')[0].innerHTML += txt.charAt(i); i++; setTimeout(typeWriter, 65); } } setTimeout(typeWriter, 1000); </script> <body> <p class="content"> <span class="typewrite anim-typewrite js-typewrite"></span> </p> </body> </div> <div id = 'mpost-text'> {{topic.text|linebreaks}} </div> <div id = 'change-text'> {%if topic.owner == request.user and user.is_authenticated %} <a href = "{%url 'new_sites:post_edit' topic.id%}">Edit entry</a> <a href = "{%url 'new_sites:delete_post' topic.id%}">Delete topic</a> {% endif %} </div> </div> {%empty%} <li>No topics have been added yet.</li> {% endfor %} {%if user.is_authenticated%} <a href="{% url 'new_sites:new_post'%}">Add Post</a> {%endif%} {%endblock%} -
loading local files in django
I have a folder in c:\images, images here are updated by another app. Then I wanted a Django application to read those images on the admin site. The django applicationis sitting in c:\inetpub\wwwroot\myapp I have tried adding below lines in settings.py CURRENT_PATH = os.path.abspath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(CURRENT_PATH, '../../images').replace('\\','/') MEDIA_URL = 'images/' I also tried including the whole path in django admin as below in admin.py def img_field(self, obj): return format_html('<img src="{}" width="500" height="500" />'.format("c:\images\phot1.png")) If i put online image link it works fine as below: def img_field(self, obj): img = "https://www.thebalancesmb.com/thmb/5G9LJXyFzbTVS-Fj_32sHcgJ8lU=/3000x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/start-online-business-with-no-money-4128823-final-5b87fecd46e0fb00251bb95a.png" return format_html('<img src="{}" width="500" height="500" />'.format(img)) How can i get around this? -
Assign permissions to users without admin-site
Im creating a custom role-based user-management system for my Django application. I want to know, if there is a way to assign permission to Django users via roles, without using the admin-site, because when the app gets deployed, the admin-site gets "deactivated". My idea was to use a one-to-one relationship with a role-model, which extends the PermissionsMixin class and for each new role, I define a list of permissions. Whenever the has_perm() function of an user gets called, I use the has_perm() function of the linked role. I have to point out, that the roles are also used to store specific information not related to the authentication process. -
Create a django background worker, best practices
I have an API in Django, which should consume a RabbitMQ queue. I'm currently using Amqpstorm Robust Consumer, instantiated by django command management, like this: python3 manage.py mycommand. and API runs in another container using gunicorn. My queue has a high message rate coming I. My concern is if this is the best practice to run this kind of process in the background with django. Is there a better way to run this worker? I say this because my container is closing sporadically, without logging anyone, just this message: Logs Killed. -
Django admin inline - show different read-only fields based on the user and the object
Django 2.2.24. I have an inline that I want to show different read-only fields based on the user's group and a field on the model. I tried to adapt the simple methodology I used on the model's admin page: class MyObjectInline(admin.StackedInline): ... def get_readonly_fields(self, request, obj=None): fields = super(self.__class__, self).get_readonly_fields(request, obj) if obj: if request.user.groups.filter(name=SPECIAL_GROUP).exists(): if obj.tag == SPECIAL_TAG: fields += (...) else: fields += (...) return fields This doesn't work bc of the well-known issue (bug?) that the object in the inline is the parent object for the whole admin page and not the object actually represented in the inline. In researching work-arounds, it seems like a custom form is required for the inline, and then a combination of __init__ and a clean routine for each field on the model is required? But I'd also need to pass the request object into the form, which research suggests incorporating a FormSet and/or FormFactory as well? As the complexities pile up, any advice on the right way to accomplish this would be appreciated! Thanks. -
Django pass PK from post to next page
I currently have a blog post feature on my site. I want users to be able to create sub posts (build log ) off of the main posts. I created this model with a FK to the Post model class BuildLog(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) I then added a button on the post page and created a form. Everything is working as expected but when I submit the form I get the error null value in column "post_id" of relation "blog_buildlog" violates not-null constraint If I understand the error correctly it is saying I am not passing the PK of the post into the form. Views def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) form = CommentForm comments = Comment.objects.filter(post=post)#.order_by('-create') if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.author = request.user new_comment.post = post new_comment.save() context = { 'post':post, 'form':form, 'comments':comments } return render(request, 'blog/post_detail.html', context) class BuildLogView(LoginRequiredMixin, CreateView): model = BuildLog form_class = BuildLogForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def save(self, *args, **kwargs): super(BuildLog,self).save(*args, **kwargs) Url path('build-log-form/', BuildLogView.as_view(), name='build-log-form'), path('post/<int:pk>/', views.DetailPostView, name='post-detail') … -
Django many to many relationship only shows on one model in the admin
I’m new to python and django and have set a many:many relationship between the Subscriber and Tag classes (i.e. one subscriber can have many tags, and one tag can have many subscribers). In the django admin panel, viewing a tag successfully shows the connected subscribers as follows: However, viewing a subscriber does not show the tags they’re associated with: It’s like the many:many relationship is not shown on both sides. I’ve read some other similar django posts creating inlines and functions etc, but to no avail - and I want the tags to show only on the individual subscriber page rather than a column in the table before clicking on an individual subscriber. How can I get the tags to show on the individual subscriber pages? I tried with inlines but to no avail. Models.py: from django.db import models from accounts.models import Account class Subscriber(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True) # tags: many to many field, with later option of users being able to define custom tags # tags = models.ManyToManyField(Tag, blank=true) # cannot uncomment, otherwise error: "NameError: name 'Tag' is not defined" - but already has many:many relationship - just not showing … -
View function that handles only POST requests to check database
My friends and I are writing a game that uses a website for registration/login. When a player logs into the game, it'll check the Django website's SQLite database using a POST cURL request or an equal to see if the player is valid. What should I sent in my request and how should I write my function that handles this? http://127.0.0.1:8000/login/ Login includes Username Password import requests url = 'http://localhost:8000' data = { "username": "password" } x = requests.post(url, data=data) print(x.status_code) Currently, this is all I have. It tells me I have to add the CSRF token. But would just doing this and adding the csrf token work? -
django form not being saved to db
<div class="review-form"> <h1 class="review-title">Add Review</h1> <form class="form" method="POST"> {% csrf_token %} <div>{{ form.title }}</div> <textarea>{{ form.description}}</textarea> <br> <button class="submit-btn" type="submit">Submit</button> </form> </div> **forms.py** from . import models from django import forms class gameReviewForm(forms.Form): title = forms.CharField(max_length=24) description = forms.CharField(max_length=500) **models.py** from django.db import models from django.db.models.fields import AutoField, CharField, TextField class gameReview(models.Model): title = CharField(max_length=24) description = CharField(max_length=500) def __str__(self): return self.title **views.py** def add_review(request): if request.method == 'POST': form = forms.gameReviewForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] review = models.gameReview(title=title, description=description) review.save() return HttpResponseRedirect('home') else: form = forms.gameReviewForm() return render(request, 'main/add_review.html', {'form': form}) // I am trying to post data to the database but for some reason it's not actually working! Any help is greatly appreciated, the redirect doesnt execute so it seems to me that the form is somehow invalid -
Access One to One Field property in DRF Serializer
I am having trouble with setting the password as a write_only property in my Serializer. This is what I currently have, and I want to hide the password. { "nit": "54545445", "direccion": "ciudad", "telefono": "54545454", "usuario": { "id": 12, "password": "asdf12321", "last_login": null, "is_superuser": false, "username": "admin3", "first_name": "admin3", "last_name": "admin3", "email": "admin3@gmail.com", "is_staff": false, "is_active": true, "date_joined": "2021-06-24T20:47:56.286694Z", "groups": [], "user_permissions": [] } } There should be a way of getting that value in my serializer to set the write_only=True property. class UserExtraSerializer(serializers.ModelSerializer): class Meta: model = UserExtra fields = ['nit', 'direccion', 'telefono', 'usuario'] depth = 1 extra_kwargs = {''''access usuario['password'] here''': {'write_only': True, 'required': True}} -
How to get HTML5 Video page or direct download link from downloadAddr or playAddr on Tiktok
I have compacted Python + PHP project it can collect data from video page in Tiktok, now i need way to get direct video link from Tiktok cdn to download this video or create HTML5 video to show this video? because the link from downloadAddr not working if I test it in other pc or browser and thank you. what I need exactly is class with python or PHP receive URL from request and respond with the link of watching or download video from Tiktok cdn. -
How to solve ModuleNotFoundError: No module named '{{cookiecutter' in docker django
I am getting this error while running docker build. File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 204, in fetch_command #14 0.440 app_name = commands[subcommand] #14 0.440 KeyError: 'collectstatic' #14 0.440 #14 0.440 During handling of the above exception, another exception occurred: #14 0.440 #14 0.440 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed #14 0.440 File "<frozen importlib._bootstrap>", line 1014, in _gcd_import #14 0.440 File "<frozen importlib._bootstrap>", line 991, in _find_and_load #14 0.440 File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked #14 0.440 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed #14 0.440 File "<frozen importlib._bootstrap>", line 1014, in _gcd_import #14 0.440 File "<frozen importlib._bootstrap>", line 991, in _find_and_load #14 0.440 File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked #14 0.440 ModuleNotFoundError: No module named '{{cookiecutter' I have installed cookiecutter via pip. How to solve this? -
how can i create rows in 2 models(tables) with reusable functions based on one form
I want to save data in two models from a single POST request. Two different models (OF, Encours) Here's my models.py: class OF(models.Model): Id_OF= models.BigAutoField(primary_key=True) Numero_Of = models.BigIntegerField(unique=True,blank=False) class Dimension_OF(models.TextChoices): PD_inférieur_à_500mm="PD" MD_Entre_500_et_1500mm="MD" GD_supérieur_à_1500mm="GD" Dimension_OF = models.CharField(max_length=20, blank=False,choices=Dimension_OF.choices) class Machine(models.TextChoices): MGP1="MGP1" MGP2="MGP2 " MGP3="MGP3" MGP4="MGP4" MGP5="MGP5" MGP6="MGP6" MGP7="MGP7" MGP8="MGP8" Machine=models.CharField(max_length=10,choices=Machine.choices, blank=False) class Scenario(models.TextChoices): Ajustage_Controle="scenario1" Ajustage_Redressage_Controle="scenario2" Ajustage_Formage_Controle="scenario3" Ajustage_Redressage_Formage_Controle="scenario4" Scenario = models.CharField(max_length=50,choices=Scenario.choices, blank=False) Date_E_initial=models.DateTimeField(auto_now_add=True,auto_now=False) Date_S_Final=models.DateTimeField(null=True, blank=True) Etat_OF=models.CharField(max_length=50, null=True, blank=True) Nb_jrs_att_Usin=models.DurationField(null=True, blank=True) Nb_jrs_att_TM=models.DurationField(null=True, blank=True) Nb_jrs_att_total=models.DurationField(null=True, blank=True) def _str_(self): return self.Scenario class Encours(models.Model): Id_encours=models.IntegerField(primary_key=True) OF = models.ForeignKey(OF, on_delete=models.CASCADE ) class Nom_encours(models.TextChoices): EN_MGP1="Encours MGP1" EN_MGP2="Encours MGP2" EN_MGP3="Encours MGP3" EN_MGP4="Encours MGP4" EN_MGP5="Encours MGP5" EN_MGP6="Encours MGP6" EN_MGP7="Encours MGP7" EN_MGP8="Encours MGP8" EN_AJU_GD="Encours Ajustage GD" EN_AJU_MD="Encours Ajustage MD" EN_AJU_PD="Encours Ajustage PD" EN_RED="Encours Redressage" EN_For="Encours Formage" EN_Contr_GD="Encours Contrôle GD" EN_Contr_MD="Encours Contrôle MD" EN_Contr_PD="Encours Contrôle PD" Nom_encours = models.CharField(max_length=30,choices=Nom_encours.choices) Capacite = models.IntegerField(default=0) Date_E_Encours=models.DateTimeField(null=True, blank=True) Date_S_Encours=models.DateTimeField(null=True, blank=True) def _str_(self): return self.Nom_encours But before saving data into Encours I want to define some functions to test field for exemple ; if OF.Machine=='MGP1' then create a row in Encours model with Nom_Encours='Encours MGP1' and Date_E_Encours = Date_E_initial that automatically added. views.py def lancerOF(request): form = OFLancementForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() messages.success(request, 'OF lancé avec succès', extra_tags='alert') return redirect('lancer') else: messages.warning(request, … -
Django group by multiple column and get count of unique combination
In my model there are 10 fields, out of which below four I need to group on, department city state zip And then get count of records which has same combination of these values Example IT|Portland|Oregon|11111 => 100 I tried annotate however it is not giving me desired results. Please advice