Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WindowsError: [Error 32] when trying to delete FileField in Django
I am writing a django-nose test to test feature for document uploading. In the test I mock new document using SimpleUploadedFile() from django.core.files.uploadedfile. The problem is that the file associated with the document instance cannot be deleted on Windows (test passes on Linux). I get the following error: in auto_delete_file_on_delete()-> os.remove(instance.document.path) WindowsError: [Error 32] The process cannot access the file because it is being used by another process: Here's my test: def test_delete_doc(self): self.client.login(username='xx', password='xx') dir_path = os.getcwd() manager_user = User.objects.get(username='xx') file_name = "test_document" file_path = os.path.join(dir_path, file_name) new_file = open(file_path, "w") new_file.write("Some file content") new_file.close() new_file = open(os.path.join(dir_path, file_name), "rb") new_doc = SimpleUploadedFile(name=file_name, content=new_file.read()) new_file.close() self.client.post(reverse('view_upload'), {'employee_id': manager_user.profile.employee.empId, 'document': new_doc}) self.assertEqual(len(Document.objects.all()), 1) self.client.post(reverse('delete'), {'file_id': Document.objects.all().first().pk}) self.assertEqual(len(Document.objects.all()), 0) My view (reverse('delete') refers to delete_document()): def delete_document(request): instance = Document.objects.get(doc_id=request.POST['file_id']) instance.delete() return redirect('view_upload') And the signal attached to the instance removal: @receiver(models.signals.post_delete, sender=Document) def auto_delete_file_on_delete(sender, instance, **kwargs): if instance.document: if os.path.isfile(instance.document.path): os.remove(instance.document.path) Does anyone have any ideas why that is happening? I already tried (getting same error): Using with to open/close the file. Using os.open()/os.read()/os.close() to deal with the file. Removing SimpleUploadedFile() and simply using new_doc = open() to open the file and pass it to the POST request. Thanks! -
Synthetic/redundant Django migrations caused by sysdate dependent date validator
I have a date field like the one below in a Django model, where I want the date to be in the future (or today, but not in the past). foo = models.DateField('Foo', null=True, validators=[MinValueValidator(date.today())]) This works fine, validation happens as expected on forms, however, makemigrations creates a new migration every day it runs with that date, below is an example produced today: field=models.DateField(null=True, validators=[django.core.validators.MinValueValidator( datetime.date(2018, 1, 26))] How can I avoid this? Should I use a custom validator instead of MinValueValidator or add a clean method to the Form subclass instead like this? -
Django 1.11 - is there a way to combine fields from models.Model to auth.models?
What I aim to achieve in the end is to combine the list of all users (from auth.models) with a DateTimeField from another model (model.Model). What's the best way of doing this? My code: survey/models/response.py from django.contrib.auth.models import User from django.db import models class Response(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, blank=True) In admin.py, I can create a custom user class which lists all of the registered users' usernames like so: survey/admin.py from django.contrib.auth.models import User admin.site.unregister(User) class UserAdmin(admin.ModelAdmin): list_display = ('username',) admin.site.register(User, UserAdmin) Essentially I want extend UserAdmin as list_display = ('username', 'created') - with username coming from auth.models and created coming from models.Model. At the moment I can create a class in admin.py that shows me a list of all the users who have submitted a Response. The issue is that if you have 200 users, it is more useful to see who hasn't submitted from a list of all users than only listing the users who have submitted a Response. -
Django model Diamond multiple inheritance
I'm a web programming starter. I'm doing web programming with Django. I found a problem with modeling. Below is my code. (I wrote this in Python 2.7.12.) class ImageModel(models.Model): pass class FaceModel(ImageModel): def save(self, *args, **kwargs): print "FaceModel" super(FaceModel, self).save(*args, **kwargs) # Do Something super(FaceModel, self).save() class ObjectModel(ImageModel): def save(self, *args, **kwargs): print "ObjectModel" super(ObjectModel, self).save(*args, **kwargs) # Do Something super(ObjectModel, self).save() class PlaceModel(ImageModel): def save(self, *args, **kwargs): print "PlaceModel" super(PlaceModel, self).save(*args, **kwargs) # Do Something super(PlaceModel, self).save() class AllModel(FaceModel, ObjectModel, PlaceModel): pass But, The result is the value I want. But there is one problem. FaceModel.save() call one, ObjectModel.save() call tow and PlaceModel.save() call four times. It's too slow. I want to call the save() function each model only once. What should I do? -
Django Forms Nested If - Second Condition
I have a django form that checks if a postcode is valid and if valid it will perform a check against postcodes that are permitted for delivery. I cant get the second condition working in the nested if structure (works fine independently). This is the code: from django import forms import requests class PostCodeForm (forms.Form): pcode = forms.CharField() def clean_pcode(self): pcode = self.cleaned_data['pcode'].lower() permitted = {'gu15','GF34','FG34','BT25'} url = 'https://api.postcodes.io/postcodes/{}/validate'.format(pcode) r = requests.get(url) is_correct = r.json()['result'] if not is_correct: raise forms.ValidationError("Your postcode is invalid. Please re-enter a valid entry.") if not pcode[:4] in (permitted): raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.") return pcode -
Django queryet FK with related name return None
I need a view where I can display a list of groups ("Group") to which the objects to download are downloaded ("Downloads"). I wrote the code in the view, but in the place of downloads I get None, even though I have attached the Download to the Group. Please hint. Model: class Group(models.Model): name = models.CharField(max_length=500) show_products = models.BooleanField(default=False) def __str__(self): return self.name class Download(AbstractDownload): group = models.ForeignKey('downloads.Group', related_name='downloads') file = FilerFileField(related_name="file_downloads_download") def __str__(self): return self.title View: class GroupListlView(ListView): queryset = downloads.Group.objects.filter(downloads=downloads.Download.objects.all()) context_object_name = 'group_list' Template: <ul> {% for i in group_list %} <li>{{ i.name }}</li> <li>{{ i.downloads }}</li> {% endfor %} </ul> -
choices with model in the form field in the django test
I have this form: class Dashboard(forms.Form): year = forms.ChoiceField(choices=Year.objects.all().values_list('pk', 'year')) and my test is not running because this error: django.db.utils.OperationalError: no such table: common_year -
Django-select2 throwing 'Results cannot be loaded.'
I'm trying to deploy my django application in a Droplet virtual machine (DigitalOcean) following this guide. For this purpose I've used nginx and gunicorn with success. The problem I'm facing is with django-select2 and is that the widget of the form always show 'Results cannot be found.' giving a 404 error, while in my local environment it work flawlessly! I've tried to implementing the cache (hoping that it will solve the issue) but things get worse since with the cache enabled the widget seems to not work anymore even in local. Now the time to show my code so far: settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', }, 'select2': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 60 * 60 * 24, }, } SELECT2_CACHE_BACKEND = 'select2' This is the code done following the guide displayed here PS: Note that using redis instead of memcached give the same result this is my nginx configuration: server { listen 80; server_name 46.101.134.225; client_max_body_size 2M; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /projectname; } location /media { root /projectname/staticfiles; } location /assets { root /; } location / { include proxy_params; proxy_pass http://unix:/projectname/projectname.sock; } } this … -
Django are sessions safe to use to store permission information
I am currently writing an application in Django and I am looking at storing specific permission information during a user's session. The permissions are made up of the following values; No Permissions - 0 Read Only - 1 Edit - 2 Add and Edit - 3 Full Permission - 4 The higher the value, the better the permission a user has. If a user has only "Edit" permission for the module "Projects", I want to store that somewhere so I don't have to get Django to query the database constantly. Would it be appropriate to use the following; request.session['project_permission'] = '2' Or would the user be able to edit this value and sneak in a higher number like 3 or 4? Thank you for reading. -
how to make social login with DRF as backend and angularjs as frontend and DRF return jwt token for further interaction
I am using angularjs as frontend and djnago rest frame(DRF) as backend. I want to make social login for my site. Requirements User logs in using the app to FB/Google. FB/Google returns an access_token. The app sends this access_token to Django backend using POST request. Django Backends find the user associated to this FB account or creates a new one using first name, last name and email from FB account. Django returns a JWT token for further authentication. The JWT is saved on the browser as cookies. Next the app uses this JWT to authenticate the user and then no more FB log in is necessary. Pls suggest me any lecture or repository. -
Error While Creating the Group and sending message Only occupants are allowed to send messages to the conference
when I create a group with a user and try to send message got the following error First got -==> Only occupants are allowed to send messages to the conference <?xml version="1.0" encoding="UTF-8"?> <body xmlns="http://jabber.org/protocol/httpbind"> <message xmlns="jabber:client" from="ac71431e028511e89b3e02e4552e4a4e@staging.xxx.co" to="1726@xmpp-staging.xxx.co/1803939046680240744214138" type="error" origin="groupchat" id="6445" attempts="1"> <body>first message</body> <x xmlns="jabber:x:event"> <composing /> </x> <html xmlns="http://jabber.org/protocol/xhtml-im"> <body xmlns="http://www.w3.org/1999/xhtml">https://xxx-storage.s3.amazonaws.com:4***0.jpg</body> </html> <error code="406" type="modify"> <not-acceptable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" /> <text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">Only occupants are allowed to send messages to the conference</text> </error> </message> </body> Then --=> User session not found <?xml version="1.0" encoding="UTF-8"?> <message xmlns="jabber:client" from="1825@xmpp-staging.xxx.co" to="1726@xmpp-staging.xxx.co/1803939046680240744214138" type="error" origin="chat" id="null" attempts="3"> <body>test4</body> <error code="503" type="cancel"> <service-unavailable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" /> </error> </message> Error 503 <?xml version="1.0" encoding="UTF-8"?> <body xmlns="http://jabber.org/protocol/httpbind"> <message xmlns="jabber:client" from="ac71431e028511e89b3e02e4552e4a4e@staging.xxx.co" to="1726@xmpp-staging.xxx.co/1803939046680240744214138" type="error" origin="groupchat" id="6445" attempts="3"> <body>first message</body> <x xmlns="jabber:x:event"> <composing /> </x> <html xmlns="http://jabber.org/protocol/xhtml-im"> <body xmlns="http://www.w3.org/1999/xhtml">https://xxxxx-storage.s3.amazo*.jpg</body> </html> <error code="503" type="cancel"> <service-unavailable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" /> <text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">User session not found</text> </error> </message> </body> what is wrong configured and what i am not doing correct to send the message -
Identify which polygon contains a point with Django?
I need to identify quickly to which polygons belong a set of point in Django 1.9, using geodjango. First option is to loop through all polygons and check which points they contain: for countrypolygon in countrypolygons: placesinthecountry = Place.objects.filter(lnglat__intersects=countrypolygon.geom) This takes a lot of time as I need to loop through a lot of polygons. Is it possible to do the opposite, i.e. loop through each point and immediately get the polygons in which it is contained? Thanks a lot -
fetching grouped records of user from a table
I am trying to fetch some data from a userholding table. My userholding table is below: +----+-------------+--------------+----------------------------+------------+--------+ | id | Qty_holding | Qty_reserved | created | tokenid_id | uid_id | +----+-------------+--------------+----------------------------+------------+--------+ | 1 | 10 | 0 | 2018-01-18 10:52:14.957027 | 1 | 1 | | 2 | 20 | 0 | 2018-01-18 11:20:08.205006 | 8 | 1 | | 3 | 110 | 0 | 2018-01-18 11:20:21.496318 | 14 | 1 | | 4 | 10 | 0 | 2018-01-23 14:26:49.124607 | 1 | 2 | | 5 | 3 | 0 | 2018-01-23 15:00:26.876623 | 11 | 2 | | 6 | 7 | 0 | 2018-01-23 15:08:41.887240 | 11 | 2 | | 7 | 11 | 0 | 2018-01-23 15:22:48.424224 | 11 | 2 | | 8 | 15 | 0 | 2018-01-23 15:24:03.419907 | 11 | 2 | | 9 | 19 | 0 | 2018-01-23 15:24:26.531141 | 11 | 2 | | 10 | 23 | 0 | 2018-01-23 15:27:11.549538 | 11 | 2 | | 11 | 27 | 0 | 2018-01-23 15:27:24.162944 | 11 | 2 | | 12 | 7.7909428 | 0.11459088 | 2018-01-23 15:27:24.168643 | 1 | 2 | | … -
How to display answers in index django?
I am trying to display questions and answer count in respective questions, all in the home page. How do I do it? Models.py class Question(models.Model): CATEGORY_CHOICES = ( ('Math', 'Math'), ('Geography', 'Geography'), ('Biology', 'Biology'), ('Physics', 'Physics'), ('Chemistry', 'Chemistry'), ('Health', 'Health'), ('Computer Science', 'Computer Science'), ('History', 'History'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(max_length=3000) slug = models.SlugField(max_length=140, unique=True) date = models.DateField(null=True, default=datetime.date.today) category = models.CharField(choices=CATEGORY_CHOICES, max_length=50, default=None, null=True) satisfied = models.BooleanField(default=False) def __str__(self): return self.title def _get_unique_slug(self): slug = slugify(self.title) unique_slug = slug num = 1 while Question.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save() class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(User, default=None) answer = models.TextField(max_length=3000, null=True) posted_on = models.DateField(default=datetime.datetime.now().date()) views.py def home(request): questions = Question.objects.all().order_by("-date") numbers = Question.objects.all().count() numbers2 = Answer.objects.all().count() total_users = User.objects.all().count() # PAGINATION =============================== page = request.GET.get('page', 1) paginator = Paginator(questions, 10) try: questions = paginator.page(page) except PageNotAnInteger: questions = paginator.page(1) except EmptyPage: questions = paginator.page(paginator.num_pages) # counting answers on specific questions empty = [] for a in Answer.objects.raw('SELECT id, question_id FROM main_answer'): idd = a.id question_id = (a.question_id) empty.append(str(question_id)) repeatition = Counter(empty) i = 0 trend_list = … -
Django form save - update boolean field
I have the following model: class Survey(models.Model): is_published = models.BooleanField() which is set to "False" as the default. I am using modelForm to add this into a form. When I call the save() method on the form, I want to change "False" to "True" and save this to the db. How do I do that? I've read through https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/ and it doesn't explain how this would work. -
How to retrieve an access token using Django OAuth Toolkit
Currently, I try to integrate the OAuth Toolkit into my Django based web service. I follow this tutorial: Building OAuth2 Services in Django I try to retrieve an access token by using the following URL: http://localhost:8000/polls/o/token The debugger shows my a HTTP 302 status code and i get the following error messge: Error retrieving access token! {"error_description": "Mismatching redirect URI." "error":"invalid:request"} If I understand it correctly, the token URL should cause the error: # OAuth2 provider endpoints oauth2_endpoint_views = [ url(r'^authorize/$', oauth2_views.AuthorizationView.as_view(), name="authorize"), url(r'^token/$', oauth2_views.TokenView.as_view(), name="token"), url(r'^revoke-token/$', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"), ] I also tried to add/remove the trailing slash, but that was not helping. I am using django version 1.11 and python2.7 Any suggestions? -
Can’t connect to MySQL while upgrading by rb-site
I am trying to upgrade Bitnami ReviewBoard from 3.0.1 to 3.0.2 . I have done the venv/bin/easy_install -U ReviewBoard. But when I try venv/bin/rb-site upgrade installdir/rb-sites/reviewboard/, I obtained an error of django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/opt/reviewboard-3.0.1-0/mysql/tmp/mysql.sock' (2)"). Following is the detailed log: bash-4.2# venv/bin/rb-site upgrade ./rb-sites/reviewboard/ Traceback (most recent call last): File "venv/bin/rb-site", line 11, in <module> load_entry_point('ReviewBoard==3.0.2', 'console_scripts', 'rb-site')() File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/ReviewBoard-3.0.2-py2.7.egg/reviewboard/cmdline/rbsite.py", line 1965, in main command.run() File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/ReviewBoard-3.0.2-py2.7.egg/reviewboard/cmdline/rbsite.py", line 1742, in run static_media_upgrade_needed = site.get_static_media_upgrade_needed() File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/ReviewBoard-3.0.2-py2.7.egg/reviewboard/cmdline/rbsite.py", line 503, in get_static_media_upgrade_needed siteconfig = SiteConfiguration.objects.get_current() File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/Djblets-1.0.2-py2.7.egg/djblets/siteconfig/managers.py", line 50, in g et_current site = Site.objects.get_current() File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/contrib/sites/models.py", line 47, in get_current current_site = self.get(pk=sid) File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/models/manager.py", line 151, in get return self.get_queryset().get(*args, **kwargs) File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/models/query.py", line 304, in get num = len(clone) File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/models/query.py", line 77, in __len__ self._fetch_all() File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/models/query.py", line 857, in _fetch_all self._result_cache = list(self.iterator()) File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/models/sql/compiler.py", line 785, in execute_sql cursor = self.connection.cursor() File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/backends/__init__.py", line 162, in cursor cursor = util.CursorWrapper(self._cursor(), self) File "/opt/reviewboard-3.0.1-0/apps/reviewboard/htdocs/venv/lib/python2.7/site -packages/django/db/backends/__init__.py", line … -
django 2.0 model, alias field
My higher level goal is to have a polymorphic association between models and I think I can solve it with a model with this signature: class Relation(models.Model): left = ForeignKey(Entity) right = ForeignKey(Entity) class Meta: db_table = 'entities' then I can extend Relation as proxy so I can be more clear on my intention of left and right field, for ex: class Authorship(Relation) author = AliasField('left') content = AliasField('right') class Meta: proxy = True So then we can do the following: Authorship.objects.filter(author=user_entity) or Authorship.objects.create(author=user_entity) My question is, how do I implement AliasField function described above? I have looked at: https://shezadkhan.com/aliasing-fields-in-django/ How to create an alias for Django Model field? for the first link, I am getting error about name is not a field or something for the second one, I am getting an error saying "can't adapt type" is this even possible to do in Django 2.0? I prefer not to use django-polymorphic Thank you! -
Django ForeignKey related field with localization of ChoiceField.
I have a custom user model with a country field and I am using django-cities's Country model as a ForignKey. I also want to use localization for country names. (I cannot import alt_names of django-cities for localization so that option is off the table). In my forms.py I try to give choice fields with from cities.models import Country from django.utils.translation import gettext_lazy as _ class SignupForm(UserCreationForm) c = Country.objects.all() country_choices = [(Country.objects.filter(id=c[i].id), c[i].name ) for i in range(len(c)) ] country_choices_localize = [(c[0], _('{0}'.format(c[1]))) for c in country_choices] country = forms.ChoiceField(choices=tuple(country_choices_localize), initial=None) This does not seem to work. I get ValueError for Country.objects.filter(id=c[i].id). Saying that MyUser.country must be 'Country' instance. Is there a work around to use localization in ChoiceField along with Country model? -
What is the best data structure for one to many relation on Django?
For instance, let's suppose we have a webapp with Pizza and Toppings. One pizza can have many toppings but a topping cannot have many pizzas, which seems logical so far. I'm using a structure like this one below but I am not sure wether I should use ManyToMany Field or ForeignKey since OneToMany doesn't exist on Django. class Pizza(models.Model): created_at = models.DateTimeField(auto_now_add=True) order_id = models.CharField(max_length=255) def __str__(self): return self.order_id class Topping(models.Model): created_at = models.DateTimeField(auto_now_add=True) topping_name = models.(max_length=255) pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) #if a pizza is deleted, delete its toppings. def __str__(self): return self.topping_name If I'm doing this right, should I access a pizza and all its toppings like this ? pizzas = Pizza.topping_set.filter(order_id=my_order_id) Is there a better way or is it optimal to keep it like this? -
Upstream prematurely closed connection while reading response header from upstream. NGINX, uWSGI, supervisor
I am trying to deploy django on ubuntu 16.04 on a DO droplet using uWSGI, NGINX and supervisor. I am successfully running the app with python manage.py runserver [ip]:8000 and uwsgi --http-socket :8080 --module saleor.wsgi When I try to run the app with supervisor I am getting: 502 Bad Gateway in the browser. In the ngxinx logs I am getting: upstream prematurely closed connection while reading response header from upstream my nginx conf file: saleor_nginx.conf # the upstream component nginx needs to connect to upstream saleor { server unix:///etc/uwsgi/saleor.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { listen 80 default_server; server_name example.com; # IP removed from post on purpose charset utf-8; # max upload size client_max_body_size 4G; # adjust to taste access_log /webapps/saleor/saleor/logs/nginx-access.log; error_log /webapps/saleor/saleor/logs/nginx-error.log; # Django media location /media { alias /webapps/saleor/saleor/media; # your Django project's media files - amend as required } location /static { alias /webapps/saleor/saleor/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass unix:///etc/uwsgi/saleor.sock; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed … -
How to make testing cache storage (Redis) in Django with Pytest?
I'm using Django 1.11.9 with django-pytest library for testing my apps. Also, I use Redis as cache storage. My question is — how to make testing cache storage and setting up his with test data before run test? Like database do it. I want to add some key: value data to testing cache storage (in Redis), run tests and then delete all of this test data (clear test cache). -
Django rest framework api response add-on
So i have a table call Book. I am using modelviewset but i wanted my response to have an add on response. In my Book table : class Book(models.Model): book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) serializer class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'book', 'author') view class BookViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Book.objects.all() serializer_class = BookSerializer the return result after post or update method will return the data/field which user have create/update. But i wanted to add on to it for example. current result { "id": 1, "book": "hello", "author": "helloauth", } result i want { "id": 1, "book": "hello", "author": "helloauth", "message": "You have successfully create a book", "status": "200", } The custom code i have now is just showing the message only: custom views class BookViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Book.objects.all() serializer_class = BookSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response({"message": "You have successfully create a book", "status": "200"}, headers=headers) How to i make it combine/display together ? -
Django API modify JSON response
I'm trying to make an API with Django rest framework but I'm struggling to modify the JSON response as I want. If you need anything else, just ask, Thanks for your help! models.py class Feature(models.Model): name = models.CharField(max_length=255, unique=True, null=True) def __str__(self): return "{}" .format(self.name) def save(self, *args, **kwargs): super(Feature, self).save(*args, **kwargs) class Opponent(models.Model): name = models.CharField(max_length=255, unique=True, null=True) features = models.ManyToManyField(Feature, blank=True, null=True) def __str__(self): return "{}" .format(self.name) def save(self, *args, **kwargs): super(Opponent, self).save(*args, **kwargs) serializers.py class FeatureSerializer(serializers.ModelSerializer): opponents = serializers.RelatedField(many=True) class Meta: model = Feature views.py @csrf_exempt @jsonify def get_opponents(request): if request.method == 'OPTIONS': return HttpResponse() opponents = list(Opponent.objects.all().values('id', 'features')) return opponents JSON response [ { "id": 1, "features__name": "feature1" }, { "id": 1, "features__name": "feature2" } ] What I want [ { "id": 1, "features": ["feature1", "feature2"] } ] -
How to produce upwards compatible Django (for Django and apache unattended security updates)
I am writing (my first) Django application, which will run on a (public accessible) Ubuntu LTS server (apache) where users (just a very small number, not "the public") can, amongst other things, upload files. Ideally this application should run for many years to come; there will be no need for any feature upgrades or updates in the interface etc; I would just like to get necessary security updates with as little future effort as possible. So I use the current standard ubuntu LTS packages: python 3.5 and Django 1.8. This way, any future security vulnerabilities will be fixed "automatically" (i.e., by the ubuntu security team). To clarify: With security I mean I want to make sure that the server isn't hacked and used to serve some illegal crap, or delete the data. I am much less concerned about availability: If evil hackers bring the server down by DOS attacks or similar so be it. (Actually, I wouldn't even be a catastrophe if hackers stole all the data). Anyways, for reasons of automatic, unattended security updates I do not want to use backports or pip. Django 1.8 is supported only till mid 2018 (according to https://www.djangoproject.com/download/). I assume it will eventually …