Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Form field data not displaying
So I am trying to figure out why my dropdown menu will not display the list of collections for the user to pick from. IMAGE: [1]: https://i.stack.imgur.com/UIrq6.png Here is also the code for the 2 models here: class Collection(models.Model): title = models.CharField(max_length=255) def __str__(self) -> str: return self.title class Meta: ordering = ['title'] class listing(models.Model): image = models.ImageField(blank=True, null=True) name = models.CharField(max_length=255) description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT, blank=True, null=True) vendors = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=False) IF I CAN GET ANY HELP IT WOULD BE NICE. -
How to check the current isolation level setting in Django?
I'm trying to check the current isolation level setting in Django. For example, the default isolation level setting in Django is READ COMMITTED so if there is transaction.current_isolation_level(), I can print READ COMMITTED on console to check the current isolation level setting in Django as shown below: # "views.py" from django.http import HttpResponse from django.db import transaction @transaction.atomic def test(request): # Here print(transaction.current_isolation_level()) # READ COMMITTED return HttpResponse("Test") And if I set REPEATABLE READ for the isolation level setting in Django as shown below: DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'admin', 'HOST':'localhost', 'PORT':'5432', }, 'OPTIONS': { # Here 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ, }, } I can print REPEATABLE_READ on console to check the current isolation level setting in Django as shown below: # "views.py" from django.http import HttpResponse from django.db import transaction @transaction.atomic def test(request): # Here print(transaction.current_isolation_level()) # REPEATABLE READ return HttpResponse("Test") So, are there such functions or variables to get the current isolation level setting in Django? If no, how to check the current isolation level setting in Django? -
Authentication verification message is not displaying as a hyperlink in the mail but rather displaying as a text in the email. please, help me
views.py under my views I have all my views for user authentication which includes: signin, signup, signout and other function views. from django.core.mail import EmailMessage,send_mail from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from my_site.settings import EMAIL_HOST_USER from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode from django.utils.encoding import force_bytes,force_str from .tokens import generate_token from .models import User # Create your views here. def all(request): return render(request,'authentication/all_signups.html') def signup(request): if request.method == "POST": username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") password2 = request.POST.get("password2") if User.objects.filter(username=username): messages.error(request, "Username already exist!") return redirect('home') if User.objects.filter(email=email): messages.error(request, "E-mail already exist!") return redirect('home') if len(username) > 15: messages.error(request, "Length of username too long!") return redirect('home') if password != password2: messages.error(request, "Passwords do not match!") return redirect('home') if not password.isalnum(): messages.error(request, "Password must be alphanumeric!") return redirect('home') user = User.objects.create_user(username=username,email=email,password=password) user.fname = fname user.is_active = False user.save() # Welcome E-mail subject = 'Welcome to ADi meals mobile!' message = f'Hello {fname.capitalize()}, welcome to ADi meals mobile!\n\nThank you for visiting our website.\n\nWe have also sent you a confirmation email, please confirm your email address to login into … -
Form returning not valid in django
In my django app I have a User model that has a Boolean field of is_manager. User model in models.py: class User(AbstractUser): name = models.CharField(max_length=15, null=True, blank=True) last_name = models.CharField(max_length=15, null=True, blank=True) title = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField(unique=True) bio = models.TextField(null=True, blank=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING, null=True) is_manager = models.BooleanField(default=False) can_assign = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] I've been trying to create an edit page in order for managers and users to be able to change some of their fields. Regular users should be able to change their bio and title, and the managers can change the can_assign Boolean. I have a form that deals with the logic of that in forms.py: class EditUserForm(ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') if self.user.is_manager: super().__init__(**kwargs) else: super().__init__(**kwargs) del self.fields['can_assign'] class Meta: model = User fields = ['title', 'can_assign', 'bio'] views.py: @login_required def editUser(request, pk): user = User.objects.get(id=pk) if request.user.is_manager or request.user == user: #POST if request.method == 'POST': form = EditUserForm(request.POST, instance=user, user=request.user) if form.is_valid(): form.save() redirect('user-page', pk) else: print('nope') #GET form = EditUserForm(user=request.user, instance=user) context = {'user': user, 'form': form} return render(request, 'users/user_edit.html', context) else: return HttpResponse('<h1>Access Denied</h1>') template: {% extends 'main.html' %} {% block content … -
CircleCI config for django
I have this circleci config version: 2.1 orbs: python: circleci/python@0.2.1 jobs: build: executor: python/default docker: - image: circleci/python:3.9 environment: DATABASE_URL: postgresql://circleci@localhost/circle_test - image: circleci/postgres:13.3 environment: PGHOST: localhost PGUSER: circleci POSTGRES_USER: circleci POSTGRES_DB: circle_test POSTGRES_HOST_AUTH_METHOD: trust steps: - checkout - python/load-cache - run: name: Installing dependencies command: | python3 -m venv venv . venv/bin/activate pip3 install -r requirements.txt - python/save-cache - run: name: Running tests command: | . venv/bin/activate python manage.py test When i commit django-test with TestCase, only choose test with SimpleTestCase, circleci comlete, but when i uncomment TestCase i have this errors RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead -
How Do I Override GET in Django Detailview?
I have a FORMVIEW that is redirecting to a DETAILVIEW and that is working perfectly. The issue I'm having is when I try to combine Pagination with DetailView. When I try to leverage the pagination, the GET is essentially redirecting me to the FORMVIEW. I get why it's doing this...I'm telling it to. What I'm trying to work out is how I can put in some logic in my overridden GET. I tried to do a self.GET_OBJECT.pk...to see if I could determine if I'm on the current page and not the FORMVIEW but that didn't work... Here's my DetailView.... def get_context_data(self, **kwargs): context = super(SuggestionByNameDetailView, self).get_context_data(**kwargs) attachments = SuggestionFiles.objects.filter(suggestion=self.object.pk).all() comment_form = SuggestionCommentForm() response_form = SuggestionCommentReplyForm() activities= self.get_related_activities() context['suggestion_comments'] = activities context['page_obj'] = activities context['attachments'] = attachments context['comment_form'] = comment_form context['response_form'] = response_form return context def get_related_activities(self): queryset = self.object.suggestion_comments.all() paginator = Paginator(queryset,5) #paginate_by page = self.request.GET.get('page') activities = paginator.get_page(page) return activities def get_object(self, queryset=None): return get_object_or_404(Suggestion, id=self.request.GET.get("dropdown")) def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") if dropdown is not None: if Suggestion.objects.filter(Q(id=self.request.GET.get("dropdown"))).distinct(): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) else: raise Http404 else: messages.add_message(self.request, messages.INFO, 'Suggestion is required.') return HttpResponseRedirect(reverse('Suggestions:suggestion_by_name')) As mentioned I did try to do something like...if DROPDOWN is … -
Insert multi selected option text into pg using django
For instance, I used Django to pull certain unique number data from my database. Then I created dropdown with search using select2. And used jQuery for search functionality. With this I could select multiple unique number at a time and with output printed in textarea field. my question is, how to insert multiple selected options in Postgrel using Django. I need help in backend as i m newbie in django I tried to served everywhere but I could see only php guide. this is my frontend code enter code here Search Models for CId {% csrf_token %} {% for x in searchmodels %} {{ x.cid }} {% endfor %} You can add multiple CID and click Add --> <br> <div class="resultbox"> <h2>Selected CIDs</h2> <textarea name="" id="cidresult" cols="70" rows="15"></textarea><br><br> <input type="button" id="addcid" value="Submit" onclick="searchresult();"> </div> </form> </tr> <style> .resultbox{ position: fixed; left: 30%; top: 10px; width: 550px; background-color: antiquewhite; padding-left: 30px; padding-right: 10px; } </style> Now here is my jQuery code $(document).ready(function() { $('#selectedcid').select2({ placeholder:'Search CID...', closeOnSelect:false }); $('#selectedcid').on('change',function() { var resultdisplay=$('#selectedcid option:selected').text(); $('#cidresult').val(resultdisplay).join(','); }) }); this is how it looks nowenter image description here -
Django custom permission not being assigned to newly created User
This seems pretty trivial but I can't figure out what I'm doing wrong. I've checked several SO posts that sounded similar but the issue apparently lies elsewhere. I have a custom permission on my model, can_key, and this is registered properly. When I try to add this permission to a newly created user, it's not added. from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission def create_dummy_user(self, username): username = 'dummy_user' user = get_user_model().objects.create(username=username, password='asdf4321') user.save() user = get_user_model().objects.get(username=username) permission = Permission.objects.get(codename="can_key") print(permission) user.user_permissions.add(permission) user = get_user_model().objects.get(username=username) print(f"{user.username} is_active - {user.is_active}") print(f"{user.username} has perm {permission.codename} - {user.has_perm(permission)}") return user This is the print outputs test_web | main_app | record case | Can key record case test_web | dummy_user is_active - True test_web | dummy_user has perm can_key - False So the user was created and the permission exists / is retrieved, but the permission isn't being added. Why? -
The styles and javascript files aren't showing when deploy Django application to a2hosting CPanel
I've deployed my Django application to the a2hosting web hosting the styles aren't showing. Also, the page that has swagger documentation is blank and doesn't have anything. Here in the image, you can see how the Admin page is showing. admin page I've made collectstatic and here is the setting.py configurations: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
How to send emails using Django All auth?
I'm trying to send emails for signup/account verification etc using django allauth, and it has worked correctly during development using the console as the email backend, however now I'm trying to send emails in using gmail, I'm getting the below error: SMTPAuthenticationError at /accounts/password/reset/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials q1-20020adfdfc1000000b0022e049586c5sm11068760wrn.28 - gsmtp') I've tried following the steps in the article mentioned in the error message, but they haven't worked. Not sure what I'm doing wrong, any help would be much appreciated! EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = '*****' -
Django Rest Framework: Not sending email from react form Error 400
I'm trying to send a form using the API endpoint beneath. The problem is that I get a 400 error when I use my react based application. If I'm using the api endpoint page it works. I checked the payload and the only difference seems to be that i'm not sending a csrf token in my react app. So far it was never neccesary when i used model serializers. I believe it is something inside the serializer but i cannot pin it down. Does anyone know what might be causing the 400 error? sendEmail.js const testmessage = "This is a test message" const testemail = "dsfds@dsfg.de" const clientnametest = "name" function sendProposal(values) { console.log("start sending proposal..."); setSendProp(true) const data = new FormData() data.append("Clientname", clientnametest || ""); data.append("Sender", testemail || ""); data.append("Message", testmessage || ""); axios.post(API.email.proposal, data, { headers: { "Authorization": `Bearer ${accessToken}`, 'Accept' : 'application/json', }, withCredentials: true, }) .then(res => { }) .finally(() => { setSendProp(false) }) success() } views.py class ProposalEmailView(APIView): permission_classes = [IsAuthenticated] serializer_class = ProposalEmailSerializer def post(self, request, *args, **kwargs): serializer_class = ProposalEmailSerializer(data=request.data) if serializer_class.is_valid(): data = serializer_class.validated_data ClientName = data.get('ClientName') Sender = data.get('Sender') Message = data.get('Message') send_mail('Contact Form mail from ' + ClientName, Message, Sender, … -
An admin view should be created to view the saved data.Create a employee database and create following api's
Add new employee Get employee by emp_id delete employee by id update employee salary -
How to validate unique attribute values of an object in respect to that object's other attributes?
I am making a school management system where each student takes 6 subjects. After trying to make dependent dropdown lists, I felt like it wasn't suited for what I was trying to achieve and I failed to implement them. I want to validate that each student's attributes concerning the subjects they're taking is unique, so that there aren't any subjects being taken twice (e.g. to prevent having Chemistry in science and Chemistry in science2) models.py from unittest.util import _MAX_LENGTH from django.db import models from django.utils.translation import gettext_lazy as _ from students.choices import * from django.core.exceptions import ValidationError # Create your models here. class Student(models.Model): def __init__(self, student_number, first_name, last_name, email, english, math, language, science, science2): self.student_number = student_number self.first_name = first_name self.last_name = last_name self.email = email self.english = english self.math = math self.language = language self.science = science self.science2 = science2 def __len__(self): return len(vars(self)) student_number = models.PositiveIntegerField() first_name = models.CharField(max_length=50) #Attribute containing student's first name, cannot exceed 50 characters last_name = models.CharField(max_length=50) #Attribute containing student's last name, cannot exceed 50 characters email = models.EmailField(max_length=100) #Attribute containing student's email, cannot exceed 100 characters #Subjects english = models.CharField(max_length=2, choices=English.choices, null=True, blank=False) math = models.CharField(max_length=2, choices=Math.choices, null=True, blank=False) language = models.CharField(max_length=1, … -
How can I update node version in docker container?
Now, I am developing some personal fullstack project using react, django, postgres and docker. I first use node version 8 but now I try to use node version 16. I tried like this. FROM buildpack-deps:bullseye ENV NODE_VERSION 16.18.0 RUN mkdir /code WORKDIR /code But when I check node version in docker shell, it still shows node 8.17.0 How can I fix that? I look forward to your great help. -
How to make REST API for booking 30 min slots. I have tried using django but it is confusing. any link would be helpful
REST API 30-minute timeslots available to schedule an appointment with a particular room. -
Django many to many field keeps adding every instance to itself
I have model "post" and model "profile". I need to add likes to the post, so I did "ForeignKey" at first, now I have ManyToMany relationship, but I keep seeing how every possible instance of "profile" is automatically being added to every instance of "post". Why is it happening? I didnt have problems like that in my previous projects. models.py for profile from django.db import models from django.conf import settings from django.contrib.auth.models import User class Profile(models.Model): """Fields that can be used to modify the profile page""" name = models.CharField(max_length=50, null=True, blank=True) bio = models.TextField(max_length=160, null=True, blank=True) profilePicture = models.ImageField(null=True, blank=True, upload_to='profiles/', default='default/default-pfp.jpg') """Technical fields unaccessable for users""" owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='account') following = models.ForeignKey("self", on_delete=models.DO_NOTHING, blank=True, null=True, unique=False) def __str__(self): str=self.owner.username str=str + "'s profile" return str model.py for pot from django.db import models from django.conf import settings from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=360) body = models.TextField() image = models.ImageField(null=True, blank=True) likes = models.ManyToManyField(User, related_name="blog_posts") author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): str=self.author.username str= self.date.strftime("%d/%m %H:%M ") + str + "'s post" return str def date_posted(self): str = self.date.strftime('%H:%M %d/%m/%y') return str [![Admin panel][1]][1] [1]: https://i.stack.imgur.com/rwgBP.png -
How to set a field different from id as primary key in django rest model
I am new to django_rest framework and I am having a problem with setting another field as primary key and then use that field as foreign key in another model. These are my models: class Test(models.Model): test_id = models.CharField(max_length=50, default="A10", primary_key=True) issue_date = models.DateField() total_amount = models.FloatField(max_length=50, default=1.0) class AnotherModel(models.Model): test_identifier = models.ForeignKey(Test, on_delete=models.CASCADE) #The identifier refered_date = models.DateField(auto_now_add=True, blank=True) But when I try to create an AnotherModel in admin page it shows this error: IntegrityError at /admin/api/anothertest/add/ FOREIGN KEY constraint failed My question is how can I make the test_id primary key and use it as foreign in second model? -
Django-Extra-Views: Inlines child model gets author none. How do I set it the same as the parent?
I have been spinning my wheels on this issue for a day or two. I have django web application that has 3 models users/models.py: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User # Create your models here. class ExtendedUser(models.Model): user=models.OneToOneField(User,null=True, on_delete=models.CASCADE) def full_name(self): return (self.user.get_full_name()) def __str__(self): return self.user.get_full_name() @receiver(post_save, sender=User) def create_or_update_user_extendeduser(sender, instance, created, **kwargs): if created: ExtendedUser.objects.create(user=instance) instance.extendeduser.save() playground/models.py: class Customer(models.Model): def __str__(self): return self.Customer_Name Customer_Name = models.CharField(max_length=100) SFDC_Customer_Record_Number = models.IntegerField(default='') Zone = models.CharField(max_length=50, default='') Government = models.BooleanField(default=False) date_posted = models.DateTimeField(default=timezone.now) customerauthor = models.ForeignKey(ExtendedUser, on_delete=models.DO_NOTHING,default=ExtendedUser) def get_absolute_url(self): return reverse('playground-home') class Vue_Quote(models.Model): def __str__(self): return self.Quote_Name Quote_Name = models.CharField(max_length=100) SFDC_Golden_Opp_ID = models.IntegerField() Vue_System_Count = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(ExtendedUser, on_delete=models.DO_NOTHING,default=ExtendedUser,blank=True,null=True) Quote_Type = models.CharField(max_length=100) Customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, default='') def get_absolute_url(self): return reverse('quote-detail',kwargs={'pk': self.pk}) I am using the 3rd party application django-extra-views to create a single form which allows a user to create a customer and quote at the same time. Views.py: class QuoteInline(InlineFormSetFactory): model = Vue_Quote fields = ['Quote_Name','SFDC_Golden_Opp_ID','Vue_System_Count','Quote_Type',] factory_kwargs = {'extra':1} class CreateQuoteInlinesView(CreateWithInlinesView): model = Customer inlines = [QuoteInline] fields = ['Customer_Name','SFDC_Customer_Record_Number','Zone','Government'] template_name= 'quote_and_customer.html' def forms_valid(self, form, inlines): form.instance.customerauthor = ExtendedUser.objects.get(user=self.request.user) return super().forms_valid(form,inlines) All of this is working … -
When to use savepoint = False in django transactions?
I can use inner atomic blocks as savepoints and catch inner savepoint errors. This way, we proceed within the atomic outer scope, just rolling back the inner atomic block, as explained in this question, but there is this argument savepoint=False that I don't see any use case for. In the docs: You can disable the creation of savepoints for inner blocks by setting the savepoint argument to False. If an exception occurs, Django will perform the rollback when exiting the first parent block with a savepoint if there is one, and the outermost block otherwise. Atomicity is still guaranteed by the outer transaction. This option should only be used if the overhead of savepoints is noticeable. It has the drawback of breaking the error handling described above. If I understand correctly, it will just change the fact that even catching an error from the inner block, the outer scope will still rollback. Is it correct? -
Serializer user "Invalid data. Expected a dictionary, but got User"
I am trying to display the fields of my user model but I always get that my serializer is not valid { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] } this is my model from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin class UserManager(BaseUserManager): def _create_user(self, username, password, is_staff, is_superuser, **extra_fields): user = self.model( username=username, is_staff=is_staff, is_superuser=is_superuser, **extra_fields ) user.set_password(password) user.save(using=self.db) return user def create_user(self, username, password=None, **extra_fields): return self._create_user(username, password, False, False, **extra_fields) def create_superuser(self, username, password=None, **extra_fields): return self._create_user(username, password, True, True, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) email = models.EmailField( max_length=255, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) age = models.PositiveIntegerField() is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def __str__(self): return f"{self.id} {self.name} {self.username} {self.age}" this is my serializer class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'email', 'username', 'name', 'age'] this is my view class UserUpdateApiView(APIView): def get(self, request, pk): try: queryset = User.objects.get(pk=pk) serializer = UserUpdateSerializer(data=queryset) if serializer.is_valid(raise_exception=True): return Response(data=serializer.data) except User.DoesNotExist: return Response(data={"error": "User no found"}, status=status.HTTP_404_NOT_FOUND) -
How can i access the count of a field in Django model?
I want to display the total revenue which equals total price, and total price is a field in the appointments model i want the count of that specific field so i can display it in the html. HELP! The Appointment model -
Insert an HTML icon within a Javascript new div
In this Django project, there is a Javascript function creating a new div in which we display some data. for (var i = 0; i < files.length; i++) { var newDiv = document.createElement('div'); newDiv.setAttribute("class","files_div"); //Call the helper function to check if it's a PDF newDiv.setAttribute("onclick","check_files(this)") console.log(files[i]) //Print the files newDiv.innerHTML = files[i]; divParent.appendChild(newDiv); } I need to add icons next to this data. For example, a pdf icon if it's a pdf file. How do you add icons in Javascript once a new div is created? -
Mock Chained DB query in Django unit test
I have a function that allows users to create a new entry in DB. But before that, I had a check if the user's existing records are less than the permissible range. Below is the function implementation def is_allowed_to_create(permissible_range): count = MyModel.objects.filter(query)[:permissible_range].count() return not count >= permissible_range Inside the test file, I am doing @mock.patch('MyApp.models.MyModel.objects') def test_is_allowed_to_create(self, mock_qs, *args, **kwargs): mock_qs.filter.return_value = mock_qs mock_qs.count.return_value = 10 self.assertTrue(is_allowed_to_create(5)) And the error I am getting is TypeError: '>=' not supported between instances of 'MagicMock' and 'int'. So what I understood from the error is, my code is not setting the proper return value for the entire DB query ie MyModel.objects.filter(query)[:permissible_range].count() . How can I set mock value for MyModel.objects.filter(query)[:permissible_range].count() as an integer. Thanks! -
Django - Aggregate into array
I have the a django model with the below data: Name Value A 1 B 2 B 4 C 7 C 5 I would like to use an aggregate my table so that I can get my data in the below format: Name Value A 1 B [2,4] C [7,5] How do I do this with Django. I'm thinking this may be the answer but Django doesn't seem to have ArrayAgg. This looks to be a Django Postgres function Test_Model.objects.annotate(dname=ArrayAgg('name')).values() Do you know how I can achieve this using native Django functions and solutions? Thank you! -
Django CharField with dynamic default value
I want to add a new field to a PostgreSQL database. It's a not null and unique CharField, like dyn = models.CharField(max_length=50, null=False, unique=True) The database already has relevant records, so it's not an option to delete the database reset the migrations wipe the data set a default static value. How to proceed?