Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Im trying list category and get category detail in django admin
How to show the products relation ship into the category and how to get category and detail categoy Models class Categoria(models.Model): slug = models.SlugField(max_length=100, unique=True) def __str__(self): class Producto(models.Model): producto = models.CharField(max_length=200, unique=True) categoria = models.ForeignKey(Categoria, related_name='categoria', on_delete = models.CASCADE) slug = models.SlugField(max_length=200, unique=True) def __str__(self): return self.producto Views class ProdList(generic.ListView): queryset = Producto.objects.filter(status=1).order_by('-created_on') template_name = 'categorias.html' class CatList(generic.ListView): queryset = Categoria.objects.all() template_name = 'index.html' -
Writing an AJAX POST request to be recieved by a Django view
I'm trying to write an AJAX post function to be recieved by one of my django views, however it isn't working. Here is my ajax call $.ajax({ url : 'localhost:8000/increment?amount=5&persist=yes', type : 'POST', data : { 'amount' : amount }, dataType:'json', success : function(data) { alert('Data: '+data); }, error : function(request,error) { } }); and here is the django view that is supposed to be recieving it @login_required def Increment(request): if request.method=="GET": amount = request.GET.get('amount', 0) # returns 5 persist = request.GET.get('persist', 'no') #returns yes profile = get_object_or_404(Profile, user=request.user) profile.coins += amount profile.save(update_fields=['coins']) return HttpResponse('') #return void -
User information incorrect in sentry event using django middleware with python sentry-sdk
I'm upgrading raven to sentry-sdk in a Python/Django application. This application uses more than one middleware to update request.user. Up to now, using Raven I got correct user information in my sentry events since I could place the Raven middleware after my user middlewares were processed. With sentry-sdk, the integration isn't accomplished with middleware. After I've upgraded to sentry-sdk, sentry events don't have the correct user information. Perhaps this is because they aren't seeing the modified user information after the middleware is processed. I'm not certain that middleware ordering is the cause, but it's my best guess. Is there a way to fix this with sentry-sdk? Perhaps the answer is to use configure_scope() and update scope.user, however some of the middleware I'm using is third party, which I can't easily modify without forking. -
How load all the css and js files in django app?
I have webpack running to do my frontend development. I serve js file while development and that's file. But when I go for production, I run webpack with some configurations and it outputs bunch js files and css files with chunk hash. Now I want to dynamically link all the css files and js files in my template. How do I do that in django? If there a for loop I can run on os.listdir, and use and if statement to link css and js differently?? Or should I create a custom template tag?? Looking for a better approach and stable way of doing this. -
Django FileSystemStorage. Access to files saved on External Hard Drive
I have set my FileSystemStorage in location='E:/'. Its an external Hard Drive. I'am working in local with a simple app in Django. It's working when I upload files. But I can't access from templates to files after that. Using the same path. My model: fs= FileSystemStorage(location='E:/repositorio/') pdf_files = models.FileField(storage=fs, blank=False, null=False) -
Get id of object with maximum field in Django
Let's say that in Django I have a Publisher model and a Book model connected to it in a one-to-many relationship. And let's further say that the book has a times_checked_out field. How do I get back a queryset of the ids of the most checked out book for each publisher? What I cannot do is something like Publisher.objects.annotate(max_book = Max('books__times_checked_out')) because that returns the maximum check-outs, not the book with the maximum check-outs. I also cannot think how to add in a Case(When()) in a helpful way. What is the way to do this in Django? -
What is the difference between request.META.get('REMOTE_ADDR') and request.META.get('HTTP_X_FORWARDED_FOR')?
I added the ip into my model and view with this function that I found on SO: def get_ip_address(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip and in the form: up = form.save(commit=False) up.ip_address = get_ip_address(request) up.save() but I want to know what is the difference between what I did and if I do it directly like this: up = form.save(commit=False) up.ip_address = request.META.get('REMOTE_ADDR') up.save() -
Error using Textfield and charfield model in Django
I have been trying to use Textfield in class but the suggestions just does not show up. Instead i receive an error in my Cmd console. This was even the case while using CharField. Below is my code: from django.db import models from django.db.models import CharField from django.db.models import Textfield from datetime import datetime class Posts(models.Model): title = models.CharField(max_length=200) body = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) This is the error i get in my CMD: Exception in thread django-main-thread: Traceback (most recent call last): File "d:\python\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "d:\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\USER\Envs\py1\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\USER\Envs\py1\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\USER\Envs\py1\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\USER\Envs\py1\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\USER\Envs\py1\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\USER\Envs\py1\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\USER\Envs\py1\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\USER\Envs\py1\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "d:\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen … -
Calling a django view function through jQuery Ajax
I'm trying to have two views called from inside my javascript function, which are increment and decrement, which are supposed to change values within one of my models. Both these views have another argument besides request (amount). I think the best way to get this system to work is through ajax, but I cannot figure out how to make the call with multiple parameters. Here is my javascript $('#redButton').click(function (e) { var amount = $("#amount").val(); var totalCoins = "{{ user.profile.coins }}"; if(amount <= totalCoins && amount > 0) { //decrement total coins by amount var choice = 0; spinWheel(choice, amount); } return false; }); $('#blackButton').click(function (e) { var amount = $("#amount").val(); var totalCoins = "{{ user.profile.coins }}"; if(amount <= totalCoins && amount > 0) { //decrement total coins by amount var choice = 1; spinWheel(choice, amount); } return false; }); $('#greenButton').click(function (e) { var amount = $("#amount").val(); var totalCoins = "{{ user.profile.coins }}"; if(amount <= totalCoins && amount > 0) { //decrement total coins by amount var choice = 2; spinWheel(choice, amount); } return false; }); function spinWheel(choice, amount){ e.preventDefault(); stoping = false; // Random between 1 and 10 var itemSelected = Math.floor((Math.random() * 11)); var $jump = $(this); //$jump.html('Jumping … -
(Cookiecutter-django) Docker deployment on Raspberry Pi 4: Why does the build fail?
I am trying to deploy a small Django app dockerized using cookiecutter-django on a Raspberry Pi 4 running Rasbian (Linux raspberrypi 4.19.97-v7l+). I would say that my setup is pretty vanilla and am hoping I am not the only one who ran into this. cookiecutter==1.7.2 django==3.0.5 The build fails and I have tried to install: sudo apt-get install python3-dev libffi-dev libssl-dev openssl-dev build-essential Didn't help though. I keep getting the following output when running: $ docker-compose -f production.yml build OUTPUT redis uses an image, skipping Building postgres Step 1/4 : FROM postgres:11.3 ---> 9ff9cc2df728 Step 2/4 : COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenance ---> Using cache ---> 2ee1f827b4bb Step 3/4 : RUN chmod +x /usr/local/bin/maintenance/* ---> Using cache ---> 861e846adc6b Step 4/4 : RUN mv /usr/local/bin/maintenance/* /usr/local/bin && rmdir /usr/local/bin/maintenance ---> Using cache ---> cb799d694f3e Successfully built cb799d694f3e Successfully tagged mysite_production_postgres:latest Building django Step 1/18 : FROM python:3.8-slim-buster ---> a852e8fce952 Step 2/18 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> bfea44a6a6a9 Step 3/18 : RUN apt-get update && apt-get install -y build-essential && apt-get install -y libpq-dev && apt-get install -y gettext && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false && rm -rf /var/lib/apt/lists/* ---> Using cache ---> df6cdd6db821 Step 4/18 : RUN addgroup … -
Why does django return the data I submitted as the HttpResponse?
So I am making Angular 8 and Django project. The scenario is that from a form in Angular, data is sent to Django to store it in a database. class NewProfileView(viewsets.ModelViewSet): queryset = NewProfile.objects.all() serializer_class = NewProfileSerializer def post(self,request,*args,**kwargs): email = request.data['email'] password = request.data['password'] username = request.data['username'] NewProfile.objects.create(email=email,password=password,username=username) return HttpResponse({'message':'Registered Successfully'},status=200) The above represents my Django view. Now, seeing this, for a successful creation, I should get the response as 'Registered Successfully'. But what I get is the data I submitted in JSON format (basically a dictionary. I don't really know if it is json). Why is it happening? export class PostService { private url = 'http://localhost:8000/login/'; constructor(private httpClient:HttpClient) {} getPosts(data){ return this.httpClient.get(this.url+'?email='+data.email+'&password='+data.password); } create(url,post){ return this.httpClient.post<any>(url,post); } } This is what is there in my angular service. onSubmit(){ console.log(this.userForm); this.service.create('http://localhost:8000/profile/',this.userForm) .subscribe(response=>{ console.log(response); }); This is the code in my component.ts file. P.S.- I know I'm storing the passwords wrong way. But its just for debugging purposes. -
How to extend JWTAuthentication in django- rest-framework
I created CustomAuthentication class, this class extend JWTAuthentication class. I put this class in file auth.py and same location with settings.py. in settings.py i modify: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } to REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( auth.CustomAuthentication', ), } But it it doest not work, it throws "Could not import 'auth.CustomAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: Module "auth" does not define a "CustomAuthentication" attribute/class." Here is content of auth.py: from rest_framework_simplejwt.authentication import JWTAuthentication class CustomJWTAuthentication(JWTAuthentication): is_valid = True What is wrong here? please help. Thank you very much. -
TypeError: 'DetailFilter' object is not iterable - How do I transfer the filtered model fields as a dynamic/dependable list to Front End in Django?
I am new to Django and don't know much things about it yet. The summary of what I want to do is below: I have User (Django's Default) Model for a student user and a Detail Model. Detail Model has a ForeignKey of User Model and contains fields such as subject, mid_term_marks, skype_session_attendance etc of the student. I want to forward the subject's list of a user (student) to the Front End users/performance_calculator.html. User will select a subject from the list and click the Calculate Button, and next the system will take that input (from user/student) and fetch the other fields (such as mid_marks, skype_session_attendance) of Detail Model filtered by the username and the subject name (the input), finally the fetched detail is passed as parameters to the fuzz_logic() function, that calculates the performance and show the result to Front End in the form of Django Messages. I have done all of the functionality, except forwarding the dynamic dependable list of subjects to Front End and using the input to fetch the other fields of Detail Model. I tried to pass the dynamic and dependable list to the Front End using django-filter, but I am getting the TypeError My views.py … -
"Invalid block tag on line 14: 'empty', expected 'endblock'. Did you forget to register or load this tag?"
I'm receiving the following error in Django: "Invalid block tag on line 14: 'empty', expected 'endblock'. Did you forget to register or load this tag?" topic.html Template: {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <ul> <% for entry in entries %> <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %} -
Django Rest Framework: how to build an appointment booking system
I want to an application like appointy.com where users can book a session and select their time slots. I will be using DRF for this, I was concerned about how I could represent the calendar?? For setting availability etc. I was thinking of creating a slot model. With a start date and time for the next 30 days. So this is a list of all available slots for next 30 days. Additionally, the slot model will have available_users list. Which will be an array of assignee available. If the user doesn't want to be available for that time slot he can just toggle it via a button and we will remove that user from the array of assignees. If no assignee available then that slot is full. How does this solution sound? Does it sound like a doable solution? -
Django: Queryset filter with multilevel nesting
The use case is the following: I'm trying to retrieve all Prospects that were generated under a Manager. The models are as follow: Prospect <---> Appointment <---> Staff <---> Manager. As you can see, there is no direct relationship between a prospect and a manager so I'm forced to do a nested, reverse lookup through the other models. For example, I try to retrieve the prospects generated under Manager id=2 through the following query: Prospect.objects.filter(appointment=Appointment.objects.filter(staff__manager=Manager.objects.get(user=2))) But then I get the following error: ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. Any hint about what's wrong with my query? Models.py class Prospect(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=40) phone = models.CharField(max_length=20) class Appointment(models.Model): appointment_time = models.DateTimeField() unit = models.ForeignKey(Unit, on_delete=models.CASCADE) staff = models.ForeignKey(Staff, on_delete=models.CASCADE) prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE) status = models.BooleanField(default=False) class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) manager = models.ManyToManyField(Manager, through=Manager.staff.through, related_name='+', blank=True) unit = models.ManyToManyField(Unit, through=Unit.staff.through, related_name='+', blank=True) profile_pic = models.ImageField(upload_to='profile_pic', blank=True) class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) staff = models.ManyToManyField('Staff', related_name='+', blank=True) company = models.CharField(max_length=40) logo = models.ImageField(upload_to='logo_image', blank=True) -
Username field removal at login in DJANGO(REST)
I recently wanted to remove the username field, which is required for registration, in my Django REST API. So I added the following lines in my settings.py: ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False Username is no longer required at registration. But when a user tries to login it still requires a username otherwise I will get a {'non_field_errors': ['Unable to log in with provided credentials.']} as response. I also noticed that when a user registers with a email address only, django takes all the characters before the @ sign in the email address, and saves that as username in the database. My question is: How can I also remove the username at login. So the only thing needed to login is the email and password. I am trying to achieve this without making custom user models. A example of the current situation at registration and login, respectively: #Registration registartion_info ={"email":"achie@gmail.com", "password1":"password","password2":"password"} registration_url = 'http://127.0.0.1:8000/users/registration/' response = requests.post(url,json= registartion_info) #Login login_info ={"username":"achie","email":"achie@gmail.com", "password":"password"} login_url = 'http://127.0.0.1:8000/users/login/' response = requests.post(url,json= login_info) A example of how I want the registration and login to be, respectively: #Registration registartion_info ={"email":"achie@gmail.com", "password1":"password","password1":"password"} registration_url = 'http://127.0.0.1:8000/users/registration/' response = requests.post(url,json= registartion_info) #Login … -
DJANGO Message error when i try to show uploaded file in admin ,in change page
In Admin change_page Model when I try to click on the link to display next to the field to display the file already uploaded, it displays the following error see image error when I click in this link to show Pdf file or any file My Model.py class InstrumentJuridiqueDoc(models.Model): # this model is inline in other model cooperationMultilaterale = models.ForeignKey(CooperationMultilaterale, on_delete=models.CASCADE,null=True,blank=True) cooperationBilaterale = models.ForeignKey(CooperationBilaterale, on_delete=models.CASCADE,null=True,blank=True) calip = models.ForeignKey(CooperationAvecLesInstitutionsPubliques, on_delete=models.CASCADE,null=True,blank=True) arj = models.FileField(verbose_name = 'Arabe',blank=True,null=True, help_text='Formats acceptés : PDF, JPG, JPEG, PNG',validators=[FileExtensionValidator(['pdf','JPG', 'JPEG', 'PNG'])]) frj = models.FileField(verbose_name = 'Français',blank=True,null=True, help_text='Formats acceptés : PDF, JPG, JPEG, PNG',validators=[FileExtensionValidator(['pdf','JPG', 'JPEG', 'PNG'])]) enj = models.FileField(verbose_name = 'Anglais',blank=True,null=True, help_text='Formats acceptés : PDF, JPG, JPEG, PNG',validators=[FileExtensionValidator(['pdf','JPG', 'JPEG', 'PNG'])]) esj = models.FileField(verbose_name = 'Espagnol',blank=True,null=True, help_text='Formats acceptés : PDF, JPG, JPEG, PNG',validators=[FileExtensionValidator(['pdf','JPG', 'JPEG', 'PNG'])]) amj = models.FileField(verbose_name = 'Amazigh',blank=True,null=True, help_text='Formats acceptés : PDF, JPG, JPEG, PNG',validators=[FileExtensionValidator(['pdf','JPG', 'JPEG', 'PNG'])]) autrej = models.FileField(verbose_name = 'Autre langue',blank=True, null=True,help_text='Formats acceptés : PDF, JPG, JPEG, PNG',validators=[FileExtensionValidator(['pdf','JPG', 'JPEG', 'PNG'])]) My url.py Project import django from django.conf.urls.i18n import i18n_patterns from django.urls import path from django.conf.urls import include, url from django.contrib import admin urlpatterns = i18n_patterns( path('admin/', admin.site.urls), url(r'^chaining/', include('smart_selects.urls')), # If no prefix is given, use the default language prefix_default_language=True ) how can i solve this … -
How to retrieve data from database using jQuery Ajax + Django MTV
I would like to fetch data from my database on document.ready using jQuery.ajax and Django MTV. This is my setup which returns jquery.min.js:2 GET http://127.0.0.1:8000/terminal/getStocksAvailable/ 500 (Internal Server Error) jQuery async database call // on pageload query availableStocks via jQuery $(document).ready(function() { $.ajax("getStocksAvailable/", { method: "GET", async: "True", dataType: "json", success: function (response) { var stocksAvailable = response; console.log(stocksAvailable); } }); }); urls.py from terminal.views import getStocksInfo, getStocksAvailable urlpatterns = [ [...] # database fetch views path('terminal/getStocksAvailable/', getStocksAvailable), ] views.py from feeder.models import StocksAvailableModel def getStocksAvailable(request, *args, **kwargs): stocksAvailable = serializers.serialize('json', StocksAvailableModel.objects.values('description')) return HttpResponse(StocksAvailable) -
My server is running perfectly but the browser window shows the site cant be reached .how do i resolve it?
The first time the server was running perfectly and I got the output as well on the browser window. Next time I ran the server it showed the error the site can't be reached on the browser window. I tried all the solutions that were available but it is still not working. How do I resolve this? -
What the usages of OneToOne for different cases are?
I use Django + PostgreSQL. I have 3 models: GeneralModel, Model1, Model2. What are differences between these architectural designs? class GeneralModel(models.Model): ... model1 = models.OneToOneField(to=Model1,) model2 = models.OneToOneField(to=Model2,) ... And class Model1(models.Model): general_model = models.OneToOneField(to=GeneralModel,) class Model2(models.Model): general_model = models.OneToOneField(to=GeneralModel,) Which situations are these cases used for? What is the best for performance? -
How best to structure database for time-series data in django
I'm fairly new to fullstack development, and I've run into a bit of a problem. I'm building a website using django (v3.06) where users will upload CSV data to the database. The data comes from optical sensors in the field, and there are two primary "types" of files that will be uploaded: one with a filter, and one without. The general structure of the CSV files is: no filter: UTC YYYY-MM-DDTHH:mm:ss.fff;YYYY-MM-DDTHH:mm:ss.fff;Celsius;Volts;mag/arcsec^2;Init/Subs;n;mag/arcsec^2;n;MoonPhaseDeg;MoonElevDeg;MoonIllum%;SunElevDeg 2020-02-16T04:43:30.000;2020-02-15T21:43:30.000;20.6;4.96;17.30;1;47488;16.37;112295;-93.2;-45.331;47.2;-44.135 2020-02-16T04:45:06.000;2020-02-15T21:45:06.000;20.3;4.96;18.20;1;20777;17.74;31798;-93.2;-45.025;47.2;-44.444 ... with filter: UTC YYYY-MM-DDTHH:mm:ss.fff;YYYY-MM-DDTHH:mm:ss.fff;Celsius;Volts;mag/arcsec^2;Init/Subs;MoonPhaseDeg;MoonElevDeg;MoonIllum%;SunElevDeg 2020-02-15T17:52:59.000;2020-02-15T10:52:59.000;20.9;5.03;21.14;0;-87.5;7.222;52.2;35.690 2020-02-15T17:55:07.000;2020-02-15T10:55:07.000;19.9;4.97;21.16;1;-87.5;6.836;52.1;35.924 ... They are very similar except for a few extra columns in the filtered file. There are multiple "sites" that will each have two sets of data: one filtered and one unfiltered. Users will be assigned sites that they have permission to upload for, and will be provided an interface to add data for those sites. I have a few questions about how to handle this on the backend. Right now, I have a model Site that has a code as an attribute. Admins will be able to create new sites through the built-in django.admin interface and modify their code attribute. Should I create two new models, one for each data type (filtered and unfiltered)? What would this class look … -
Re-render page from JS Django Template
I have an endpoint that renders a template that has a list of movies On the page, there is a button called "Add movie" and an input field to add the name of the movie. When the button is pressed, I want to add a movie of the name to the list of movies and re render the page. Right now, I am doing it all in JS, with a fetch request, but I can't re render the page like this. How could I achieve the effect I want? -
List of Freeware IDE for PHP and Django
I wanna know . As Eclipse is best but is there any IDE with Inbuilt server so testing will be easy. -
Django DRF nested serializers are not linked
I'm trying to build an API for a picture gallery using Django and Django Rest Framework for the API. I have set up the following two models: class Album(models.Model): name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) start_date = models.DateField() end_date = models.DateField(null=True, blank=True) parent_album = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE ) class Picture(models.Model): path = models.ImageField() album = models.ForeignKey('Album', on_delete=models.CASCADE) For the serializers, I have defined the following, using the official Django DRF doc: class PictureSerializer(serializers.ModelSerializer): class Meta: model = Picture fields = '__all__' class AlbumSerializer(serializers.ModelSerializer): pictures = PictureSerializer(many=True, read_only=True) class Meta: model = Album fields = '__all__' Now, I have some objects already defined, so I wanted to try in a shell: >>> album = Album.objects.get(pk=1) >>> len(Picture.objects.filter(album__exact=Album.objects.get(pk=1))) 3 >>> AlbumSerializer(instance=album).data {'id': 1, 'name': 'First album', 'description': '', 'start_date': '2019-08-15', 'end_date': None, 'parent_album': None} >>> AlbumSerializer() AlbumSerializer(): id = IntegerField(label='ID', read_only=True) pictures = PictureSerializer(many=True, read_only=True): id = IntegerField(label='ID', read_only=True) path = ImageField(max_length=100) album = PrimaryKeyRelatedField(queryset=Album.objects.all()) name = CharField(max_length=100) description = CharField(allow_blank=True, allow_null=True, required=False, style={'base_template': 'textarea.html'}) start_date = DateField() end_date = DateField(allow_null=True, required=False) parent_album = PrimaryKeyRelatedField(allow_null=True, queryset=Album.objects.all(), required=False) You will notice that there's no pictures in the serialized data, but the fields is there when I print the serializer, and thaaaaat's …