Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'block' tag with name 'title' appears more than once
I'm trying to implement logic for my website with a title. But have this error - Django 'block' tag with name 'title' appears more than once. How do i fix this? base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} Main {% endblock %}</title> <meta charset="utf-8"> In my template product_list {% extends 'shop/application.html' %} {% if category %} {% block title %} Product name of category {% endblock %} {% elif subcategory %} {% block title %} Product name of subcategory {% endblock %} {% endif %} ... How to implement it? Thanks for help! -
(Django 2.1) Media files doesn't show?
I have a page where I want to show images uploaded by the users. So i made a for loop to iterate through every image in the database so here's the template tags : <div class="row"> {% for image in Patient_detail.images.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <div class="card"> <img src="{{ image.pre_analysed.url }}" > <div class="card-body"> <form method="POST" action="{% url 'patients:image_delete' image.pk %}"> {% csrf_token %} <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <!-- <button type="button" class="btn btn-sm btn-outline-secondary">Analyse</button> --> <button type="submit" class="btn btn-sm btn-outline-secondary">delete</button> </div> </div> </form> </div> </div> </div> </div> {% endfor %} </div> The number of images in the model appear but the images don't show, it appears as a broken link. Models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') analysedimage = models.ImageField(upload_to=analyses_directory_path, verbose_name='analysed Image', blank=True) upload_time = models.DateTimeField(auto_now=True) a = models.CharField(max_length=250) b = models.CharField(max_length=250) c = models.CharField(max_length=250) d = models.CharField(max_length=250) e = models.CharField(max_length=250) f = models.CharField(max_length=250) g = models.CharField(max_length=250) h = models.CharField(max_length=250) i = models.CharField(max_length=250) j = models.CharField(max_length=250) def get_absolute_url(self): return reverse('analysed_images',kwargs={'pk':self.pk}) I reference patient_detail as it's the context_object_name of the detail view of this particular detail view and .images.all as i reference the related name in the model … -
Django Rest Framework, React and Localization
I have a django rest framework which interacts with react. What is the best way to manage localization in such projects? I have django.po on server side. Is it possible to create one file and synchronize with both apps? -
Python Django Admin | Use to change content from website
First of all, I wanted to say, that I couldn't find a proper solution to this problem, and I am very new to Django and I have no idea how I could make this. Nor finding the proper documentation to this problem. As an example, I have a template with the following inside a <div>. An image, header, and a description. I want to configure my Django-Admin site localhost:8000/admin/ to be able to manage this content. So I need to program something that can upload images to a specific folder, write a header and a description. So that the information is being generated as a div inside the template. So can anyone give me any tips on how I should do this project? And where to find the proper docs, and/or a proper way of how to do this? So what I want in the end is on my Django-Admin site the option to add new objects and edit current ones. And that these objects autogenerate inside the template. So should I write/edit/read from a JSON file, or is there another way how to do this. -
Mapping a 1 - many relation in a Django Rest Framework View
In my DRF i want to map a customers/sercvices relation in the view. So one Customer can have 0 - many services inside of it My serializer class appears to be fine class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['name' , 'phone' ,'email1' ... , 'service_id'] class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = ['service_name', 'product_name', ...] class Customer_ServiceSerializer(serializers.ModelSerializer): service = ServiceSerializer(many=True, read_only=True) class Meta: model = Customer fields = ['name' , 'phone1' , 'email1' ... 'service'] My Customer_ServiceSerializer class seems to be nested correctly Im stuck on how i would show these combined models in the view as i have tried multiple things and come up stuck class Customer_serviceListAPIView(generics.ListAPIView): ... def get(self, request, *args, **kwargs): Above is how i started my views but i am stuck on how to solve this problem tried for example this Serialize multiple models in a single view / https://simpleisbetterthancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-querysets.html but i get Customer objects arent iterable so how would i go about this Thanks in advance -
Some CSS styles in css file are not applied, but they work when added to header of Html page
I previously had two CSS files, and the html page needed some css from one and only part of css from the other. The section of code was copied and pasted to the first CSS file, but these styles are not applied to the HTML page. when I create a block in the header and add the copied css styling into the html file, the styling is applied. I would like for the styling to work from linked css file. I checked that the linked urls are correct, and actually some of the other css files styles are used. I checked if I added the html elements into a wrong parent element, but does not seem to be the case. CSS file: #d_content_external{ line-height: 1.8; padding: 20px; } #d_links_indent{ margin-left: 40px; } /* OTHER STYLING ABOVE */ /* CODE BELOW ONLY WORKS IN HTML HEADER, NOT FROM HEADER FILE*/ #buttonwrapper{ padding: 10px 10px 15px 10px; } #attrwrapper{ position: relative; display: inline-block; width: 100%; } #dropupbtnIMG{ width: 100%; padding: 10px; font-size: 12px; font-weight: bold; background-color: #4d79ff; color:black; float: right; } /* attribution content DIV */ #divattributions{ min-height: 60px; max-height: 290px; padding: 10px; width:90%; font-size:14px; display: none; position: absolute; bottom: 100%; border-style: … -
Django celery - to check if a task is complete, if complete to restart the task (if not complete, do not restart the task)
I am currently trying to run a periodic check on a scheduled celery task every minute. If the task is still running, to let it continue running and not interrupt it, but if the task has no longer running, to activate the task and start running it. But at the moment, I cannot get the script to run only when it is no longer running. I have tried two methods of doing it but my script does not detect the existing running script and it starts to run even when it shouldn't and my task starts to run simultaneously. I am using celery 4.2.0 and django 1.11.6. Any tips on how I can solve this problem? Thanks in views.py Task to run @task(name='send-one-task') def send_one_task(): for i in range(1,100): time.sleep(1) print ("test1 " + str(i)) return None I have tried two methods to to check if process is complete and stopped running - if its not, do not rerun it method 1 @task(name='send-two-task') def send_two_task(): # method 1 from celery import current_task if current_task.request.task != "send-one-task": send_one_task() else: pass return None method 2 @task(name='send-two-task') def send_two_task(): from celery.task.control import inspect insp = inspect() testactive = insp.active() checkrunning = list(testactive.values()) try: … -
Archive data after every year
I have lots of models in my project like Advertisements, UserDetails etc. Currently I have to delete the entire database every year so as to not create any conflicts between this year data and previous year data. I want to implement a feature that can allow me to switch between different years. What can be the best way to implement this? -
Fix 'SECRET_KEY must not be empty' django error when hosting on pythonanywhere
I am trying to host my Django application on PythonAnywhere. Unfortunately, I cannot get past the following error: Error running WSGI application 2019-07-15 13:29:44,375: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I tried to follow their official tutorial for hosting an existing django app and have a basic wsgi configuration: # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/tkainrad/wagtail_cms_project' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'wagtail_cms_project.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() To be sure, I have two identical settings.py files in /home/tkainrad/wagtail_cms_project and /home/tkainrad/wagtail_cms_project/wagtail_cms_project These settings.py files contain a secret key, similar to the following: SECRET_KEY = 'dafa_o^el4*4+************************_@3sdfasdf' I.e. I do not try to read the key from a system property. Atm, this is just a test deployment and I am only trying to get it to work. Security and best practices will follow afterwards. Do you have an idea what could be wrong? -
Django REST Framework Serialize model with foreign key
Simple question: I have next models: class Artist(models.Model): name = models.CharField(...) surname = models.CharField(...) age = models.IntegerField(...) clas Album(models.Model): artist = models.ForeignKey(Artist, ...) title = models.CharField(...) I wish to create an Album serializer that: Shows Artist information on GET Can link Artist using pk on POST I can make the POST using pk using the following serializer, but I don't know how to GET artist information in the same serializer: class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = '__all__' Thanks. -
Django ORM really slow iterating over QuerySet
I am working on a new project and had to build an outline of a few pages really quick. I imported a catalogue of 280k products that I want to search through. I opted for Whoosh and Haystack to provide search, as I am using them on a previous project. I added definitions for the indexing and kicked off that process. However, it seems that Django is really, really really slow to iterate over the QuerySet. Initially, I thought the indexing was taking more than 24 hours - which seemed ridiculous, so I tested a few other things. I can now confirm that it would take many hours to iterate over the QuerySet. Maybe there's something I'm not used to in Django 2.2? I previously used 1.11 but thought I use a newer version now. The model I'm trying to iterate over: class SupplierSkus(models.Model): sku = models.CharField(max_length=20) link = models.CharField(max_length=4096) price = models.FloatField() last_updated = models.DateTimeField("Date Updated", null=True, auto_now=True) status = models.ForeignKey(Status, on_delete=models.PROTECT, default=1) category = models.CharField(max_length=1024) family = models.CharField(max_length=20) family_desc = models.TextField(null=True) family_name = models.CharField(max_length=250) product_name = models.CharField(max_length=250) was_price = models.FloatField(null=True) vat_rate = models.FloatField(null=True) lead_from = models.IntegerField(null=True) lead_to = models.IntegerField(null=True) deliv_cost = models.FloatField(null=True) prod_desc = models.TextField(null=True) attributes = models.TextField(null=True) … -
how can i take the comma separated ip addresses in django form?
i have to create a form which can take mutiple IP addresses (comma separated) from user and run the desired command (input from user) and display it on the web page. i could not figure out how can i do it. Currently the code is able to take single IP address, run command and display the result on web page, successfully.! forms .py from django import forms class CmdForm(forms.Form): ip_address = forms.CharField(label='Enter IP address:') command = forms.CharField(label='Command to execute:') Views.py click here for views.py note:- the issue on the link has been resolved -
get instances of child models of abstract base model class
I have a BaseModel class and three children of it. I want to get a queryset, that combines all instances of all subclasses to my BaseNotification class. Is there a way to do that in one query? class BaseNotification(BaseModel): seen = models.BooleanField(default=False) text = models.TextField() class Meta: abstract = True class ApprovalNotification(BaseNotification): object = models.ForeignKey("Object", on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey("User", on_delete=models.CASCADE) class ComplaintNotification(BaseNotification): complaint = models.ForeignKey("Complaint", on_delete=models.CASCADE) class ProposalNotification(BaseNotification): proposal = models.ForeignKey("Proposal", on_delete=models.CASCADE) When I try python BaseNotification.objects.all() it obviously gives an error that BaseNotification has no attribute 'objects'. -
status code in custom exception in python [on hold]
I want to create custom exception with custom status code in my django project my code must be something like this class CustomJsonError(Exception): def __init__(self, encoder=DjangoJSONEncoder, message=None, **kwargs): final_json = { "success": False, "code": kwargs.get('status'), "message": message, "data": {} } content = json.dumps(final_json, cls=encoder) super(CustomJsonError, self).__init__(content, kwargs.get('status')) and I want using that like this raise CustomJsonError(message=validate.errors, status=status.HTTP_400_BAD_REQUEST) and I expect to getting result like this in response with STATUS CODE 400, not 500 { "success": true, "code": 400, "message": { "adviser": [ "required field" ], "job": [ "required field" ] }, "data": {} } -
How to connect daphne and nginx using linux socket
I am trying to deploy Django application that needs both http and websocket connection using daphne and nginx. The connection between nginx and daphne is established using Linux socket. when nginx receives a request, daphne would exit with error "address already in use" I made sure that both users who run nginx and daphne have read and write access to the sock file nginx conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events {worker_connections 1024;} http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; map $http_upgrade $connection_upgrade { default upgrade; '' close;} access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; upstream websocket{server unix:/run/daphne/bot.sock;} include /etc/nginx/conf.d/*.conf; server { listen 80; server_name 10.xx.xx.65; location /static/js { alias /var/botstatic/js;} location /static/img { alias /var/botstatic/img;} location /static/css { alias /var/botstatic/css;} location /static/webfonts {alias /var/botstatic/webfonts;} location / { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade;} } daphne service file [Unit] Description=daphne server script After=network.target [Service] User=sattam Group=sattam WorkingDirectory=/home/sattam/sattambot #Environment=DJANGO_SETTINGS_MODULE=myproject.settings ExecStartPre=/home/sattam/ExecStartPre.sh ExecStart=/usr/bin/daphne -u /run/daphne/bot.sock --access-log /var/log/daphne/log SattamBot.asgi:application Restart=always [Install] WantedBy=multi-user.target ExecStartPre #!/bin/bash if [ ! -f /run/daphne/bot.sock ]; then mkdir -p /run/daphne; touch /run/daphne/bot.sock; … -
Django annotate not giving values for a many to many field
I wrote a views function: def get_lists(request,user_email): """Get all the lists made by user""" try: user_instance = MyUser.objects.get(email=user_email) except MyUser.DoesNotExist: return HttpResponse(json.dumps({'message':'User not found'}),status=404) if request.method == 'GET': influencers_list = UserInfluencerGroupList.objects.filter(user=user_instance).annotate(total_reach=Sum('influencers__followers'),total_engagement=Sum('influencers__avg_picture_engagement')).order_by('id') influencers_list = serializers.serialize('json',influencers_list, fields =['id','influencers','list_name','total_reach'], indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True) return HttpResponse(influencers_list,content_type='application/json',status=200) else: return HttpResponse(json.dumps({'message':'No lists found'}), status=400) I want to return the total number of followers of all the influencers in each list and also their total_engagement. However after using the annotate field, the json object returned doesn't have the total number of followers or the total_engagement in each list. How should I use annotate to display the total number of followers of all the influencers in each list and also their total_engagement. My django model is as follows: class UserInfluencerGroupList(models.Model): list_name = models.CharField(max_length=255) influencers = models.ManyToManyField(Influencer, blank=True) user = models.ForeignKey(MyUser, on_delete = models.CASCADE) -
How to range the items in loop in query set?
I am working on QuerySet and I have connected this views.py with MongoDB and instead of writing every item, I just want to loop it with database. But whenever I run the code it gives me AttributeError saying that 'int' object has no attribute 'img'. How to give range to it? Because I made three variables target1, target2 and target3 just to divide the title and images in three columns in index.html. Without for loop range it is giving me all the results def index(request): query = request.GET.get('srh') if query: target1 = Destination.objects.filter(title__icontains=query) target1 = Destination.objects.all() for field in target1: field.img field.title *Without using database with it.* target2 = c = [Destination() for __ in range(2)] c.img = 'Data Entry.jpg' c.title = 'Data Entry' target3 = f = [Destination() for __ in range(2)] f.img = 'Website Testing.jpg' f.title = 'Website Testing' context = { 'target1': target1, 'target2': target2, 'target3': target3 } return render(request, 'index.html', context) -
How to inherit file from parent to fill form field?
I did some inheritance from filled data to one of my form. That fields are strings and files. When inheritance string fields worked fine, but the files was empty and not showed in my template. I though main problem on my views. I really stuck here. Any solution for my code? Or any ideas for what i have to do? views.py @login_required def forward(request, message_id, form_class=ComposeForm, template_name='mails/compose.html', success_url=None, recipient_filter=None, quote_helper=format_quote, subject_template=_(u"Re: %(subject)s"),): """ Prepares the ``form_class`` form for writing a reply to a given message (specified via ``message_id``). Uses the ``format_quote`` helper from ``messages.utils`` to pre-format the quote. To change the quote format assign a different ``quote_helper`` kwarg in your url-conf. """ parent = get_object_or_404(Message, id=message_id) if parent.sender != request.user and parent.recipient != request.user: raise Http404 if request.method == "POST": sender = request.user form = form_class(request.POST, request.FILES, recipient_filter=recipient_filter) if form.is_valid(): form.save(sender=request.user, parent_msg=parent) messages.info(request, _(u"Message successfully sent.")) if success_url is None: success_url = reverse('mails:messages_inbox') return HttpResponseRedirect(success_url) else: form = form_class(initial={ 'body': quote_helper(parent.sender, parent.body), 'subject': parent.subject, #HERE #this two are filefield, but strings other worked fine and showed on template 'file_surat': [parent.file_surat.url], 'lampiran': [parent.lampiran.url], 'nomor_surat': parent.nomor_surat, 'jenis_surat' : parent.jenis_surat, 'sifat_surat' : parent.sifat_surat, }) return render(request, template_name, { 'form': form, }) forms.py class … -
Django rest framework custom filter backend data duplication
I am trying to make my custom filter and ordering backend working with default search backend in django rest framework. The filtering and ordering working perfectly with each other, but when search is included in the query and i am trying to order query by object name, then data duplication is happening. I tried to print queries and queries size, but it seems ok when i logging it in the filters, but in a response i have different object counts(ex. 79 objects in filter query, 170 duplicated objects in the final result) Here is my filterset class class PhonesFilterSet(rest_filters.FilterSet): brands = InListFilter(field_name='brand__id') os_ids = InListFilter(field_name='versions__os') version_ids = InListFilter(field_name='versions') launched_year_gte = rest_filters.NumberFilter(field_name='phone_launched_date__year', lookup_expr='gte') ram_gte = rest_filters.NumberFilter(field_name='internal_memories__value', method='get_rams') ram_memory_unit = rest_filters.NumberFilter(field_name='internal_memories__units', method='get_ram_units') def get_rams(self, queryset, name, value): #here is the problem filter #that not works with ordering by name q=queryset.filter(Q(internal_memories__memory_type=1) & Q(internal_memories__value__gte=value)) print('filter_set', len(q)) print('filter_set_query', q.query) return q def get_ram_units(self, queryset, name, value): return queryset.filter(Q(internal_memories__memory_type=1) & Q(internal_memories__units=value)) class Meta: model = Phone fields = ['brands', 'os_ids', 'version_ids', 'status', 'ram_gte'] My ordering class: class CustomFilterBackend(filters.OrderingFilter): allowed_custom_filters = ['ram', 'camera', 'year'] def get_ordering(self, request, queryset, view): params = request.query_params.get(self.ordering_param) if params: fields = [param.strip() for param in params.split(',')] ordering = [f for f in … -
save multiplechoicefield in django
I try to save data from multiplechoiceField but only one item is save. when only one item we don't have a problem , when is multiple only the last item is save models.py class Reservation( models.Model): date_de_reservation = models.DateTimeField('Date de reservation', auto_now = True) type_enseignement = models.CharField('Type enseignement', max_length = 10, choices = (("cm", "CM"), ("td", "TD"), ("tp", "TP"), ("tc","TC")), ) date_du_jour_reserve = models.DateField("Date du jour reservé") plage_horaire = models.ForeignKey("Plage_Horaire", on_delete = models.CASCADE ) cours = models.ForeignKey(Cours, on_delete = models.CASCADE) enseignant = models.ForeignKey(Enseignant, on_delete = models.CASCADE) sallecours = models.ForeignKey(SalleCours, on_delete = models.CASCADE, blank = True, null = True) option = models.ForeignKey(Option,on_delete = models.CASCADE ) valide = models.BooleanField(blank = True, default = False) analyse = models.BooleanField(blank = True , default =False ) forms.py class Reservation_Form(forms.ModelForm): faculte=forms.ModelChoiceField(label="Faculte", queryset=Faculte.objects.all()) departement=forms.ModelChoiceField(label="Département", queryset=Departement.objects.all()) filiere=forms.ModelChoiceField(label="Filière", queryset=Filiere.objects.all()) niveau = forms.ModelChoiceField(label = 'Niveau', queryset = Niveau.objects.all() ) option=forms.ModelChoiceField(label="Option", queryset=Option.objects.all()) semestre=forms.ModelChoiceField(label='Semestre', queryset=Semestre.objects.all()) plage_horaire = forms.ModelMultipleChoiceField(label="", queryset = Plage_Horaire.objects.all()) class Meta: model=Reservation exclude=('date_de_reservation', 'sallecours', 'valide', 'enseignant','plage_horaire' ) widgets={ 'date_du_jour_reserve': DateInput(), } views.py def reservation(request): f=Reservation_Form() if request.method=='POST': f=Reservation_Form(request.POST) print (f.is_valid()) print(request.POST.getlist('plage_horaire') ) if f.is_valid() : res = f.save(commit=False) plage_horaire = f.cleaned_data['plage_horaire'] for i in plage_horaire: res.plage_horaire=i res.save() return redirect('configuration:ma_reservation') -
What are types of project recommended for django to do as a student?
Doing a Django project, what should be its structure and add-ons ? I've tried doing a game project on windows but all the codes were in a mess. Using the latest version of pycharm and django. -
Python test coverage for class' __str__
I have a very basic questing regarding Python coverage tests. In my Django models, all the __str__ representations are not covered in my tests. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name What would be the appropriate way to test these? This doesn't work: class TestCategory(TestCase): def test_category(self): category = Category.objects.create(name='Test Category') self.assertEqual(category.__str__(), 'Test Category') Thank you in advance for your help! -
if a task call with delay() when will execute exactly?
I'm new in celery and i want use it but i don't know when i call a task with delay() when exactly will execute? and after adding a new task what i must to do to this task work correctly? i use a present project and i extending it, but old task work correctly and my task doesn't . present app1/task.py: from __future__ import absolute_import, unicode_literals import logging logger = logging.getLogger('notification') @shared_task def send_message_to_users(users, client_type=None, **kwargs): . . #doing something here . . logger.info( 'notification_log', exc_info=False, ) ) and this is my code in app2/task.py: @shared_task def update_students_done_count(homework_id): homework_students = HomeworkStudent.objects.filter(homework_id=homework_id) students_done_count = 0 for homework_student in homework_students: if homework_student.student_homework_status: students_done_count += 1 homework = get_object_or_404(HomeWork, homework_id=homework_id) homework.students_done_count = students_done_count homework.save() logger.info( 'update_students_done_count_log : with id {id}'.format(id=task_id), exc_info=False, ) sample of how both task calling: send_message_to_users.delay(users = SomeUserList) update_students_done_count.delay(homework_id=SomeHomeWorkId) project/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hamclassy.settings') app = Celery('hamclassy') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. … -
Is using view decorators to handle user permissions bad practice?
I'm using django view decorators to check permissions in quite a complex way, and am starting to realise that this might be bad practice. Given a user's profile is in a certain state, say 'application pending' and so certain views should not be shown to this user, but should be shown to users who have 'application complete'. I'm currently using decorators to redirect pending users to the homepage, with a popup telling them their application is still pending. However, I read on google's python best practice, that decorators should be simple, and not rely on database connections, files etc. Does this mean that something such as checking the state of a borrowers application before showing a view is bad practice, and if it is, what is an alternative? -
Django rest framework - Serialize all fields of native object
I'm trying to serialize an object that's a mix of normal fields, model objects and querysets. I want to include all normal fields and then I'll create serializers for each model type. The problem is I can't automatically add all the non-model fields from my class: class ObjectSerializer(serializers.Serializer): class Meta: fields = '__all__' It Gives me an empty object. Is there any way to include all fields using non-model serializer? Or is there better way to achieve what I'm trying to do?