Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
KeyError in ORM code when annotating using a Case and aggregating the annotation in a group by
We encountered this issue in a pretty complex project, but I've managed to reproduce it in a dummy project: This is django 1.11.7 on python3.6 and postgres10: models.py: from django.db import models class Thing(models.Model): multiplierA = models.IntegerField() multiplierB = models.IntegerField() class Data(models.Model): thing = models.ForeignKey('Thing') multiplier_choice = models.CharField(max_length=1, choices=(('A', 'use multiplier A'), ('B', 'use multiplier B'))) option = models.IntegerField(choices=((1, 'option 1'), (2, 'option 2'))) percentage = models.FloatField() tests.py: from django.db.models import Case, F, FloatField, IntegerField, Sum, When from django.test import TestCase from .models import Data, Thing class AnnotateTests(TestCase): def test_simple(self): thing = Thing.objects.create(multiplierA=2, multiplierB=3) Data.objects.create(thing=thing, multiplier_choice='A', option=1, percentage=0.2) Data.objects.create(thing=thing, multiplier_choice='A', option=2, percentage=0.3) Data.objects.create(thing=thing, multiplier_choice='A', option=3, percentage=0.1) Data.objects.create(thing=thing, multiplier_choice='B', option=1, percentage=0.1) Data.objects.create(thing=thing, multiplier_choice='B', option=2, percentage=0.4) Data.objects.create(thing=thing, multiplier_choice='B', option=3, percentage=0.5) whens = [ When(multiplier_choice='A', then=F('thing__multiplierA')), When(multiplier_choice='B', then=F('thing__multiplierB')) ] multiplier_case = Case(*whens, output_field=IntegerField(), default=0) qs = (Data.objects # select only certain options to sum up for each thing: .filter(thing=thing, option__in=[1, 2]) # select the correct multiplier .annotate(multiplier=multiplier_case) # group by thing => sum of percentage * multiplier .values('thing') .annotate(amount_sum=Sum(F('percentage') * F('multiplier'))) .values('amount_sum')) print(qs.values('thing__id', 'amount_sum')) Running this test will result in the following traceback: ====================================================================== ERROR: test_simple (annotate.tests.AnnotateTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/robin/src/ormweirdness/annotate/tests.py", line 34, in test_simple .annotate(amount_sum=Sum(F('percentage') * F('multiplier'))) File … -
How can I get the user data in serializer `create()` method?
How can I get the user data in serializer create() method? I tried to get the user data use self.request, but failed: class OrderCreateSerializer(ModelSerializer): class Meta: model = Order fields = ( "product_describe", "billing_type", "buytime", "count", "paytype", ) def create(self, validated_data): print(self.request.user.username) validated_data["order_num"] = generateOrderNum() return Order.objects.save() 'OrderCreateSerializer' object has no attribute 'request' -
Showing Many-To-Many in different model's form in Django?
Say I have three models, a Professor model, a Course model, and a Review model. The user is allowed to make a Review, which reviews a Professor that teaches a certain Course. I'm thinking of how to model the many to many relationship of Professor and Course, and how to reference that relationship in Review. My idea so far is to use models.ManyToMany to link Professor and Course. Models.py (Prof) class Prof(models.Model): first_name = models.CharField(max_length = 20, unique = False) last_name = models.CharField(max_length = 20, unique = False) def __str__ (self): return self.first_name + " " + self.last_name class Course(models.Model): name = models.CharField(max_length = 20, unique = True) prof = models.ManyToManyField(Prof) def __str__ (self): return self.name Models.py (Review) class Review(models.Model): message = models.TextField(max_length = 4000) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(null = True) rating = models.IntegerField( default = 5, validators = [MaxValueValidator(5), MinValueValidator(0)] ) prof = models.ForeignKey(Prof, related_name = 'reviews') course = models.ForeignKey(Course, related_name = 'reviews') user = models.ForeignKey(User, related_name = 'reviews') def __str__ (self): return self.message forms.py class ReviewForm(ModelForm): rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5})) class Meta: model = Review fields = ['message', 'rating', 'prof', 'course', 'user'] This is my code so far for … -
Perform lookup and update within a single Django query
I have two models: MetaModel and RelatedModel. I want to include the result of a RelatedModel lookup within a MetaModel query, and I'd like to do this within a single DB call. I've tried to define a 'subquery' QuerySet for use in the main query, but that hasn't worked - it's still making two queries to complete the operation. Note: I can't use a traditional ForeignKey relationship because the profile_id field is not unique. Uniqueness is a combination of profile_id and channel. This is an aggregation table and profile_id is not guaranteed to be unique across multiple third-party channels. Any suggestions? Models: class Channel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField( max_length=25, ) class MetaModel(models.Model): profile_id = fields.IntegerField() channel = fields.ForeignKey(Channel)) metadata = fields.TextField() class RelatedModel(models.Model): related_id = fields.IntegerField() profile_id = fields.IntegerField() channel = fields.ForeignKey(Channel)) Dummy data channel = Channel("Web site A") channel.save() sample_meta = MetaModel(profile_id=1234, channel=channel) sample_related = RelatedModel(profile_id=1234, related_id=5678, channel=channel) Query: # Create a queryset to filter down to the single record we need the `profile_id` for # I've limited to the only field we need via a `values` operation related_qs = RelatedAccount.objects.filter( related_id=5678, channel=channel ).values_list("profile_id", flat=True) # I'm doing an update_or_create as there is other data to store, … -
How to add model through UI?
I need to create an app that generates an admin panel. One of the concepts is for it to have an option to add models (which will be migrated to the database) and have a list of all models. The question is: is it even possible to add Models through UI? After a few days search, I'm starting to think that the only way is by going into the code. I can create forms for adding objects, but not models. Any ideas? -
Difference between two lists of django models objects
I have two data sources. One is a psql table (managed using Django models) and another is a CSV. I have to keep the table in sync with the csv. So, my current procedure is: Reading all the rows from the table and creating a set of tuples, calling it old_data Reading all the rows from the csv and creating another set of tuples, calling it new data. So, old_data - new_data gives me all the objects that have been deleted and updated. Similarly, new_data - old_data gives me all the objects that have been inserted and also updated. So, objects with primary key in both the differences are the ones which will be used for updated. Rest are deleted and inserted accordingly. Now, this is not a Django way of doing it. (I'm comparing the two sets of tuples, not the model objects itself) Can this be done by comparing the models somehow. -
django 1.7.1 python manage.py runserver
The following error is displayed when you run "python manage.py runserver" and go to the browser and type localhost:8000 Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/core/management/init.py", line 385, in execute_from_command_line utility.execute() File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/core/management/init.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **options.dict) File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute output = self.handle(*args, **options) File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 63, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/db/migrations/executor.py", line 17, in init self.loader = MigrationLoader(self.connection) File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/db/migrations/loader.py", line 48, in init self.build_graph() File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/db/migrations/loader.py", line 179, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()): File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/db/backends/init.py", line 165, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/home/ngn/Documents/django_projects/multipleenv/django171/lib/python3.4/site-packages/django/db/backends/dummy/base.py", line 18, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
Technology limitations for web application that scrapes web pages
I am starting the development of a web platform that provides automated tasks to users. I have no technology requirements, and I am tackling as to what should be the best choice regarding the technology and platform I will be implementing this in, as ultimately I am concern about the integration of the web application itself with the features or applications that allow me to do tasks on specific sites on behalf of users. I can do this with PHP + Laravel and use some external package such as Goutte for handling the scraping and interaction, I can rely on Selenium and interact with it through php or by calling selenium directly as long as I have the ability to execute applications using exec(), system() or something else. I can also go with Python + Django and use this as the scraper, or once again rely on some external application installed in the system such as Selenium, or go with something else. My main concern is limitation due to the chosen technology, as I will have to process output of the pages, and I don't really like system or exec in php and then trying to parse their output, and … -
Python Django - Stacking multiple URL parameters
I have a default layout for a list of objects in a template that will be under a URL like /default/. When a user clicks a filter button then the list of objects will be filtered down. Button 1 may have a link pointing to 'href="?d=not-default"', and Button 2 to 'href="?p=another-parameter"'. When clicking on Button 1, I go to the new URL. But, when I click on button 2 then it of course does not add the parameter to the new URL, but instead will go straight to '/default/?p=another-parameter'. Is there a way to 'stack' multiple parameters so that the objects on the page would be filtered so the URL will end up looking something like "/default/?d=not-default&p=another-parameter" regardless of the order that I click each of the different buttons in, and so each new filter clicked will be added to the URL parameters? Edit: I should mention that I am currently using the Django web framework for Python -
Django formset non_form_errors as i have more than 1000 forms in a formset
I have a formset which is a modelformset_factory.And when the formset validates it throws a non_form_error like "Please submit 1000 or fewer forms.".I have more than 2000 forms in the same formset. is it possible to validate the formset ?. And how to overcome the above issue? Please guide, Thanks -
SMTPServerDisconnected: Connection unexpectedly closed: timed out
After running the sentry on-premise docker container (version 8.20) and passing in the following eviromental variables: -e SENTRY_EMAIL_HOST="smtp.sendgrid.net" -e SENTRY_EMAIL_PORT=465 -e SENTRY_EMAIL_USE_TLS="True" -e SENTRY_EMAIL_USER="apikey" -e SENTRY_EMAIL_PASSWORD= '****' I am receiving the following: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/sentry/tasks/base.py", line 54, in _wrapped result = func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/sentry/tasks/email.py", line 76, in send_email send_messages([message]) File "/usr/local/lib/python2.7/site-packages/sentry/utils/email.py", line 415, in send_messages sent = connection.send_messages(messages) File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 87, in send_messages new_conn_created = self.open() File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 48, in open local_hostname=DNS_NAME.get_fqdn()) File "/usr/local/lib/python2.7/smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python2.7/smtplib.py", line 317, in connect (code, msg) = self.getreply() File "/usr/local/lib/python2.7/smtplib.py", line 365, in getreply + str(e)) SMTPServerDisconnected: Connection unexpectedly closed: timed out Any one have an idea what might be the cause? -
DJANGO_SETTINGS_MODULE envar not getting set
I am currently developing an application in Python 3.6 and Django 1.11, on the production server (Ubuntu 16.04) I am using Apache2. I am trying to use separated settings for production and development. Instead of a file, I have a settings directory with base setttings, and production and development settings file, which import the base settings and potentially override them. To let Django know which settings to use, I am setting the DJANGO_SETTINGS_MODULE to either prehranske_oznacbe.settings.development or prehranske_oznacbe.settings.production. This works fine for development. Concerning setting the envvars on the production server, I followed the answers to these two SO: Access Apache SetEnv variable from Django wsgi.py file, Django + mod_wsgi. Set OS environment variable from Apache's SetEnv. The problem is, when I try to acces my application, I get a 500 Internal Error. The apache error logs: mod_wsgi (pid=404): Target WSGI script '/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=404): Exception occurred processing WSGI script '/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py'. Traceback (most recent call last): File "/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py", line 25, in <module> application = WSGIEnvironment() File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 151, in __init__ self.load_middleware() File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 48, in load_middleware if settings.MIDDLEWARE is None: File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in … -
Django Rest Framework - Auto Filter Fields
I would like to made, all fields in models should be filter fields or i want to achieve by without using filter_fields = ('id', 'created',) in Views.. is their a way to achieve this using django - DRF (Django Rest Framework) is their any extension to do so? making field_fields automatically by existing fields? -
(UNIQUE constraint failed: auth_user.username) for user registration Django with Email confirmation
I need to register a user by sending an activation token to her Email address. I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register her using custom built-in functions register and activate. My code is as follows: forms.py class UserRegisterForm(forms.Form, UserCreationForm): username = forms.CharField(max_length=20) date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1))) email = forms.EmailField() def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username).exists(): raise forms.ValidationError('Username already exists') return username def clean_date_of_birth(self): ''' Only accept users aged 13 and above ''' userAge = 13 dob = self.cleaned_data.get('date_of_birth') today = date.today() if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day): raise forms.ValidationError('Users must be aged {} years old and above.'.format(userAge)) return dob def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('A user has already registered using this email') return email def clean_password2(self): ''' we must ensure that both passwords are identical ''' password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('Passwords must match') return password2 views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') new_user = User.objects.create(username=username, email=email, password=password) new_user = form.save(commit=False) #new_user.set_password(password) # hashes the password new_user.is_active = False new_user.save() current_site … -
wkhtmltopdf is not reading javascript (Django)
I am trying to convert my Html page in Django to PDF and using 'Wkhtmltopdf' to do so. Everything is working as planned but it is not reading my bar chart in javascript. I have used simple js but still while converting to pdf, the charts are not shown. I have used the following codes: response = PDFTemplateResponse(request=request, template=self.template, filename="hello.pdf", context=data, show_content_in_browser=False, cmd_options={'margin-top': 10, "zoom": 3, "viewport-size": "1366 x 513", 'javascript-delay': 1000, 'footer-center': '[page]/[topage]', "no-stop-slow-scripts": True}, ) return response The CSS are also loaded just fine. -
Trying to link social accounts with single user (trouble inheriting from DefaultSocialAccountAdapter)
I've followed through basic allauth installation docs so I have a basic Google, Facebook and username/password system working fine. What I'd like to do now is to automatically associate social accounts with an existing username + password account when a user attempts to login with the social account link. There are many posts about this topic already, such as this and this but I'm stuck quite early on in the process. As per those other posts, I've created a class that overrides DefaultSocialAccountAdapter and called it SocialAccountAdapter. I've then added it as a configuration setting to my settings.py file (where my_app is the name of my app inside INSTALLED_APPS): ACCOUNT_ADAPTER = 'my_app.adapter.SocialAccountAdapter' The class in question looks like the following. from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class SocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): pass ...in other words, it should do absolutely nothing more than the parent class. The problem is I get errors on the /accounts/login/ page. File ".../site-packages/allauth/account/utils.py", line 41, in get_next_redirect_url if not get_adapter(request).is_safe_url(redirect_to): AttributeError: 'SocialAccountAdapter' object has no attribute 'is_safe_url' So to 'fix' that, I added the following to the SocialAccountAdapter class: def is_safe_url(self, url): from django.utils.http import is_safe_url return is_safe_url(url) ...but upon using the default form to enter in … -
Django ORM: Select query when i instantiate a new Object
I have these models: class Alarm(ModelWithValidation): datetime = models.DateTimeField(auto_now_add=True, db_index=True) priority = models.CharField(choices=ALARM_PRIORITY, default=NORMAL, max_length=6, db_index=True) value = models.TextField(null=True, blank=True) description = models.TextField() reading = GenericForeignKey('content_type', 'object_id') device_name = models.CharField(db_index=True, max_length=200, null=True, blank=True, default=None) device_type = models.CharField(db_index=True, max_length=30, null=True, blank=True, default=None) register = models.CharField(db_index=True, max_length=50, null=True, blank=True, default=None) content_type = models.ForeignKey(ContentType, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) class SolarMeterReading(ModelWithValidation): datetime = models.DateTimeField(db_index=True, auto_now_add=True) irradiance = RoundedDecimalField(max_digits=15, decimal_places=2, null=True, blank=True) ambient_temp = RoundedDecimalField(max_digits=15, decimal_places=2, blank=True, null=True, default=None) module_temp = RoundedDecimalField(max_digits=15, decimal_places=2, blank=True, null=True, default=None) wind_speed = RoundedDecimalField(max_digits=15, decimal_places=2, blank=True, null=True, default=None) name = models.CharField(db_index=True, max_length=30) alarms = GenericRelation(Alarm) I noticed that when i instatiate a SolarMeterReading Django make a SELECT query: SolarMeterReading(name='test', alarms=[]) Query: SELECT "api_alarm"."id", "api_alarm"."datetime", "api_alarm"."priority", "api_alarm"."value", "api_alarm"."description", "api_alarm"."device_name", "api_alarm"."device_type", "api_alarm"."register", "api_alarm"."content_type_id", "api_alarm"."object_id" FROM "api_alarm" WHERE ("api_alarm"."object_id" IS NULL AND "api_alarm"."content_type_id" = 18); Why Django make this query? There's no reason to search for the related alarms if the SolarMeterReading is not yet saved on the database. -
login() is not working at all - Django
I have a django app and I am trying to integrate the login system that they have within the framework. I have the following line of code: user = authenticate(username=username, password=password) login(request, user) I am running this method right after I create a new user after the user signs up and creates an account. I know the authentication is going to be successfull because I just created the account and I know it is there. I am gettting the following error login() takes 1 positional argument but 2 were given In the documentation is says you pass in a request and user... so why is it not working. this is driving me crazy.... Here is the documentation on djangos websites: login(request, user, backend=None)[source]¶ To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework. Note that any data set during the anonymous session is retained in the session after a user logs in. This example shows how you might use both authenticate() and login(): from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, … -
Mac OSX: LoadModule wsgi_module not working as mentioned in docs
I upgraded apache from 2.4.25 to 2.4.29 due to security reasons in Mac OSX. Also installed mod_wsgi via pip. Now facing difficulty while restarting the apache server! I ran this command as per the mod_wsgi docs, > mod_wsgi-express module-config LoadModule wsgi_module "/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so" WSGIPythonHome "/System/Library/Frameworks/Python.framework/Versions/2.7" Copied the above two lines in apache.conf file and tried to start the apache server but getting the following error: > sudo apachectl start /usr/local/apache/bin/apachectl: line 79: 51863 Illegal instruction: 4 $HTTPD -k $ARGV Any help would be appreciated. Thanks! -
Send Custom response from serializer in django rest framework?
I want to send a custom response from serializers create view to front-end of my application. I tried rest framework Response tutorials but it does not work. My code is: class UserSerializer(serializers.ModelSerializer): """Serializer to serialize user model object""" class Meta: model = User fields = ('id', 'username', 'password', 'first_name', 'last_name') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): """create a new user""" firstname = self.initial_data['first_name'] lastname = self.initial_data['last_name'] fullname = str(firstname) +" "+ str(lastname) email = self.initial_data['username'].lower() try: customer = User.create( name=fullname, email=email) except Error as e: error = {'message': e._message or 'Unknown error'} return Response(error,status=status.HTTP_400_BAD_REQUEST -
Bootstrap 4 popover not moving
I am looking to use a bootstrap popover on a scale from 0 to 100% showing the % that the user hover on. I do not now why when I have more than two scales my popover start to mess up ! have a look on the picture The 51% should be above the third scale. How can I fix the popovers ? I created the scales using a JS Script: var my = document.getElementsByClassName("scale"); for(var k = 0; k < my.length; k++){ for(var i = 0; i <= 100; i++) { var strg = '<div class="numbers ' + i + ' ' + k + '"' + 'onclick=\'select(this)\' data-toggle="popover" data-placement="top" data-content= "' + i + '%" ></div>'; my[k].innerHTML += strg; } } -
How to prevent fixtures to update the DB in Django?
I'm deploying a Django application as a deb file. The user is installing it using dpkg. When there is an update the user is installing it using dpkg and the application is updated. In every install process the is user is loading the default data from fixtures automatically. Consider s/he changed the default admin password. When s/he updates the deb package the password is set to default. I have tried to check if there is an old version already intalled in the system. So I can pass over loaddata issues. However the solution I provided above is not a good solution. Does Django provides a mechanism or choice for this? -
Django how to add a Group model field
i want add a description filed to Group, how to do it? edit source code? @python_2_unicode_compatible class Group(models.Model): name = models.CharField(_('name'), max_length=80, unique=True) description = models.CharField(_('description'), max_length=180, null=True, blank=True) # add permissions = models.ManyToManyField( Permission, verbose_name=_('permissions'), blank=True, ) objects = GroupManager() class Meta: verbose_name = _('group') verbose_name_plural = _('groups') def __str__(self): return self.name def natural_key(self): return (self.name,) and have other way? -
Django: Get request return old data
I updated data (call it data1) and saw in /admin page new values. But Model.objects.get(_id=obj.id) - return not actual data. So next step - i updated it again on data2 and i got data1. The values that I updated last time. The request is the most simple: def get_settings(self, obj): try: obj = Setting.objects.get(user_id=obj.id) except Setting.DoesNotExist: return None else: return UserSettingsSerializer(obj).data Are there any ideas why this happens? This is reproduced every time - returns only the previous value -
How to return several list without the model in Rest Framework?
How can I returns serval list in Rest Framework? I have serializers.py class HostTypeSerializer(ModelSerializer): class Meta: model = HostType fields = "__all__" class DiskOSTypeSerializer(ModelSerializer): class Meta: model = DiskOSType fields = "__all__" class DiskEssenceTypeSerializer(ModelSerializer): class Meta: model = DiskEssenceType fields = "__all__" I have the three Serializers, and I want to return data like bellow: { hosttypes:[the HostTypeSerializer's list data ], diskostype:[the DiskOSTypeSerializer's list data], diskessencetype:[the DiskEssenceTypeSerializer's list data], } I tried but failed, but I don't know how to do with that: class DiskPreCreateSerialzer(ModelSerializer): hosttypes = HostTypeSerializer(many=True, read_only=True) diskostypes = DiskOSTypeSerializer(many=True, read_only=True) diskessencetypes = DiskEssenceTypeSerializer(many=True, read_only=True) class Meta: fields = ( "hosttypes", "diskostypes", "diskessencetypes", ) In views.py: class DiskPreCreateAPIView(APIView): serializer_class = DiskPreCreateSerialzer permission_classes = [] ... I want to use this Serializer to returns my requirement, but failed, how can I get that?