Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelFormSet to answer an ordered list of questions that shouldn't change their order in the formset after submit if answered in a random order
I have to display a Django formset containing a list of predefined questions (a few dozen questions) arranged in a specific order. The user has the freedom to answer whatever questions they want, in an arbitrary order, save their answers, and continue answering later. So there are no mandatory fields. For instance the user answers the questions 2, 5, 6, and 7: Question Answer Question 1 Question 2 Answer to question 2 Question 3 Question 4 Question 5 Answer to question 5 Question 6 Answer to question 6 Question 7 Answer to question 7 Then the user submits the formset. The first issue I had was that after submitting the formset the newly added answers (and their questions) were moved to the top of the formset: Question Answer Question 2 Answer to question 2 Question 5 Answer to question 5 Question 6 Answer to question 6 Question 7 Answer to question 7 Question 5 Question 6 Question 7 The (simplified) models I used are: class Question(models.Model): position_nr = models.SmallIntegerField(db_index=True) content = models.CharField(max_length=200) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.PROTECT) content = models.CharField(max_length=100, blank=True, null=True, ) I used a ModelFormSet. In the simplified versions of my view and forms (see below) the … -
django - submit multiple forms in one post request (different from one click cause I need to process the data of those two forms together!)
I have two models jobposition and wage and models are related by a OneToMany relation. class JobPosition(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.ForeignKey(Title, on_delete=models.CASCADE) ... class Wage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) amount = models.FloatField(blank=True,null=True) type = models.CharField(choices=WAGETYPE, max_length=30) position = models.ForeignKey(JobPosition, related_name='wages', on_delete=models.CASCADE, blank=True, null=True) I am building a user interface where a user can create a position with associated wage (let's say just one wage for now). The problem I am facing is that I would like to do this using some combination of forms instead doing everything manually. I created these two forms and served them to a django template using a templateview class JobPositionForm(forms.ModelForm): class Meta: model = JobPosition fields = ['title','city','dept_head','files','department_budget'] ... class WageForm(forms.ModelForm): class Meta: model = Wage exclude = ['id'] The page is rendered smoothly, however I am now realizing that I don't know how to submit those two forms together inside a single post request. I thought about using formset but I don't know how to use it with different forms. I guess I can always do this manually using Javascript to parse each value and place it into the same POST... but I was hoping there was a work … -
I can't get the content of an object
I have to POST the contents of some objects, but I'm not able getting this content from the objects. Any help would be greatly appreciated. from django.shortcuts import render, redirect from cadastro.forms import CadastroForm import requests from . import models def cadastro_usuario(request): data = {} data['form'] = CadastroForm() return render(request, 'cadastro.html', data) def create(request): form = CadastroForm(request.POST or None) user_name = models.Cadastro_alunos.user_name user_cpf = models.Cadastro_alunos.user_cpf user_password = models.Cadastro_alunos.user_password user_genre = models.Cadastro_alunos.user_genre user_email = models.Cadastro_alunos.user_email dados_obrigatorios = {'token': 'caf9bc8bdf3fa9ed2040236252cf3d312c5d984f', 'course_id': '1', 'course_plan': '1', 'user_name': user_name, 'user_cpf': user_cpf, 'course_type': '4', 'user_email': user_email, 'user_password': user_password, 'user_genre': user_genre} print(dados_obrigatorios) try: form.save() y = requests.post('https://www.iped.com.br/api/user/set-registration', data=dados_obrigatorios) print(y.json()) except Exception as e: print(e) return redirect('https://icegetec.com.br/') -
Odd Django queryset behavior trying to filter use 'lte' filer on datetime field
I'm seeing some weird behavior with one of my models and am having a hard time tracing down what's going on. My application has a relatively simple 'posts' model that I'm trying to feed into a ListView: # models.py class Posts(models.Model): draft = 0 published = 1 status_choices = [(draft, "Draft"), (published, "Published")] id = models.AutoField(primary_key=True, unique=True) title = models.CharField(max_length=500) slug = models.SlugField(max_length=500, unique=True) text = models.TextField(null=False) html = models.TextField(blank=True, null=True) status = models.IntegerField(choices=status_choices, default=draft) create_date = models.DateTimeField(default=timezone.now, verbose_name="Post date") update_date = models.DateTimeField(default=timezone.now, verbose_name="Last edited") def __str__(self): return self.title def save(self, *args, **kwargs): savetime = datetime.now().replace(microsecond=0) if savetime != self.create_date # set the update date if needed self.update_date = savetime if not self.slug: self.slug = slugify(self.title) # make sure the post gets a slug self.html = md.convert(self.text) # convert markdown to HTML for storage return super().save(*args, **kwargs) # views.py class PostList(ListView): context_object_name = "posts" model = Posts queryset = ( Posts.objects.all() .filter(create_date__lte=datetime.now(), status__exact=1) .order_by("-create_date") ) template_name = "post.html" paginate_by = 20 paginate_orphans = 2 But when I create a new post, it won't show in the template until I restart the app. I think it might have something to do with the create_date__lte=datetime.now() filter, because when I take that out, … -
jsonfield queryset and filtering
I want to search through the contents of this JSONField: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() class Test(models.Model): name = models.CharField("layout", max_length = 32, unique = True) prod = models.ForeignKey("product", on_delete = models.CASCADE, null = True, blank = True) where the data looks like this: {"name": "monkey", "price": 22, "description": "text here", "imgb64": "bkmocdnm32iojo3d0..."} I want to search via the product_data attributes, but not the imgb64 attribute within the JSONField. I tried: qs = Test.objects.filter(product__data__in = "monkey") ## <QuerySet []> but this does not yield a hit. Is it possible to search through some of the keys of data? Or even better, exclude some keys when searching? -
Como gerar uma senha aleatória no django?
Para caso a senha não for inserida, ela teria de ter um valor aleatório para ela -
Django + nginx + gunicorn not being able to serve static files
I'm trying to deploy a django app in a EC2 instance but I'm currently having issues serving the static files of the app. Currently, my nginx's conf file looks like this: location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. #try_files $uri $uri/ =404; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://0.0.0.0:8000; } location /static/ { #autoindex on; root /home/ubuntu/some/folder/static/; } Also in my settings.py file in my django project I have the following config related to my static files: STATIC_URL = '/static/' STATIC_ROOT = '/home/ubuntu/some/folder/static/' and Gunicorn, I'm launching it as the following: gunicorn3 --bind 0.0.0.0:8000 myproject.wsgi:application And with that, if I access http://ec2-my-instance:8000 I see the html content, but all my js and css files get error 404. I'm kinda lost and I don't know what I'm missing to make it works, I already migrated the static content and I checked the folder which nginx is looking for the static files have them, but if I check the browser's console I see this kind of errors: GET http://ec2-my-instance:8000/static/somefile.js net::ERR_ABORTED 404 (Not Found) -
How to retrieve data from model that current user created and list it for another model's field in django
Let us imagine that I have two models. First model contains curse details and user that created this course class Course(models.Model): course_name = models.CharField(max_length=100, null=False) description = models.CharField(max_length=255) user_profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and my second model is: class Lesson(models.Model): course = models.OneToOneField(Course, on_delete=models.CASCADE) # # inside the course I want my APIVIEW to list only the courses that current user created. # OnetoOne relationship does not solve the problem. status = models.CharField(choices=STATUS, null=False, default=GOZLEMEDE,max_length=20) tariffs = models.FloatField(max_length=5,null=False,default=0.00) continues_off = models.CharField(max_length=2) user_profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) My serializers for both Models: class LessonSerializer(serializers.ModelSerializer): class Meta: model = models.Lesson fields = ('course', 'status', 'tariffs', 'continues_off', 'user_profile') def create(self, validated_data): lesson = models.Lesson.objects.create( course = validated_data['course'], status = validated_data['status'], tariffs=validated_data['tariffs'], continues_off=validated_data['continues_off'], user_profile=validated_data['user_profile'] ) return lesson class CourseSerializer(serializers.ModelSerializer): """Serializers Course content""" class Meta: model = models.Course fields = '__all__' def create(self,validated_data): course = models.Course.objects.create( course_name = validated_data['course_name'], description=validated_data['description'], user_profile=validated_data['user_profile'] ) return course My Viewset: class LessonViewset(viewsets.ModelViewSet): model = models.Lesson serializer_class = serializers.LessonSerializer authentication_classes = (SessionAuthentication,) permission_classes = (IsAuthenticated,BasePermission,) def get_queryset(self): user_current = self.request.user.id return models.Lesson.objects.filter(user_profile=user_current) How can I get the desired result. I want to get the courses for the current user and show them as a dropdown list in my API view. -
save leaflet marker in django form
I want to create a web app with django where user can create marker on a map. I have this js script to add marker by clicking on a leaflet map. window.onload = function () { element = document.getElementById('osm-map'); var markers_list = new Array() var map = L.map(element); let rm = false L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); // var markers = L.featureGroup([]) var target = L.latLng('48.8686034651125', '2.34261607443957'); map.setView(target, 5); map.on('click', function (e) { var node = document.createElement("LI") var marker = new L.marker(e.latlng).addTo(map); markers_list.push(marker); var marker_id = marker._leaflet_id let title_marker = window.prompt("give a name to your marker",marker_id); //todo make sure input is not empty while (!title_marker){ title_marker = window.prompt("give a non empty name",marker_id); } marker.bindPopup("marker's info: "+title_marker).openPopup() map.addLayer(marker) a = document.createElement('a') a.innerHTML=title_marker a.setAttribute('id', marker_id) a.setAttribute('href',"javascript:void(0);"); node.appendChild(a); document.getElementById("marker-list").appendChild(node) } ); rm_btn.onclick = function () { // function to enable edit of marker rm = !rm if (rm) { document.getElementById('rm_btn').innerHTML = "Edition enabled"; } else { document.getElementById('rm_btn').innerHTML = "Edition disabled"; } } var ul = document.getElementById('marker-list'); //list of li marker ul.onclick = function(e) { if (rm) { id_to_rem = e.target.id for(var i=0;i<markers_list.length;i++){// iterate over layer to remove marker from map if (markers_list[i]._leaflet_id == id_to_rem){ map.removeLayer(markers_list[i]) } } var a_list = … -
Django template with nested loop rendering HTML table horizontally (vertically needed)
As the title says I need a HTML in a Django template rendering vertically. View code: data = { "id": id, "name": name, "country": country } context = { "data": data, } HTML_STRING = render_to_string("home-view.html", context=context) Template code: <table> <thead> <tr> <th>#</th> <th>name</th> <th>country</th> </tr> </thead> <tbody> {% for key, values in data.items %} {% for v in values %} <tr> <td>{{ v }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> This code renders this table: id name country 1 2 3 Ioan Juan John Romania Spain UK What I need: id name country 1 Ioan Romania 2 Juan Spain 3 John UK What am I doing wrong? Can someone help me pls -
How to display data in carousel card - bootstrap
I use bootstrap 5.0 and I try display title of book on the card but not effective. My carousel in html {% block content %} <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner" style="background:gray; color:white; height:300px; position:relative"> <div class="carousel-item active"> <div class="container" style="position:absolute; right:0; padding-top:150px; padding-bottom:50px"> {% for book in obj %} <h1>{{book.title}}</h1> <p>Some first text to test</p> <a href="#" class="btn btn-lg btn-primary">Read more</a> {% endfor %} </div> <img src="/assets/media/book_images/BookDefault.png" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> {% endblock %} and my example method def display_book(request): obj = Book.objects.get(1) return render(request, 'templates/carousel_1.html', {'obj': obj}) Everything in the for loop is not displayed. My project structure: WebBook |-accounts |-books |--views.py with method |-templates |--carousel_1.html with my carousel I looked in many places but none of the methods worked. Could you help? -
How to return all the message between two Users - Django/Python/Chat Building
I'm building a simple chat with Django-Rest-Framework in Python. I created a GET/POST methods for Users and Chat. MODEL from django.db import models from django.db.models.base import Model class User(models.Model): class Meta: db_table = 'user' user_firstname = models.CharField(max_length=200) user_lastname = models.CharField(max_length=200) class Chat(models.Model): class Meta: db_table = 'chat' from_message = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') message = models.CharField(max_length=1000) to_message = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') SERIALIZERS from rest_framework import serializers from .models import User, Chat class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class ChatSerializer(serializers.ModelSerializer): class Meta: model = Chat fields = '__all__' URLS from django.urls.conf import re_path from . import views urlpatterns = [ re_path(r'^users/$', views.UserList.as_view(), name='users-list'), re_path(r'^chat/$', views.ChatList.as_view(), name='chat-get-list'), re_path(r'^chat/(?P<from_id>.+)&(?P<to_id>.+)/$', views.ChatList.as_view(), name='chat-list'), ] VIEWS from rest_framework import generics, serializers from .models import User, Chat from .serializers import ChatSerializer, UserSerializer class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() return queryset class ChatList(generics.ListCreateAPIView): queryset = Chat.objects.all() serializer_class = ChatSerializer def get_queryset(self): queryset = Chat.objects.all() from_id = self.request.query_params.get('from_id') to_id = self.request.query_params.get('to_id') if from_id is not None and to_id is not None: queryset = Chat.objects.filter(from_message=from_id,to_message=to_id) #Probably my error is here, because I'm specifying the messages. I need to add something like 'to_message=to_id or from_id return queryset THE PROBLEM: When I … -
django deleteview edit performance
I'm new in Django, I'm learning class based view and all works fine, what I'm trying to do is to edit the DeleteView performance, this just delete de object but what im looking is to edit the object instead of delete class borrar(DeleteView): model = Usuario template_name = "usuario_confirm_delete.html" success_url = '/alta/' I would like to edit but I do not know how to achieve this. Usuario.objects.filter(id=23).update(activo='False') Any idea ? -
Django search and display results in chart on refresh
am creating a search Web for psql database I have. Am having a few issues with django, my app draw a chart for results and print them. On refresh results change and chart disappear! -
CSRF token missing or incorrect - using auto-complete light in Django
Running into CSRF_Token missing or incorrect in my Django-app, don't really understand what the issue is as I've included the {% csrf_token %} in any possible form being rendered by my template. I suspect it may have to do with the ajax requests that are done within the form to retrieve area-names and more, maybe someone can tell me what the issue is. I'm using autocomplete-light for retrieving some data from my DB, don't know if that can play a part in this. I've tried searching around online but haven't found a solution that seems to apply to my problem. Views.py Class BreedAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return DogBreeds.objects.none() qs = DogBreeds.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class AdListTakeMyDog(generic.ListView): model = Advertisement context_object_name = 'ads' template_name = 'core/advertisement_list_take.html' def get_queryset(self): queryset = Advertisement.objects.filter(is_offering_own_dog=True) return queryset class AdListGetMeADog(generic.ListView): model = Advertisement context_object_name = 'ads' template_name = 'core/advertisement_list_get.html' def get_queryset(self): queryset = Advertisement.objects.filter(is_offering_own_dog=False) return queryset class NewAdTakeMyDog(CreateView): model = Advertisement form_class = NewAdTakeMyDogForm success_url = reverse_lazy('view_ads_take_my_dog') template_name = 'core/advertisement_form_take.html' def form_valid(self, form): form.instance.author = self.request.user form.instance.is_offering_own_dog = True return super().form_valid(form) class NewAdGetMeADog(CreateView): model = Advertisement form_class = NewAdGetMeADogForm success_url = reverse_lazy('ad_changelist') template_name = 'core/advertisement_form_get.html' def form_valid(self, form): form.instance.author = … -
what is the best architecturefor multi website (url) Django web server?
I would like to build a multi web platform which is based on Django (Python) + WSGI. The webs will have one database, exactly same backend and only the different frontend/url. What is the best Architecturefor such plateform, docker or simply congfigure different Apps? Any suggestions -
Django Countries - unable to pre-select the right country in an edit form
Consider this model: class Address(models.Model): line1 = models.CharField(max_length=255, db_index=True, blank=True, null=True) city = models.CharField(max_length=255, db_index=True, blank=True, null=True) state = models.CharField(max_length=255, db_index=True, blank=True, null=True) postcode = UppercaseCharField(max_length=64, blank=True, db_index=True, null=True) country = CountryField(db_index=True, blank=True, null=True) I'm trying to populate this model using data that comes in through webhook call. I'm having trouble populating the country in two cases: When the country is "United States" (this is what the webhook returns, I have no control over it) - django_countries does not recognize this, so I added an if condition to change "United States" to USA before creating a new Address object but, when the country is not United States, for example "Panama", I populate it directly into the model by doing this: country = request.POST.get('country') # returns something like "Panama" Address.objects.create(line1=line1, city=city, state=state, country=country) This works fine, except when I try to edit the Address form, the country field is blank, it isn't pre-selecting "Panama" from the options. I know the country field of this Address instance is a country object because I can do address_form.instance.country and it outputs Pa, if I do address_form.instance.country.name it outputs Panama. So why isn't the country field in the form pre-selecting the right Country, why does … -
Azure Hosted ASGI Django Server Bottleneck When Handling Over a Dozen Simultaneous Requests
I'm new to working with ASGI and I'm having some performance issues with my Django API server so any insight would be greatly appreciated. After running some load tests using JMeter it seems that the application is able to handle under 10 or so simultaneous requests as expected, but any more than that and the application's threads seem to lock up and the response rate vastly diminishes (can be seen in sample #14 and up on the 'Sample Time(ms)' column in the screenshot provided). It's as if requests are only being processed on 1-2 threads after that point as opposed to the configured 4. Here is my startup.sh config: gunicorn --workers 8 --threads 4 --timeout 60 --access-logfile \ '-' --error-logfile '-' --bind=0.0.0.0:8000 -k uvicorn.workers.UvicornWorker \ --chdir=/home/site/wwwroot GSE_Backend.asgi I am aware that the individual API responses are quite slow. That is something I want to address. However, is there perhaps something I am doing wrong on the ASGI level here? Thanks. -
DRF serializer data property not overridden
I have a the following serializer where I need to override the data property but for some reason it does not seem to be overridden at all. class ShopItemListSerializer(AvailabilitySerializerFieldMixin, serializers.ModelSerializer): is_aggregation_product = serializers.BooleanField() price = MoneyField(allow_null=True) discount_price = serializers.SerializerMethodField() is_favorite = serializers.SerializerMethodField() categories = ShopItemCategorySerializer(many=True) price_effect = ProductPriceEffectSerializer(source="aggregation_product.price_effect") special_information = serializers.CharField() @property def data(self): logging.error("I should be overridden") ret = super().data return_dict = ReturnDict(ret, serializer=self) if self.context.get("include_unavailable", False) is True: """ remove products that are not available """ for product in return_dict.copy(): if product["availability"] and product["availability"]["is_available"] is True: return_dict.remove(product) return return_dict I am using viewsets like the following: class ProductViewSet(StorePickupTimeSerializerContextMixin, ReadOnlyModelViewSet): queryset = ShopItem.app_visibles.prefetch_related("pictures").distinct() permission_classes = [IsCustomer] filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilterWithNoneSupport) filterset_class = ShopItemFilter search_fields = ["name", "number", "categories__name"] def get_serializer_class(self): if self.action == "list": return ShopItemListSerializer return ShopItemProductDetailSerializer I would appreciate any insights explaining the reason behind this behavior. -
Return value if not exist
Within my template, I have a number of values being presented from data within the database. {{ fundamentals.project_category }} But when no data exists it throws an error matching query does not exist. i think because the no data is being returned in the query set within the fundamentals model. fundamentals = project.fundamentals_set.get() within my view im trying: if project.fundamentals_set.get().exists(): fundamentals = project.fundamentals_set.get() else: #what should i put here? Im assuming an if statment is requried along with exists(): but this isn't working and im not sure what i should put in the else statement to return something like nothing exists when no data exists within the fields? -
(553, b'Relaying disallowed as webmaster@localhost')
I'm trying to send a password reset email on Django web app using the Zoho SMTP but it keeps throwing this error when I use Gmail. Below are some snippets Views.py def post(self, request): name = request.POST['Name'] email = request.POST['Email'] phone = request.POST['Phone'] message = request.POST['Message'] email_msg = EmailMessage( subject='New Enquiry', body=message + phone, from_email='noreply@domain.com', to=['support@domain.com'], ) email_msg.send() settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.zoho.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' -
Specific problem while migrating Django models
Attempt to migrate just default models in Django app with python manage.py migrate returns following annoying error: Traceback (most recent call last): File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/home/stepski/anaconda3/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/checks/model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/models/base.py", line 1307, in … -
hot reload of Django development in Docker is delayed
The hot reload is delayed by 1 cycle. So for example, if I have print("Hi"), nothing changes, but then if I have print("Hello"), then print("Hi") appears on the screen. If I have a third command print("Goodbye"), then print("Hello") appears. So it is always delayed by a cycle. How can I fix the code below so it is not delayed by 1 cycle but the update happens instantly. Here is my dockerfile. ########### # BUILDER # ########### # pull official base image FROM python:3.9.9-slim-bullseye as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.9.9-slim-bullseye # installing netcat (nc) since we are using that to listen to postgres server in entrypoint.sh RUN apt-get update && apt-get install -y --no-install-recommends netcat && \ apt-get install ffmpeg libsm6 libxext6 -y &&\ apt-get autoremove -y && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* # install dependencies COPY --from=builder /usr/src/app/wheels /wheels COPY --from=builder /usr/src/app/requirements.txt . RUN pip install --no-cache /wheels/* # set work directory WORKDIR /usr/src/app # copy our django … -
different between title and title_icontains in model filter django
what is diffrent between title and title_icontains in django ? from .model import product product.objects.filter(title='blah') product.objects.filter(tite__icontains='blah') -
ArrayField in djongo models, i get json response like these
[ { "id": 10, "table_name": "cars", "columns": "[{"column_key": "paul", "display_key": "paul@mail.com", "column_type": "text", "char_limit": "0"}, {"column_key": "tus", "display_key": "tus@mail.com", "column_type": "text", "char_limit": "1"}]" }, { "id": 26, "table_name": "comics", "columns": "[{"column_key": "ben-10", "display_key": "ben@mail.com", "column_type": "text", "char_limit": "5"}]" } ]