Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3 installed_app shows ModuleNotFoundError in custom folders
while using customized folders, I am having a trouble using my app correctly in Django 3. My folder levels are: --manage.py --mdtour ----settings -------settings.py ----apps ------core ----templates In core app my apps.py file is: from django.apps import AppConfig class CoreConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'core' But i cannot use my app in Django 3. In settings file I tried to add the app in two ways: INSTALLED_APPS = [ 'mdtour.apps.core.apps.CoreConfig.core' ] The error I get: `ModuleNotFoundError: No module named 'mdtour.apps.core.apps.CoreConfig'; 'mdtour.apps.core.apps' is not a packa`ge or INSTALLED_APPS = [ 'mdtour.apps.core.apps.CoreConfig.core' ] this time I get: django.core.exceptions.ImproperlyConfigured: Cannot import 'core'. Check that 'mdtour.apps.core.apps.CoreConfig.name' is correct. How can I correct this error? Thanks -
Frontend stops responding, when using WebSockets with RabbitMQ turned off
I have frontend on VueJS and backend on Django. Some functions are using sockets to contact with backend using RabbitMQ. Example: this.healthCheckWs = new WebSocket(`${wsProtocol}://${host}/health_check_bo/?token=${this.$auth.getToken('local')}`); this.healthCheckWs.onclose = async function(event) { setTimeout(() => { this.connectsCheckHealthWs(); }, 5000); }.bind(this); But if RabbitMQ will be off and you try to use this, website freezes. I can't do anything. When you turn RabbitMQ on, message from front arrives and everything works good. So, my question is: Is there a way to terminate WebSocket connection, if it is not responding, and continue your work on site? Thanks everyone -
Getting 400_BAD_REQUEST when i'm trying to return data from django endpoint
Currently i'm trying to make an APIView that returns data like this: ["question_text": "answer_text", "question_text": "answer_text"] ... So, basically i want to make that in order to get the current user quizzes attempts, with the next REQUEST BODY: "quizname" my UserAnswer model looks like this: class UserAnswers(models.Model): user = models.ForeignKey(User, related_name='User', on_delete=models.CASCADE) answer = models.ForeignKey(Answer,related_name='Answer', on_delete=models.DO_NOTHING) Answer model : class Answer(models.Model): question = models.ForeignKey(Question, related_name='answer', on_delete=models.CASCADE) answer_text = models.CharField(max_length=255, default='', verbose_name="Answer") is_right = models.BooleanField(default=False) is_checked = models.BooleanField(default=False) def __str__(self): return self.answer_text Question model: class Question(models.Model): quiz = models.ForeignKey(Quiz, related_name='question', on_delete=models.CASCADE) question_text = models.CharField(max_length=255, default='', verbose_name="Question") def __str__(self): return self.question_text Basically, the UserAnswers table contains a FK to Answer, that contains a FK to Question, that contains a FK to quiz I tried to do this in my APIView: class UserAnswersView(APIView): permission_classes = [IsAuthenticated] def get(self,request): try: data = request.data # quizName toReturn = {} userAnswers = UserAnswers.objects.filter(user=request.user) # Getting all entries from UserAnswers table WHERE user = request.user for userEntry in userAnswers: # parsing al entries answer = Answer.objects.get(answer_text=userEntry.answer) # Getting the answer of every entry question = Question.objects.get(id=answer.question_id) # Getting the question of every entry quiz = Quiz.objects.get(id=question.quiz_id) # Getting the quiz of every entry if (quiz.category == request.data): … -
Sending an Excel file from postoffice
I am trying to send a base64-encoded excel file through Django post_office lib. Here's the code that I have now An example of encoded content: body = 'UEsDBBQAAAAIAAAAPwBhXUk6TwEAAI8EAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbK2Uy27CMBBF9/2KyNsqMXRRVRWBRR/LFqn0A1x7Qiwc2/IMFP6+k/BQW1Gggk2sZO7cc8eOPBgtG5ctIKENvhT9oicy8DoY66eleJ8853ciQ1LeKBc8lGIFKEbDq8FkFQEzbvZYipoo3kuJuoZGYREieK5UITWK+DVNZVR6pqYgb3q9W6mDJ/CUU+shhoNHqNTcUfa05M/rIAkciuxhLWxZpVAxOqsVcV0uvPlFyTeEgjs7DdY24jULhNxLaCt/AzZ9r7wzyRrIxirRi2pYJU3Q4xQiStYXh132xAxVZTWwx7zhlgLaQAZMHtkSElnYZT7I1iHB/+HbPWq7TyQunURaOcCzR8WYQBmsAahxxdr0CJn4f4L1s382v7M5AvwMafYRwuzSw7Zr0SjrT+B3YpTdcv7UP4Ps/I8dea0SmDdKfA1c/OS/e29zyO4+GX4BUEsDBBQAAAAIAAAAPwDyn0na6QAAAEsCAAALAA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MUAAAACAAAAD8A05PycyQBAABQAgAAEQAAAAAAAAAAAAAAgIGkDwAAZG9jUHJvcHMvY29yZS54bWxQSwECFAMUAAAACAAAAD8AXrqn03cBAAAQAwAAEAAAAAAAAAAAAAAAgIH3EAAAZG9jUHJvcHMvYXBwLnhtbFBLBQYAAAAACgAKAIACAACcEgAAAAA=' The the code itself: from django.core.files.base import ContentFile from post_office import mail attachments = [{ 'name': 'example.xlsx', 'body': ContentFile(body), 'mimetype': 'application/vnd.ms-excel'}] mail.send(to, from, attachments=attachments, **params) The problem is that the content in the actual file that is sent by email looks like this: What could be the reason for that ? -
(Best practice) Handling multiple simple forms relating to one object in one view
I have a working solution but I would like to know if this is the best way to do it. I have three models: Meal, Indgredient and IngredientWithQuantity (IwQ). Meal can have multiple IwQ and Ingredient can have multiple IwQ. I created a simple view where you can create Meal (one form), add IwQ (another form) and if needed go to another view to create new Ingredient (yet another form) and then come back to this view where you still will edit the previous Meal. The only problem is keeping the information about the meal that is being created. I am doing this through html hidden input field where I store an information about meal_id. I am simply not sure if this is the best way to exchange this information, because at times it seems a little off. Could some take a look and tell me if maybe this could be achieved in a more effective manner? Thanks, models.py class Ingredient(models.Model): name = models.CharField(max_length=200, null=True) #brand #WW def __str__(self): return self.name class Meal(models.Model): EVALUATION = ( ('Perfect', 'Perfect'), ('Average', 'Average'), ('Bad', 'Bad') ) name = models.CharField(max_length=200, null=True) time_eaten = models.DateTimeField(auto_now=False, auto_now_add=False, default=timezone.now, null=True) # time_of_day = jaki posiłek? bolus_n = … -
How to create table with migrate after drop table from postgresql in django?
Using PostgresSQL and Django, I dropped two tables from postgresql manually. drop table ... Then I did make migrations and migrate. But my tables are not recreated. Can not access from shell_plus. Also in this page, django return relation 'table name' does not exists. I want to makemigrations and migrate to create tables again. How can I solve my issue ? -
How to upload multiple files in Django Admin?
I have the following two models. class Event(models.Model): title = models.CharField(max_length=120) ... def __str__(self): return self.title class EventPhotos(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) photo = models.ImageField(upload_to='events/') What I am trying to do is to use the default admin panel to select multiple images for upload. My current code works as I want it to, I create an event then open the EventPhotos model, select the event I just created and I have the select file button which I can use to add photos, but the thing is, Django lets me add only 1 photo! I want to add multiple photos. Thanks in advance guys, would appreciate it if you help me out. -
django get file size and put it in serializer
serializers.py class ModFileSerializer(serializers.ModelSerializer): size = serializers.CharField(default=os.path.getsize('file'), max_length=16) class Meta: model = models.ModFile fields = '__all__' read_only_fields = ( 'size', ) models.py class ModFile(models.Model): downloads = models.IntegerField(default=0) file = models.FileField(upload_to='mods/') created_at = models.DateTimeField(auto_now_add=True) Here I have a serializer for the ModFile model and the only thing that's missing is the file's size, I know os.path.getsize() needs the exact location of the file so how do I actually access the file field from the model in order to pass in the getsize() function or is there a better way to do it? -
Django tests serializers: "django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N" and "django.core.exceptions.AppRegistryNotReady"
I am testing my serializer in Django Rest Framework with pytest. Here are my modules versions: python 3.8.8 django==3.2.5 djangorestframework==3.12.4 pytest==6.2.4 Here is my test_serializers.py file: from my_app.serializers import my_serializer class TestMySerializer: def setup(self): self.serializer = my_serializer @pytest.mark.parametrize( "input", [ { "a": ["test"], "b": ["test"], "c": ["test"], }, ], ) def test_valid_serializer(self, input): ser = self.serializer(data=input) assert ser.is_valid() @pytest.mark.parametrize( "input", [ {"a": ["test"]}, ], ) def test_invalid_formats(self, input): ser = self.serializer(data=input) assert not ser.is_valid() And of course my serializers.py file is: class my_serializer(Serializer): a = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True)) b = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True)) c = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True)) The test_valid_serializer test pass without any problem because the input is valid for the serializer. OK ✅ The test_invalid_formats should pass as well because the input is not valid for the serializer. But unfortunately this test doesn't pass and I have this error that occurs: django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Following this stackoverflow post, I add a DJANGO_SETTINGS_MODULE variable pointing to my settings.py file. When I try again my test, the following error occurs: django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps … -
Word Quiz - How to properly implement VIEW and HTML page Django
I am building a website for learning vocabulary in English. The website let users add words in English and an association on how to remember the word in Hebrew. I want to add a word quiz function. The user gets 4 random words from the database and has to choose the right word and if he answered correctly he gets the right answer I get a little tricky how to implement it and would be happy to help. What do I do wrong when I click on a word I get nothing? (I try to get the "message") def practice(request): words_list = Words.objects.filter(approved= True) # Take all the words that approved random_word_to_guess = random.choice(words_list) word_1 = random.choice(words_list) word_2 = random.choice(words_list) word_3 = random.choice(words_list) if request.method == "POST": guess = request.POST.get("guess") if request.POST.get("correct"): message = "Correct answer" return render(request, "practice.html", {'message': message},{'guess':guess}) else: message = "wrong answer" return render(request, "practice.html", {'message': message},{'guess':guess}) return render(request, "practice.html", {'word_1':word_1,'word_2':word_2,'word_3':word_3,'random_word_to_guess':random_word_to_guess,}) <h1> Practice </h1> </br> {{random_word_to_guess.English_word}} </br> </br> </br> <form name = "guess" action ="" method="post" class="from-inline"> <button name = "uncorrect" type="button" value="Submit" class="btn btn-primary">{{word_1.Hebrew_word}}</button> <button name = "uncorrect" type="button" value="Submit" class="btn btn-primary">{{word_2.Hebrew_word}}</button> <button name = "uncorrect" type="button" value="Submit" class="btn btn-primary">{{word_3.Hebrew_word}}</button> <button name = "correct" type="button" … -
Django channels web chat not updating live
I built a live web chat that has 2 people interacting, the user and a friend. Everything works except I need to refresh it to actually see a new text. I have no idea what is not working, as I've done something similar before but with group chat and not 1 - 1. Here is the code: Consumer: class PrivateChatConsumer(WebsocketConsumer): # Fetch messages def fetch_messages(self, data): self.friend = self.scope['url_route']['kwargs']['friend'] self.user = self.scope["user"] messages1 = PrivateMessage.objects.all().filter(author__username=self.friend, friend__username=self.user) messages2 = PrivateMessage.objects.all().filter(author__username=self.user, friend__username=self.friend) messages = list(chain(messages1, messages2)) messages.sort(key=lambda x: x.timestamp, reverse=False) content = { 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) # New message def new_message(self, data): self.friend = self.scope['url_route']['kwargs']['friend'] author = data['from'] author_user = User.objects.get(username=author) friend = User.objects.get(username=self.friend) message = PrivateMessage.objects.create( author=author_user, content=data['message'], friend=friend ) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) # returns a list of json objects def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'author': message.author.username, 'content': message.content, 'friend': str(message.friend), 'time_stamp': str(message.timestamp), 'image': message.author.profile.image.url, 'id': message.id, 'is_online': message.author.profile.is_online } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message, } def connect(self): self.friend = self.scope['url_route']['kwargs']['friend'] self.room_group_name = 'chat_%s' % self.friend # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def … -
How can I import a django model from one project into another project, both the projects use same database
File structure - root/ project1/ app1/models.py project1/ project2/ app2/views.py project2/ Now I want to import a model from project1/app1/models.py into project2/app2/views.py . How can I achieve this? I had a larger django project earlier but I have to split the project into different micro-services due to dependency issues. -
Setting X-Frame-Options header for static HTML file in Django
In my Django project, I am serving an HTML file from the static folder. This HTML file is basically being used to render PDFs on the site. I want to set the X-Frame-Options header for this HTML file and, if possible, all the static files served from the Django server. I have already set the 'django.middleware.clickjacking.XFrameOptionsMiddleware' middleware in my settings.py file. This is only applying the X-Frame-Options to my views and not to my static files. Any suggestions on how to configure the X-Frame-Options for static files? Note: This header is needed for Clickjacking Protection and I need to make sure this particular HTML file cannot be clickjacked. -
django prefetch_related() attribute error
How to properly user prefetch_related with ManyToMany relation my model: class Subject(models.Model): subject_name = models.CharField(max_length=150) subject_code = models.CharField(max_length=50) year = models.ForeignKey(YearLevel, null=True, on_delete=models.SET_NULL) units = models.CharField(max_length=10) def __str__(self): return self.subject_name + ' ' + '(' + self.subject_code + ')' class Student(models.Model): student = models.ForeignKey(settings.AUTH_USER_MODEL, limit_choices_to= Q(is_student=True), on_delete= models.CASCADE) enrolled_subject = models.ManyToManyField(Subject) my view: def home(request): verses = VerseOfTheDay.objects.all() news = Announcement.objects.all() student_grade_form = AddStudentGradeForm() students = Student.objects.all().prefetch_related('subject_set') context = { "verse": verses, 'news': news, 'form': student_grade_form, 'students': students, } return render(request, 'sample.html', context) my html: {% for student in students %} <p> <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapse{{forloop.counter}}" role="button" aria-expanded="false" aria-controls="collapse{{forloop.counter}}"> {{student.student}} </a> </p> <div class="collapse" id="collapse{{forloop.counter}}"> <div class="card card-body"> {% for subject in student.subject_set.all %} {{subject.subject}} {% endfor %} </div> </div> {% endfor %} I am getting an error: AttributeError at / Cannot find 'subject_set' on Student object, 'subject_set' is an invalid parameter to prefetch_related() -
Django app does not display content, how to fix it?
The Blog button does not display information about the number of blogs written and the blogs themselves (when adding a blog number, nothing appears in the address bar.https://i.stack.imgur.com/Zv700.jpg -
Receiving "Select a valid choice. That choice is not one of the available choices." while using Djongo ForeignKey with Django
I got this weird error in Django Admin while using the ForeignKey from djongo.models. Not sure if I did anything wrong in the models file. Error Message Image Machine/models.py from djongo import models class Machine(models.Model): _id = models.ObjectIdField(primary_key=True) machine_type = models.TextField(null=False) machine_description = models.TextField(null=False) def __str__(self): return self.machine_type # Create your models here. class Errorcode(models.Model): _id = models.ObjectIdField(primary_key=True) code_name = models.TextField(null=False) machine_type = models.ForeignKey('Machine', on_delete=models.CASCADE) description = models.TextField(null=False) instruction = models.TextField(null=False) def __str__(self): return self.code_name class AdditionalFile(models.Model): error_code = models.ForeignKey('Errorcode', on_delete=models.CASCADE) file_name = models.TextField(blank=True) file_path = models.FileField(blank=True, upload_to='static/asset') def __str__(self): return self.file_name If any other files is needed to inspect the problem, I can add the code here. -
Change table name for django model in runtime
Example Django model with table name: from django.db import models class MyModel(models.Model): class Meta: managed = False db_table = "default_table_name" than i have a few filters(in the real world more than 1): qs = MyModel.objects.filter(id=42) Question How can i change model name ("default_table_name") dynamically, in runtime, request can have 'table_name' in 'query_params'? It doesn't work: 1 I can't change "db_table" directly: qs.model._meta.db_table = request.query_params.get('table_name’) 2 Raw query is too complicated. I don't want to convert all filters to SQL by myself. MyModel.objects.raw('SELECT * FROM %s WHERE id=42', [request.query_params.get('table_name’)]) -
Authenticating AJAX requests in Django for an already logged in user
I have a long form, so in order to prevent the dreaded retype all fields cause cat pounced on the power cord, I wish to save fields everytime a field is changed via AJAX. Its easy to set up an Ajax view that does not require authentication, however these forms do require authentication. A user would have already logged in when editing the form. So I have been reading about Django REST framework, which talks a lot about tokens. I am guessing this is for server to server comunication? When talking user to server, could one not just re-use the CRSF token in the form, and in the backend authenticate by checking the CRSF token like this: from django.middleware.csrf import CsrfViewMiddleware def check_csrf(request): reason = CsrfViewMiddleware().process_view(request, None, (), {}) if reason: # CSRF failed raise PermissionException() def AjaxFormChange(generic.View): def post(self, request): check_csrf(): # Do something to the model, e.g. obj = Foo.objects.get(id=request.POST['id']) obj.foo = request.POST['foo'] obj.save What is the recommended way of authenticating AJAX requests in Django for an already logged in user? -
CreateView and UpdateView based class are not working in Django Project
I have Django in Which there is app called Listing and it's model as follows but CreateView and UpdateView are not woking for model. I am also using mixins but I have implemented Custom User , so is that cuases a problem? ListingCreateView is working properly in frontend but new Listing in database is not created! Any other user is updating listing of others, UserPassesTestMixin not working import uuid from django.db import models from django.urls import reverse from django.contrib.auth import get_user_model User = get_user_model() class Listing(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) owner = models.ForeignKey(User, on_delete=models.CASCADE) ...other fields CreateView class ListingCreateView(LoginRequiredMixin, CreateView): model = Listing fields = blah blah blah def form_valid(): form.instance.owner = self.request.user return super().form_valid(form) UpdateView class ListingUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Listing fields = blah blah blah def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) def test_func(self): listing = self.get_object() #print(self.request.user, listing.owner) if(self.request.user == listing.owner): return True else: return False Tysm for solving in advance! -
I have an error on django athentication system with authenticate () method
I have an issue with autenticate () method , please help me. it return to me '' the view didn't return an httpresponse . It returned none instead. def registrazione (request): if request.method == 'POST': form = FormSito(request.POST) if form.is_valid(): username = form.cleaned_data ["username"] password = form.cleaned_data ["password"] User.objects.create_user ( username = 'username', password = 'password' ) user = authenticate (request,User) else: form = FormSito() context = { form : 'form' } return render (request,"registration/form/registrazione.html", context) -
I am trying to write a factory. The error is mentioned below
SEPARATOR.join((model_name, attr)) for attr, value in factory_class._meta.declarations.items() if is_dep(value) AttributeError: 'Options' object has no attribute 'declarations' class Motors(models.Model): #models abc = models.ForeignKey( ABC, on_delete=models.CASCADE ) xyz = models.ForeignKey( XYZ, on_delete=models.CASCADE ) rejected_at = models.DateTimeField(auto_now_add=True) class MotorsFactory(factory.django.DjangoModelFactory): #factories abc = factory.SubFactory(ABCFactory) xyz = factory.SubFactory(XYZFactory) class Meta: model = Motors from pytest_factoryboy import register from .factories import MotorsFactory register(MotorsFactory) #conftest -
How to change function of Django source in our code
I want all inactive users also can login, in dajngo/contrib/auth/backends.py line 51 we have: def user_can_authenticate(self, user): """ Reject users with is_active=False. Custom user models that don't have that attribute are allowed. """ is_active = getattr(user, 'is_active', None) return is_active or is_active is None it should return True instead of is_active or is_active is None but i don't want change Django source. this is my login view: def login(request): if not request.user.is_authenticated: if request.method == "POST": phone_number = request.POST["phone_number"] password = request.POST["password"] user = authenticate(request, username=phone_number, password=password) if user is not None: login_auth(request, user) return HttpResponseRedirect("/account/") else: ctx = {'msg_bad':'wrong password or phonenumber!'} else: ctx = {} else: return redirect("/account/") return render(request, "account/login.html", ctx) is there way to solve this problem by returning True user_can_authenticate in this view or if we do that, it also work in account page and others ? or should do that solution everywhere ? -
Subset Django Tables across all Models
I am trying to figure a way to subset the Database that is > 10 GB in size. I tried tweaking around with Condensor and Jailer. The former has a space issue i.e can work effectively for DB under 10GB and I really couldn't figure out Jailer. So I went on with identifying relationships in my Django tables i.e Foreign key relationships. I have identified a primary key lets say : loan_application_number and looking for the same in all other tables that have access to it directly or indirectly. I am just having a hard time figuring out how can I subset my tables based on this key. I have minimal experience with the same and If anybody could guide me in the right direction. Before that I just need to understand if I can subset lets say two models: Model A : Loan Model B : Payments If Models A and B have lets say 10000 entries and have loan_application_no as their primary key. Then is there a way to get a 10% of these tables? -
How do I create a simple formset that works?
So the code I have: models.py class Department(models.Model): code = models.CharField(max_length=250, unique=True) code_meaning = models.CharField(max_length=250, ) def __str__(self): return "%s" % (self.code) urls.py path('departments/', DepartmentCreateView.as_view(), name='department'), department.html {% extends 'base.html' %} {% block content %} {% load crispy_forms_tags %} <div class="content-section"> {{ formset.management_form }} <form method= "POST"> {% csrf_token %} {% for form in formset %} {{ form}}<br><br> {% endfor %} <button class="btn btn-outline-info" type="submit">Save</button> </form> </div> {% endblock content%} views.py class DepartmentCreateView(CreateView): model = Department form_class = DepartmentForm template_name = 'department.html' def get_context_data(self, **kwargs): context = {'formset': DepartmentFormset} return context def form_valid(self, formset): formset.save() messages.success(self.request,'Changes were saved.') return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return HttpResponseRedirect(reverse('home')) forms.py class DepartmentForm(ModelForm): class Meta: model = Department fields = ('code', 'code_meaning',) My page shows the formset, but when I click on the submit button it just reloads, don't saves anything and the succes message is also not showed on my home page. (My other createviews where I have only one form works prefect) I very new to django so I don't know where I did something wrong ? Thanks in advance -
Behind the scenes of authenticate(),login(), and is_valid()
How these three differ from each other, I have seen the authentication() and login() in registration form, But i don't really understand these usage of these two in registration(Because i don't get an complete explanation form anywhere about this). From Django Doc, I understand that the valid() will make sure that, every field is perfectly validated according to the given and default requirements. But in some program I have seen the usage of valid() and followed with the login(). (I can't understand how that work without comparison of data) My Doubts How is these differ from each other? On first registration, by logic we have to store the credentials somewhere, and in login we have to compare that data with the stored data right. Then by these, what's happening behind the hood? Can anyone make it more clear for me about these three? And the usage?.Thankyou!