Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Python 3.7 contextvars to pass state between Django views
I'm building a single database/shared schema multi-tenant application using Django 2.2 and Python 3.7. I'm attempting to use the new contextvars api to share the tenant state (an Organization) between views. I'm setting the state in a custom middleware like this: # tenant_middleware.py from organization.models import Organization import contextvars import tenant.models as tenant_model tenant = contextvars.ContextVar('tenant', default=None) class TenantMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user = request.user if user.is_authenticated: organization = Organization.objects.get(organizationuser__is_current_organization=True, organizationuser__user=user) tenant_object = tenant_model.Tenant.objects.get(organization=organization) tenant.set(tenant_object) return response I'm using this state by having my app's models inherit from a TenantAwareModel like this: # tenant_models.py from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from organization.models import Organization from tenant_middleware import tenant User = get_user_model() class TenantManager(models.Manager): def get_queryset(self, *args, **kwargs): tenant_object = tenant.get() if tenant_object: return super(TenantManager, self).get_queryset(*args, **kwargs).filter(tenant=tenant_object) else: return None @receiver(pre_save) def pre_save_callback(sender, instance, **kwargs): tenant_object = tenant.get() instance.tenant = tenant_object class Tenant(models.Model): organization = models.ForeignKey(Organization, null=False, on_delete=models.CASCADE) def __str__(self): return self.organization.name class TenantAwareModel(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_related', related_query_name='%(app_label)s_%(class)ss') objects = models.Manager() tenant_objects = TenantManager() class Meta: abstract = True In my application the business logic can then retrieve querysets using … -
How to fix this error: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}`
I have tried many things to solve my problem but I can't resolve it. I want to give user details when I give the token but I get this error: ##AssertionError at /api/token/get HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer.## Here the code in views.py class GetUserInfo(RetrieveUpdateAPIView): # permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) # serializer to handle turning our `User` object into something that # can be JSONified and sent to the client. return Response({"user": serializer.data}, status=status.HTTP_200_OK) Here the code in serializers.py lass UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'photo','director','manager','collaborator') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.save() profile.title = profile_data.get('title', profile.title) profile.dob = profile_data.get('dob', profile.dob) profile.address = profile_data.get('address', profile.address) profile.country = profile_data.get('country', profile.country) profile.city = profile_data.get('city', profile.city) profile.zip = profile_data.get('zip', profile.zip) profile.photo = profile_data.get('photo', profile.photo) director … -
Django migration error - ValueError: Invalid model reference 'apps.auth.Permission'
When I run python manage.py makemigrations users I get ValueError: Invalid model reference 'apps.auth.Permission'. String model references must be of the form 'app_label.ModelName'. my django file structure is . ├── README.md ├── __init__.py ├── apps │ └── users │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py ├── siteconfig │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── virtualenv some relevant variables from settings.py are settings.py PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps')) AUTH_USER_MODEL = 'users.CustomUser' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.users.apps.UsersConfig', 'rest_framework', ] users/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext as _ class CustomUser(AbstractUser): kindle_email_address = models.EmailField(_('kindle email address')) users/apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'apps.users' The full stack trace is: Traceback (most recent call last): File "/virtualenv/lib/python3.7/site-packages/django/db/models/utils.py", line 11, in make_model_tuple app_label, model_name = model.split(".") ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/virtualenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, … -
how to save object of PIL.Image.Image in django ImageField ? Django image processing?
I'm working on a Django project where users can upload images and it will be processed by a function made by a friend of mine. first, the function returned the image in the same path as the uploaded image with changing the filename and this wouldn't save the model field as the model has it's own file_path so I asked my friend to make the function return just an image and now the function returns object of PIL.Image.Image but whenever I call the save I get errors like object has no attribute '_committed' so when I searched, I stumbled across answers regarding BytesIO and saving it in in-memmory blob You can use a BytesIO to save the Pillow file to an in-memory blob. Then create a File object and pass that to your model instance ImageField's save method. but is this the best practice? and how can I imply this in my situation? btw the processing function is named main models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') class Processed(models.Model): uploaded_image = models.ForeignKey(UploadedImages,on_delete=models.CASCADE,related_name='processed') analysedimage = models.ImageField(upload_to=analyses_directory_path, verbose_name='analysed Image', blank=True) views.py def AnalysedDetails(request,pk=None): Uimage = get_object_or_404(models.UploadedImages,pk=pk) analysed = models.Processed(uploaded_image=Uimage,analysedimage=main(Uimage.pre_analysed.path)) analysed.analysedimage = main(Uimage.pre_analysed.path) analysed.analysedimage.save() return … -
Django AuthUserAdmin get_form override method being ignored
I want to override the get_form method for the AuthUserAdmin class with something like this (taken from https://realpython.com/manage-users-in-django-admin/): class AuthUserAdmin(admin.ModelAdmin): list_display = ('id', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', 'is_active', 'last_login') def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser disabled_fields = set() # type: Set[str] if not is_superuser: disabled_fields |= { 'username', 'is_superuser', } for f in disabled_fields: if f in form.base_fields: form.base_fields[f].disabled = True return form However, the method is never called when the user opens the change form. -
Django: trigger SweetAlert2 in the redirect
I am new to JS, and I want to implement a dialog message with SweetAlert2 for 2 sec. A the moment I'm triggering the message with the submit button which is not great. I want to know how to trigger it after the redirection. views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return redirect('product_tree:index') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/change_password.html', { 'form': form }) change_password.html [...] <button type="submit" class="btn btn-success" id="ResetPassword">Save</button> [...] alerts.js $('#ResetPassword').click(function(){ Swal.fire({ position: 'top-end', type: 'success', text: 'New password saved!', showConfirmButton: false, timer: 2000 }) }); -
How can i add depth=1 to BaseSerializer
ModelSerializer have a depth in Meta class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None depth = 2 fields = '__all__' any alternative in BaseSerializer? -
Avoiding function calls in 'where' clause of sql queries generated by django
The Django generating sql queries with function calls in where clause like below, when using Django queries for search or any other purposes. SELECT COUNT(*) AS "_count" FROM "products_product" INNER JOIN "products_productmeta" ON ("products_product"."meta_id" = "products_productmeta"."id") WHERE ((NOT ("products_product"."archived" = true) AND "products_product"."owner_id" = 1281 AND UPPER(UNACCENT("products_product"."sku")::text) LIKE '%' || UPPER(REPLACE(REPLACE(REPLACE((UNACCENT('octavi')), '\', '\'), '%', '\%'), '', '_')) || '%') OR (NOT ("productsproduct"."archived" = true) AND "products_product"."owner_id" = 1281 AND UPPER(UNACCENT("products_productmeta"."name")::text) LIKE '%' || UPPER(REPLACE(REPLACE(REPLACE((UNACCENT('octavi')), '\', '\'), '%', '\%'), '', '_')) || '%') ) Response time is taking too long with these type of queries because of whole data sets are passing through the function calls. Is there any way to avoid those function calls such as UPPER, REPLACE etc... in where clause of sql generated by django? Is writing raw sql queries the only option? -
Django 2.2 upgrade - mongoengine query performance
We are trying to upgrade from Django 2.1.11 to 2.2.4. During the upgrade we noticed a significant performance drop relating to queries made through the mongoengine library (http://mongoengine.org/) We did some profiling with pyspy (https://github.com/benfred/py-spy) and noticed the control flow is significantly different and there are lots of extra function calls relating to pagination. I can't find anything in the release notes for Django 2.2 (https://docs.djangoproject.com/en/2.2/releases/2.2/) that suggests why we might be getting the problem. Any help is much appreciated. We have tried doing some profiling with pyspy and some other tools and we tried different minor versions but it seems to broken in all Django 2.2 versions. def get_context_data(self, **kwargs): ctx = super(BaseOverview, self).get_context_data(**kwargs) ctx['result_template_name'] = self.result_template_name ctx['action_form'] = self.action_form ctx['page_size_form'] = self.page_size_form ctx['submitted'] = self.submitted ctx['model'] = self.model ctx['paginate'] = self.paginate_by results = ctx[self.context_object_name] if not isinstance(results, list): # Need to evaluate the queryset, so attached data remains set results = results.select_related(max_depth=self.select_depth) self.attach(results, self.request.session['environment']) # assert len(results) <= self.paginate_by ctx[self.context_object_name] = results return ctx Where results is a mongoengine Document class instance pyspy output -
Installed Django and ran now it says command not found
I am new to python and Django I have installed Python 3.7 and Django on MacOS 10.14 followed online tutorials I created folder on Desktop called Development and in that i have test, polls folder. ran python manage.py runserver open browser 127.0.0.0:8000 it worked. Then I was trying sample project from Django website it did not work so next day I want to troubleshoot my code. I cd to development folder ran python manage.py runserver keep saying command not found. I could not find answers online. My question do i have to create virtualenv every time I want to open existing Django project? how do I open existing project please if you can give me step by step that would be great. -
Django skips domain name while appending urls
While using @user_passes_test(function, login_url) decorator on production server I found out login_url is not getting appended as host/mysitename/login_url but just like host/login_url. Though it worked just fine on my local PC. I found out that changing the login_url to /mysitename/login_url solves the problem, but is there an elegant solution how to avoid this? -
Ordering django Group model for all related objects
I'm trying to order the group objects alphabetically by name in all usages. So in every dropdown where the groups are displayed, they should be ordered by name. Right now the are "random" (in the order the were created). There are some third party models (django-cms: class AbstractPagePermission code) which are using the Group model from django.contrib.auth.models. I can't change their code, so I can't modify the form nor the models... I can code a GroupAdmin but this is only ordering the objects in the admin itself, not in other forms... Any ideas? I guess there is no easy/simpel and beautiful way to solve this. P.S. I hate this kind of SO questions myself... forgive me... there is no code to show... Help is appreciated! -
How to check an item in a tuple in a tuple with inconsistent items
I have a tuple that has some single items in it as well as some more 2 item tuples in it, and I need to be able to check the 2 item tuples for a specific match. I have tried specifying the 2 item tuple to avoid the problem, but I am using django and it is a fieldset field item and if I specify down to the 2 item tuple that I know the item I'm looking for is in, I can't perform the operation that the check is testing for. The django error that comes up is "cannot be specified for myModel model form as it is a non-editable field". I also don't think that I can do a nested for loop because not all items in the tuple are nested tuples. I've also tried to make a testing variable as a boolean of if the item is there or not, but then I get the error thrown when I try and do the if statement, even though it should be skipped due to the fact that the item is actually present in the list. I've looked at a lot of the answers here and on the web … -
In Django how do I call a function in the template
As you can see I am trying to create a function and use it in the template by calling it in the get_context_data But when I refresh the page, it gives me the error: name 'sidebar' is not defined. I think I might need to pass some variables into the sidebarFunction but I am not entirely sure. HTML: {% if user.is_staff %} {% for client in sidebar %} <li> <!-- <a href="{% url 'public:client_detail' client.client.pk %}"> --> <p class="client-title" onclick="subNavDropDown(this)">{{ client.client }}</p> <!-- </a> --> </li> <ul class="sub-nav" id="{{ client.client }}-subnav"> {% for project in client.projects %} <!-- Add a link to this --> <li class="sub-nav" id="project-dropdown-{{ project.pk }}"> {{ project }} </li> {% endfor %} </ul> {% endfor %} <br> {% else %} {% for project in sidebar %} <li> <a href="{% url 'public:client_detail' client.pk %}"> <p class="client-title"></p>{{ client }}</p> </a> </li> {% endfor %} {% endif %} Python: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) client = self.request.user.groups.all() context["project"] = Project.objects.filter(client=self.get_object()) context["projects"] = Project.objects.filter(client__in=client, active=True) context["sidebar"] = sidebar return context def sidebarFunction(self): if self.request.user.is_staff: sidebar = [] for client in Client.objects.all(): data = { "client": client, "projects": Project.objects.filter(client=client), } sidebar.append(data) else: sidebar = Project.objects.filter(client__in=client, active=True) -
how to count total student according to 'course' model in django
I am trying to count the number of the student according to CourseMasterModel. I did it in MySQL, but I want to in Django. select cn.course_name,count(st.id) from course_master cn,semister_master sem,division_master di,student_profile st where st.division_id = di.id and di.semister_id = sem.id and sem.course_id = cn.id GROUP BY cn.course_name; class CourseMasterModel(models.Model): course_name = models.CharField(max_length=20,unique=True) total_semister = mod`enter code here`els.SmallIntegerField() class Meta: db_table = "course_master" verbose_name_plural = 'Course (Department)' verbose_name = "Course" def __str__(self): return self.course_name class SemisterMasterModel(models.Model): semister = models.SmallIntegerField() total_div = models.SmallIntegerField() course = models.ForeignKey(CourseMasterModel,on_delete=models.PROTECT) class Meta: db_table = "Semister_master" verbose_name_plural = 'Semister' verbose_name = "semister" def __str__(self): return "%s - %d" %(self.course.course_name,self.semister) class DevisionMasterModel(models.Model): div_name = models.CharField(max_length=2) semister = models.ForeignKey(SemisterMasterModel,on_delete=models.CASCADE) class Meta: db_table = "division_master" verbose_name_plural = 'Division' verbose_name = "Division" def __str__(self): return "%s - %s - %s"%(self.semister.course.course_name,self.semister.semister,self.div_name) class StudentProfileModel(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile") division = models.ForeignKey('core.DevisionMasterModel',on_delete=models.CASCADE,verbose_name="Course / Semister / Division") roll_no = models.IntegerField() enrollment_no = models.IntegerField(unique=True, error_messages={'unique':"This enrollment number has already been registered."}) def __str__(self): return self.user.username class Meta: db_table = "Student_Profile" -
Django Channels (and other framework) session id/key uses
I would like to assign a meaningful value to self.group_name in a channels application and I would like this tied to the user session (i.e. data will go anywhere the same user is logged in). Is it safe to use the session ID (from self.scope['session'].session_key) as this identifier, provided this value never leaves the server? I want my channels connection lifetime to match that of my Django session, so this seems like the most straight forward approach and avoids cluttering up the session with other variables. The alternative would be to assign something like a uuid4 value to a new session variable. That would make it more difficult for me to leak a users session_key. -
Error importing "openwisp_utils.admin import ReadOnlyAdmin"
I am trying to implement django-freeradius, but I get the error cannot import name 'ReadOnlyAdmin', when I write the line * in urlspatters within urls.py of my project. I have tried to use the same configuration in https://github.com/openwisp/django-freeradius/blob/master/tests/urls.py, but it does not work. # myproject/urls.py from django.contrib import admin from django.urls import path, include from openwisp_utils.admin_theme.admin import admin, openwisp_admin openwisp_admin() admin.autodiscover() urlpatterns = [ url(r'^', include('django_freeradius.urls', namespace='freeradius')), #* This line path('admin/', admin.site.urls), ] I have installed: Python 3.6.8 Django 2.2.4 django-filter 2.1.0 django-freeradius 0.1a0 openwisp-utils 0.2.2 These are my apps in settings.py # myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_freeradius', 'django_filters', ] And, this is the complete error when I run python manage.py runserver () Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/mnt/c/Users/myuser/Documents/python/hotspot/env/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate … -
How can I exclude script tags and style tags from a TextField that will turn eventually to a plain html code
I need a way that removes Script tags and Style tags from a textarea since it runs when I post a post. When I post something as a Post-it should turn everything from HTML tags to plain text that HTML was applied on, therefore, script tags and style tags will be applied as well, which is quite unprofessional and risky. class Post(models.Model): user = models.ForeignKey(User, related_name = 'posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable = False) group = models.ForeignKey(Group, related_name='posts',on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('posts:single', kwargs = {'username': self.user.username,'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message'] I expect the output not to be applied or built, instead, I expect it to delete the , and show everything inside as plain text. -
How to serialize a dictionary containing lists with Django-Restframework?
I'm creating a REST-API for my Django-App. I have a function, that returns a list of dictionaries, that I would like to serialize and return with the rest-api. The list (nodes_of_graph) looks like this: [{'id': 50, position: {'x': 99.0, 'y': 234.0}, 'locked': True}, {'id': 62, position: {'x': 27.0, 'y': 162.0}, 'locked': True}, {'id': 64, position: {'x': 27.0, 'y': 162.0}, 'locked': True}] Since I'm a rookie to python, django and the Restframwork, I have no clue how to attempt this. Is anybody here, who knows how to tackle that? somehow all my attempts to serialize this list have failed. I've tried with class Graph_Node_Serializer(serializers.ListSerializer): class Nodes: fields = ( 'id', 'position' = ( 'x', 'y', ), 'locked', ) def nodes_for_graph(request, id): serializer = Graph_Node_Serializer(nodes_of_graph) return Response(serializer.data) The result I hope for is an response of the django-rest-framwork, containing the data in the list of dictionaries. -
How to display queryset list?
I am creating website for game tournaments. I have specialized queryset. I want to display on one page teams' names and their players. I tried to work with "get_queryset()" function but I don't understand what exactly. Probably there is mistake in template section. models.py from django.db import models class TestTeam(models.Model): name = models.CharField(max_length=30, default='Team') slug = models.SlugField(max_length=5) def __str__(self): return self.name class TestPlayer(models.Model): name = models.CharField(max_length=100, default='Player') nick = models.CharField(max_length=20, default='Nickname') team = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, default='Team') #photo = models.ImageField(upload_to='', null=True) No = 'N' Yes = 'Y' STANDIN_CHOICES = [ (Yes, 'Yes'), (No, 'No'), ] standin = models.CharField(max_length=5, choices=STANDIN_CHOICES, default=No) slug = models.SlugField(max_length=20, default=nick) def __str__(self): return self.name class TestMatch(models.Model): name = models.CharField(max_length=100, default='Match') leftTeam = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, related_name='+', default='Left Team') rightTeam = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, related_name='+', default='Right Team') slug = models.SlugField(default=str(name)) def __str__(self): return (str(self.leftTeam) +" - "+ str(self.rightTeam)) urls.py from . import views from django.urls import path urlpatterns = [ path('', views.TestView.as_view(), name='home'), path('<slug:slug>/', views.MatchView.as_view(), name='match'), ] views.py from django.views.generic import ListView, DetailView from . import models from django.shortcuts import get_list_or_404 class TestView(ListView): model = models.TestMatch template_name = 'home.html' class MatchView(DetailView): model = models.TestPlayer template_name = 'match.html' def get_queryset(self): queryset = super().get_queryset() if 'slug' in self.kwargs: team_slug = self.kwargs['slug'] TEAM … -
Bootstrap CDN not loading inside Django?
I am following this tutorial to learn Django : https://realpython.com/get-started-with-django-1/#why-you-should-learn-django All the steps were successful until the author started implementing Bootstrap CDN in his code: Django simply ignores it and doesn't show any different text fonts from the Bootstrap style. The section in the tutorial "Add Bootstrap to Your App" is the one I encountered a problem with and also later on "Projects App: Templates". I checked if all the code from the tutorial is correct in my project already. Do I need to install anything from Bootstrap? from the tutorial I understood I only needed to add the link. Thank you -
How can i get custom fields on ModelSerializer
I have a model class Teacher(models.Model): name = models.CharField(max_length=100) message = models.CharField(max_length=300) status = models.OneToOneField(Dictionary, on_delete=models.CASCADE) money = models.IntegerField(default=None, blank=True, null=True) My urls urlpatterns = [ path('get', views.GetViewSet.as_view({'get': 'list'})), ] My view class GetViewSet(viewsets.ModelViewSet): def get_serializer_class(self): GeneralSerializer.Meta.model = Teacher return GeneralSerializer def post(self, request): return self.select_api() def select_api(self): queryset = Teacher.objects.values("name","money").annotate(Count("money")) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) serializer class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None depth = 2 fields = '__all__' in this example in annotate func i have +1 field "money__count" but i can't display it cause my model have not a this field. How can i display it in api and i want a universal serializer (without adding static field to serializer cause it is universal serializer for all models) Please help me -
How to return each iteration using for loop in Django views
How to print iteration in template -
ArrayField In Django is giving error while doing migrations
I have added arrayfield to model in my application. Below is my model class employees(models.Model): firstName=models.CharField(max_length=10), lastName=models.CharField(max_length=10), tags_data = ArrayField(models.CharField(max_length=10, blank=True),size=8,default=list,) Below is my migrations file data. class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='employees', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tags_data', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, max_length=10), default=list, size=8)), ], ), ] when I am doing migrate I am getting the below error django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[8] NOT NULL)' at line 1") What is wrong with the syntax. Please help me where I am going wrong? -
After user login based on the user role page should redirect
Table called profile,in that table there is a field called designation,when user logins based on the designation the page should redirect.