Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest-Django does not specifically support Django’s multi-db and fails Database access not allowed
I was trying to run the testing with multi-db setup with the unmanaged (read-only) models. when I ran test the import functionality in the serailizers.py is failing and test database is not accessible. settings.py if 'test' in sys.argv or 'test_coverage' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', }, 'test_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } INSTALLED_APPS += ['test'] pytest.ini [pytest] DJANGO_SETTINGS_MODULE=apps.settings models.py from django.db import models class TestModelA(models.Model): testid = models.CharField(max_length=200) class Meta: managed = False db_table = 'TestD' serializers.py from rest_framework import serializers from apps.services import get_testid class SearchSerializer(serializers.Serializer): application_names = serializers.MultipleChoiceField( choices=get_testid(), required=False, style={'base_template': 'select_multiple.html'} ) services.py from apps.models import TestModelA def get_testid(): return TestModelA.objects.values_list('testid ', flat=True) tests.py import pytest from django.test import RequestFactory, TestCase from appsviews import ( details ) class MyTestCase(TestCase): def setUp(self): self.request = RequestFactory().get('/details/') @pytest.mark.django_db def test_my_function(self): response = details(self.request) self.assertEqual(response.status_code, 200) Error apps/tests/tests.py:4: in <module> from apps.views import ( <frozen importlib._bootstrap>:971: in _find_and_load??? <frozen importlib._bootstrap>:955: in _find_and_load_unlocked ??? <frozen importlib._bootstrap>:665: in _load_unlocked ??? /tmp/lib/python3.6/site-packages/_pytest/assertion/rewrite.py:149: in exec_module exec(co, module.__dict__) apps/views.py:6: in <module> from apps.serializers import ( <frozen importlib._bootstrap>:971: in _find_and_load ??? <frozen importlib._bootstrap>:955: in _find_and_load_unlocked ??? <frozen importlib._bootstrap>:665: in _load_unlocked ??? /tmp/lib/python3.6/site-packages/_pytest/assertion/rewrite.py:149: in exec_module exec(co, module.__dict__) apps/serializers.py:9: in <module> … -
Django API - Chart.js
Im having difficulties using json data from a model in the template. I set the api endpoint, but the data from the model does not come through. views.py class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self,request,format=None): mobilen = Mobiles.objects.all() serializer = DeviceSerializer(mobilen,many=True) labels = ['Jan','Feb','March','Jan','Feb','March','Jan','Feb','March'] out = serializer.data data = { "labels":labels, "default":out, } return Response(data) index.html {% block jquery %} var endpoint = '/api/chart/data/' var defaultData = [] var labels = [] $.ajax({ method: 'GET', url: endpoint, success: function(data){ labels = data.labels defaultData = data.default setChart() }, error:function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: '#', data: defaultData, }] } }) } {% endblock %} I get the data from the labels, but no data from the model in the chart. Thank you for any help -
How to link a profile to a newly created user using Django
Just finished a website using Django and i got stuck after creating a user or superuser. For some reason the same code i used before does not work anymore, and now whenever i create a new user it is saved (because i cant create another one with the same name) but not a profile for it. So now, after the registration form, the user should be redirected to the profile page which brings back an error. If i try to restart the server and login again, same error appears. Here is my signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() and models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) TypeError at /register/ save() got an unexpected keyword argument 'force_insert' -
validate_email python library working on local machine but not on aws elasticbean
validate_email is a python library to verify if an email exists or not.I have been using it in my local machine for a long time but when I made a web app using django,and hosted it on aws elasticbean it is not able to validate and always returns None.code is: from validate_email import validate_email choice="someoneeg@somedomain.com" is_valid = validate_email(choice,verify=True) I suspect if it is problem of some port or some firewall issue ,I have tried adding http listener at port 25 but still it didn't work. I also tried directly using the validate.py file of the developer which is available on github ,still results are same (I have validate_email and Py3DNS installed as required) -
How use class-based views inheritance to override to parent class?
In my ShowChart has model called Electronic(Electronic.objects.values..etc) , in my inheritance class(ChartElectrical) it need to changed to to Electrical (Electronic.objects.values..etc), here i just pass it. I don't know how to do it class ShowChart(View): def get(self, request): my_count = Electronic.objects.values('allocated_time')\ .annotate(complete=Count('allocated_time', filter=Q(batch_18=True)), not_complete=Count('allocated_time', filter=Q(batch_18=False)), complete_1=Count('allocated_time', filter=Q(batch_19=True)), not_complete_1=Count('allocated_time', filter=Q(batch_19=False)), complete_2=Count('allocated_time', filter=Q(batch_20=True)), not_complete_2=Count('allocated_time', filter=Q(batch_20=False)), complete_3=Count('allocated_time', filter=Q(batch_21=True)), not_complete_3=Count('allocated_time', filter=Q(batch_21=False))) class ChartElectrical(ShowChart): pass -
How to use for loop tag inside chart.js template
Hello guys i am having trouble using for loop in chart.js template i do not know how to use for loop tag inside chart.js template in order to get some data dynamically i am unable to find complete tutorial of chart.js and django kindly help me please. template var endpoint = '/api/chart/data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(i){ labels = i.newlabels defaultData = i.newdata var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of Votes', data: defaultData, backgroundColor: "#4e73df", hoverBackgroundColor: "#2e59d9", borderColor: "#4e73df" borderWidth: 1 }] }, }); }, error: function(error_data){ console.log("error") console.log(error_data) } }) views.py class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): qs_count = User.objects.all().count() av = Add.objects.aggregate( bud=Sum('budget'), exp=Sum('expense'), budexp=Sum('budget')-Sum('expense')) # I WANT TO DISPLAY THIS DATA labels = ["Black", "Blue", "Yellow", "Green", "Purple", "Orange"] default_items = [qs_count, 23, 2, 3, 12, 2] data = { "newlabels": labels, "newdata": default_items, } return Response(data) -
How To Get URL Parameters in django mako template?
I have url like this, blablabla.com/home?public=true how can I get the value public in django mako template? I previously using request.path but it's just show '/home' as a string Thank you for your answer -
how to set customize delimiter in vue-cli 3?
I'm using django with vue-cli 3 and I want to access the django data in vue template but there is a conflict with the syntax of data accessing i.e. delimiter in case of vue. Now I want to resolve this issue but the delimiter option is not working or I don't know where or how to add this command. I tried to add this to the main.js file in the src directory but it did not work out. Please suggest me if you know the solution or have any solution. new Vue({ router, store, vuetify, delimiters: ['[[',']]'], render: h => h(App) }).$mount('#app') Thank you. -
How can I use TTL to prevent a message backlog when using Firebase Cloud Messaging with Django-Push-Notifications?
I am working with Firebase Cloud Messaging in Django using django-push-notifications to deliver push notifications to our users via desktop notifications. After a browser is fully closed (such as when the the computer is turned off), our users receive a backlog of all notifications previously sent next time they boot up. While there are situations where a user would want to receive the entire backlog of messages, this is not one of them. It seems the answer is to set TTL=0, as per this section of the FCM documentation, but my attempts are not resulting in the desired behavior. Please help me better understand TTL in this context. If TTL is the right way to go, what is the proper way to format TTL in send_message() using django-push-notifications so that messages will not accumulate if not immediately delivered? Here is what I have attempted: devices.send_message( body, TTL=0, time_to_live=0, link='blah', extra={'title': 'blah blah', 'icon': '/foo/bar.png'} ) -
Optimize the filtering of Queryset results in Django
I'm overriding Django Admin's list_filter (to customize the filter that shows on the right side on the django admin UI for a listview). The following code works, but isn't optimized: it increases SQL queries by "number of product categories". (The parts to focus on, in the following code sample are, qs.values_list('product_category', flat=True) which only returns an id (int), so I've to use ProductCategory.objects.get(id=i).) Wondering if this can be simplified? from django.utils.translation import ugettext_lazy as _ from django.contrib.admin import SimpleListFilter from product_category.model import ProductCategory class ProductCategoryFilter(SimpleListFilter): title = _('ProductCategory') parameter_name = 'product_category' def lookups(self, request, model_admin): qs = model_admin.get_queryset(request) ordered_filter_obj_list = [] # TODO: Works, but increases SQL queries by "number of product categories" for i in qs.values_list('product_category', flat=True).distinct().order_by('product_category'): cat = ProductCategory.objects.get(id=i) ordered_filter_obj_list.append((i, cat)) return ordered_filter_obj_list def queryset(self, request, queryset): if self.value(): return queryset.filter(product_category__exact=self.value()) # Above filter is then used in the admin class ItemAdmin(admin.ModelAdmin): list_filter = ( ProductCategoryFilter, ) -
It is normal django_redis generate this kind of session key
I'm new to django_redis lib. I'm using this confs for session store with redis: ... CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, "KEY_PREFIX": "" } } SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' SESSION_CACHE_ALIAS = "default" ... Everything seems to work properly. But, when i check the key for a session on the database (default sqlite) and then compare that key value with the redis db in redis-cli, the session key are diferent. In the redis-cli version the session key has a prefix, even when I set no prefix. DB (sqlite) Version of Session Key skxn0oqp3goeipt6hnwvpeyp83hhoao0" redis-cli version of the key 127.0.0.1:6379[1]> keys * 1) ":1:django.contrib.sessions.cached_dbskxn0oqp3goeipt6hnwvpeyp83hhoao0" 127.0.0.1:6379[1]> This is normal ? -
django.db.utils.OperationalError: (1054, "Unknown column 'commons_smsmessages.sent_date' in 'field list'")
I'm using mysql as a db and I'm getting a django.db.utils.OperationalError: (1054, "Unknown column 'commons_smsmessages.sent_date' in 'field list'") when I add a field to the a pre-existing model. How do I fix it? I tried python manage.py makemigrations and I've also tried deleting all the migration files and running python manage.py makemigrations but it doesn't seem to work. This is the model I'm trying to update/add a field to: class SMSMessages(models.Model): sms_number_to = models.CharField(max_length=14) sms_content = models.CharField(max_length=160) sender_company = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="company_that_sent", limit_choices_to=1) sent_date = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "SMSMessages" def __str__(self): return self.sender_company The field I'm trying to add to the model is sent_date. But whenever I run python manage.py makemigrations I get the error Traceback (most recent call last): File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/MySQLdb/connections.py", line 226, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'commons_smsmessages.sent_date' in 'field list'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in … -
Azure Docker Django sqlite3 not deploying
I have spent an entire day trying to deploy a simple Django app to Azure with a docker container following this links advice. Dockerfile: # My Site # Version: 1.0 FROM python:3.7.2 # Install Python and Package Libraries RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ default-libmysqlclient-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools \ vim # Project Files and Settings RUN mkdir -p myproject WORKDIR /myproject COPY requirements.txt manage.py . ./ RUN pip install -r requirements.txt # Server EXPOSE 8000 STOPSIGNAL SIGINT ENTRYPOINT ["python", "manage.py"] CMD ["runserver", "0.0.0.0:8000"] docker-compose.yml version: "2" services: django: container_name: django_server build: context: . dockerfile: Dockerfile image: johnmweisz/education_app:latest stdin_open: true tty: true volumes: - .:/myproject ports: - "8000:8000" using docker-compose build/run locally works perfectly fine but when deploying the app from https://cloud.docker.com/repository/docker/johnmweisz/education_app to Azure it will not start and says that it cannot find manage.py. I keep going in circles trying to find instructions that work. Anyone with advice please help. -
Django get related foreignkey count (Distinct)
i want to get count of related foreignkey values like this; Assume that, the value table of this GAME STATUS GAME1 FINAL GAME2 FINAL GAME3 PLAYOFF GAME4 FINAL I want to show how many different situations (the result from the table above should be 2) models.py class Game(models.Model): gamestatus = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True) class Status(models.Model): name... -
Facebook: Redirect URI is not whitelisted in the app’s Client OAuth Settings
I realize this is a common problem, but am unable to find an up-to-date solution for this problem. Using social-auth-app-django to login users based on their social accounts. Currently I am focusing on Facebook, but am getting redirect URI errors for Instagram & LinkedIn as well. I am aware of current solutions and have tried the following (to name a few): 1. https://github.com/python-social-auth/social-app-django/issues/130 2. https://help.sharetribe.com/en/articles/1317674-how-to-solve-the-url-blocked-this-redirect-failed-because-facebook-login-error 3. https://github.com/python-social-auth/social-app-django/issues/152 4. python-social-auth and facebook login: what is the whitelist redirect url to include in fb configuration? 5. Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." settings.py INTALLED_APPS = [ ... 'social_django', ... ] MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.linkedin.LinkedinOAuth2', 'social_core.backends.instagram.InstagramOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ] LOGIN_URL = 'login' LOGOUT_URL = 'logout' SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_FACEBOOK_KEY = '*****************' SOCIAL_AUTH_FACEBOOK_SECRET = '************************' urls.py urlpatterns = [ ... path('login/', login_page, name="login"), path('social-auth/', include('social_django.urls', namespace="social")) ] login.html .... <a href="{% url 'social:begin' 'facebook' %}">Facebook</a> <br> .... Facebook Developer App Domains: todayatmyinternship.com Site URL: https://www.todayatmyinternship.com/ Valid OAuth Redirect … -
How to solve TypeError: create_superuser() got an unexpected keyword argument 'paid' in django
I am implementing custom user model extending AbstractBaseUser. Here is my account/models.py file. from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email, password. """ user = self.create_user( email, password=password ) user.paid = True user.is_superuser = True user.is_admin = True user.is_staff = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) paid = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) list_filter = () # Con USERNAME_FIELD = "email" REQUIRED_FIELDS = ("paid",) objects = MyUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin But I am getting the error while creating super user with the command python manage.py runserver This is what I got from the terminal : Email: i@j.com Paid: True Password: Password (again): Traceback (most recent call last): File … -
Django search model by dictionary (also include between a range)
Hello i'm having trouble trying to figure out how to handle this problem. I have a dict like so(the data key can be anything, but value has 3 types of a string, int or a dictionary with min and max values): { "city":5, "size":{ "max":78693, "min":11202 }, "type":"rent", "ward":229, "price":{ "max":43660474485, "min":7660026858 }, "street":1853, "district":20, "frontend":{ "max":90, "min":18 }, "direction":"ne" } Right now what i'm trying to do is to search a model using filter following the values of the above dictionary, The problem is i don't know how to handle ,if a key has a min and max then i have to find between it's range in the filter. I know that you can search by dict with the following : models.objects.filter(**my_dict) But how do i handle special condiation like min and max range in the filter ? I'm looking to output like this(the field name follow the key of the dictionary): models.objects.filter(city=5, size__range(min, max), type="rent",... other keys and values) Thank for reading -
Suggestion on database schema
I need to creat a database setup where in there are main three roles and use rest framework 1. Data entry : will do data entry and send to reviewer. Entry will be logged. 2. Reviewer: will review data, if any error is found send it back to data entry. When data entry is corrected, raise an ok flag. 3. Approver : will approve data after ok flag by reviewer. Confused about how to set up django model, serializer and how to log all these back and forth data between reviewer and data entry. I can do that on Access/visual basic but I am just starting to use django. Any suggestion please ? -
How to correctly perform django queries of ManyToMAny fields
I am working on an IMDB Clone project for the sake of learning. It has two important models: Movie and Celebrity. Movie model had three MTM fields all related with Celebrity model. class Movie(models.Model): # .. unrelated fields deleted for code brevity .. directors = models.ManyToManyField(celeb_models.Celebrity, related_name='movies_as_director', limit_choices_to=Q(duties__name__icontains='Director')) writers = models.ManyToManyField(to=celeb_models.Celebrity, related_name='movies_as_writer', limit_choices_to=Q(duties__name__icontains='Writer')) casts = models.ManyToManyField(to=celeb_models.Celebrity, through='MovieCast') I would like to delete all three fields and add only one MTM field. class Movie(models.Model): # one 'crews' field takes the place of three fields ('directors', 'writers', 'casts') # but it shows bad query performance. crews = models.ManyToManyField(celeb_models.Celebrity, through='MovieCrew', related_name='movies') And created an intermediate model which has some methods and a custom manager (which should do the magic). class MovieCrewManager(models.Manager): def get_queryset(self): return super().get_queryset() def get_directors(self): qs = self.get_queryset() return qs.filter(duty__name__icontains='Director').select_related('crew') def get_writers(self): qs = self.get_queryset() return qs.filter(duty__name__icontains='Writer').select_related('crew') def get_casts(self): qs = self.get_queryset() return qs.filter(duty__name__icontains='Cast').select_related('crew') class MovieCrew(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='movie_crews') #Movie Model duty = models.ForeignKey(celeb_models.Duty, default=1, on_delete=models.CASCADE) crew = models.ForeignKey(celeb_models.Celebrity, on_delete=models.CASCADE) # Celebrity Model role = models.CharField(max_length=75, default='', blank=True, help_text='e.g. short story, scrrenplay for writer, voice for cast') screen_name = models.CharField(max_length=75, default='', blank=True, help_text="crew's name on movie") objects = MovieCrewManager() def clean(self, *args, **kwargs): if not self.duty in self.crew.duties.all(): raise … -
How to solve error during follow standard output of a systemd unit?
I try to enable all systemd units and check systemd unit status but it shows some error with exit code and spawning. Step 1: To enable systemd sudo systemctl enable rt3-django-server.service Step 2: To check systemd unit status sudo systemctl status rt3-django-server.service Step 3: To follow the standard output of a systemd unit journalctl -fu rt3-django-server.service So when I run this line of command, I got this error. Please look at the picture. How to solve this problem? -
Django 'ifequal' with string comparisons
I currently am trying to compare two strings with an ifequal tag in Django. The current issue is that although the two strings are equal, Django does not run everything inside the if statement. html {% for group in groups %} <h1 class="inverted-popout">{{ group.name }}</h2> <div class="sheets"> {% for sheet in sheets %} {% ifequal sheet.sheetGroupValue group.sheetGroupName %} <!-- This is the issue --> <div class="sheet popout"> <h2><a href="{% url 'sheets:detail' slug='sheet.slug' slug=sheet.slug %}"> {{ sheet.name }} {{ sheet.hitPoints }} / {{ sheet.maxHitPoints }} </a></h2> <h3>{{ sheet.sheetGroupValue }}</h3> <p><i>Lvl {{ sheet.level }} ({{ sheet.xp }})</i></p> <p>{{ sheet.Class }}</p> <p>{{ sheet.background }}</p> <p>{{ sheet.race }}</p> </div> {% endifequal %} {% endfor %} </div> {% endfor %} views.py def sheetList(request): sheets = Sheet.objects.all().order_by('name') groups = SheetGroup.objects.all().order_by('name') return render(request, 'sheets/sheetList.html', { 'sheets': sheets, 'groups': groups }) models.py class SheetGroup(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name def sheetGroupName(self): return str(self.name) class Sheet(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100) sheetGroup = models.ManyToManyField(SheetGroup) slug = models.SlugField(default="") # there's a bunch of fields but they do not contribute to the error def __str__(self): return self.name def sheetGroupValue(self): groups = '' for group in self.sheetGroup.all(): groups += group.name + " " return groups Here … -
Django Serializer
I have a model with name,age,and a JSONField called nestedobject which holds a json string which holds a scheme like so {color="red",shape=[1,2,3,4]} a standard serializer would do something like this class MyRecordSerializer(serializers.ModelSerializer): class Meta: model = MyRecord fields = ('name','age','nestedobject') What I am after is class MyRecordSerializer(serializers.ModelSerializer): class Meta: model = MyRecord fields = ('name','age','shape') where shape would be that field with in that JSONField. So i would get something like {name="mike",age=10,shape=[1,2,3,4]} I have tried something like this class MyRecordSerializer(serializers.ModelSerializer): shape = serializers.SerializerMethodField('nestedobject')['shape'] class Meta: model = MyRecord fields = ('name','age','shape') Is this even doable ? Any help would be appreciated -
I want to push a Python app to Heroku on Windows 10, but i get "error: command 'gcc' failed with exit status 1"
I enter git push heroku master into the command prompt and all goes well for a while then... WARNING: The Python installation you are using does not appear to have been installed with a shared library, or in the case of MacOS X, as a framework. Where these are not present, the compilation of mod_wsgi may fail, or if it does succeed, will result in extra memory being used by all processes at run time as a result of the static library needing to be loaded in its entirety to every process. It is highly recommended that you reinstall the Python installation being used from source code, supplying the '--enable-shared' option to the 'configure' script when configuring the source code prior to building and installing it. then... gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tmp/pip-build-oxraezk2/mod-wsgi/src/packages/apache/include -I/app/.heroku/python/include/python3.7m -c src/server/mod_wsgi.c -o build/temp.linux-x86_64-3.7/src/server/mod_wsgi.o -I/tmp/pip-build-oxraezk2/mod-wsgi/src/packages/apache/include -I. -I/tmp/pip-build-oxraezk2/mod-wsgi/src/packages/apr/include/apr-1 -I/tmp/pip-build-oxraezk2/mod-wsgi/src/packages/apr-util/include/apr-1 -DLINUX -D_REENTRANT -D_GNU_SOURCE -g -O2 -pthread src/server/mod_wsgi.c: In function ‘wsgi_socket_sendv’: src/server/mod_wsgi.c:10966:44: warning: signed and unsigned type in conditional expression [-Wsign-compare] (nvec < iov_max ? nvec : (int)iov_max)); ^ src/server/mod_wsgi.c: In function ‘wsgi_scan_headers’: src/server/mod_wsgi.c:11125:30: warning: signed and unsigned type in conditional expression [-Wsign-compare] buflen = buffer ? buflen : sizeof(x); ^ gcc -pthread -Wno-unused-result … -
Filtering a Django queryset's related ManyToMany field when using values()
I'm working with a queryset which includes a ManyToMany field brand_groups. Users only have access to a subset of BrandGroups based on their organization. I'm trying to keep that ManyToMany field filtered down while still using values(), which is heavily integrated with the view. The simplified tables I'm working with: class BrandGroup(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=256) organization = models.ForeignKey( Organization, related_name="brand_groups", null=False ) class Fact(models.Model): id = models.CharField(max_length=256, primary_key=True) brand_groups = models.ManyToManyField(BrandGroup, blank=True) What's worked for me in the past is using Prefetch objects to handle this kind of limiting: qs = Fact.objects.prefetch_related( Prefetch("brand_groups", queryset=BrandGroup.objects.filter( organization_id=self.request.META["ORG_ID_HEADER"] ))) But I find that values() seems to ignore prefetches entirely. qs.values("brand_groups__name") The above always includes the full set of associated BrandGroup objects without the filter. I've tried adding to_attr='org_brand_groups' to the Prefetch, but then qs.values("org_brand_groups__name") complains that the field doesn't exist. I've also tried using an annotation to rename the prefetched field in a similar way. I don't get a complaint about the field not existing, but again values() returns the unfiltered queryset. The only way I've managed to accomplish this kind of filtering is by using a subquery: qs = Fact.objects.annotate( brand_group_name=Subquery( BrandGroup.objects.filter( organization_id=self.request.META["ORG_ID_HEADER"], Q(id=OuterRef("brand_groups__id"))).values( "name"[:1],output_field=CharField(),)) # Now it gives … -
How to add Custom Attributes to QuerySets in Django?
consider the following models: class User(AbstractUser): ... def messages(self): return Message.objects.filter(user=self).order_by('-created_on') def unread_count(self): return Message.objects.filter(user=self, read=False).count() class Message(models.Model): user = models.ForeignKey('account.User', related_name='message', on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now=True) data = models.TextField() read = models.BooleanField(default=False) objects = MessageManager() I call both the messages and unread_count methods from within a template, like this: <h1> You have {{ request.user.unread_message_count }} new messages </h1> <ul> {% for message in request.user.messages %} <li>{{ message.body }}</li> {% endfor %} </ul> My assumption is that this is a poor strategy, since splitting this into two separate methods requires 2 separate DB hits, so instead I want to override the QuerySet behavior for the Message model to include an unread_count: class MessageManager(models.Manager): def get_queryset(self): queryset = super().get_queryset() unread_count = queryset.filter(read=False).count() print(unread_count) # this works # these don't work queryset.unread_count = unread_count setattr(queryset, 'unread_count', unread_count) # return queryset The messages method works fine, and the print statement inside the manager executes, but if I try to access the unread_count I get an AttributeError: >>>user = User.objects.get(id=1) >>>messages = user.messages() 2 # this is from the print statement >>>messages.unread_count AttributeError: 'QuerySet' object has no attribute 'unread_count' Note that I want to do this without changing my view. What am I missing here?