Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set session key in djago channels
I have a chat app and i want to use session key to save chats in models for persistence,how can i do this import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() ........ -
Need to apply a clear function or rest for the following code to rest the input field
I need to apply a clear function when I add the input frequency. Now when I add a number say 2, 2 fields are created and when I add 3, it's getting appended and showing 5 fields. I need the exact number of fields as given in the input. Please give any tips <div class="container"> <div class="row"> <div class="col-4"></div> <div class="col-4"> <form method="post" enctype="multipart/form-data" autocomplete="off"> {%csrf_token%} <div class="mb-3"> <label>{{medicineform.frequency.label}}</label> </div> <div class="mb-3"> {{medicineform.frequency}} </div> <br> <div id="dynamicCheck"> <input type="button" value="+" onclick="createNewElement();"/> </div> <br> <div id="newElementId">Your time here</div> <br> <div class="mb-3"> <button type="submit" class="btn btn-block btn-primary">Add a reminder</button> </div> </form> </div> <div class="col-4"></div> </div> </div> </div> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#medicine").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> <script type="text/JavaScript"> function createNewElement() { var inpObj = document.getElementById("id_frequency").value; // First create a DIV element. var i; for (i=1;i<=inpObj;i++) { var txtNewInputBox = document.createElement('div'); // Then add the content (a new input box) of the element txtNewInputBox.innerHTML = "<input type='time' name='reminder' id='newInputBox'>"; // Finally put it where it is supposed to appear. document.getElementById("newElementId").appendChild(txtNewInputBox); } } </script> {% endblock %} -
How speed up sending email in Django rest framework?
I have a backend server that allows users to track the price of products on an ecommerce site. Whenever the price drops down, I'll have to send an informing email to my users. I have been written an API that updates the price of products and at the same time, sending an email if the price has dropped. So, the are thousands of emails have to be sent in one API call. Currently, I'm using django.core.email to sending email to users but it takes so long each time sending an email (about 3s-4s for each. If it has 5 product's prices dropped, the time of the API call will be around 20s). Is there any way to make a lot of emails sent within the shortest amount of time in my case? -
Image url not displaying my uploaded images when django project loaded onto heroku site
My uploaded images are not loading when uploaded to heroku and I think its not related to static file issue. When i set debug = False they come fine and i know that when it is false django uses itself to host the static assests. So setting that and my images loads fine but that's not the case if i set Debug = True on heroku or on my local env. Can somebody help me solve this issue. template <img class="img-fluid" style="height:auto;" src="{{post.work_img.url}}" alt="Generic placeholder image"> model class WorkExp(models.Model): work_img = models.ImageField(upload_to="work_images/") app/urls.py urlpatterns = [ path("carrer/", WorkExpView, name="carrer_page"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) project/urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("blog.urls", namespace="blog")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django Excel Custom Column and Rows format
I want to customized Columns and Rows in Excel output like the image below. It is possible to make the same output in django using openpyxl workbook? This is my regular export excel code: def summary_excel(request): car_queryset = Reg_Date.objects.all() response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename=Reg.xlsx' workbook = Workbook() worksheet = workbook.active worksheet.title = 'Reg' columns = [ 'SUBJECT:', 'PERSONEL:', 'LOGOUT:' ............. ] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title for car in car_queryset: row_num += 1 row = [ car.subject, car.personel, car.time .................... ] for col_num, cell_value in enumerate(row, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = cell_value workbook.save(response) return response -
To Fetch Data from scanned barcode number
I am new to Django,I am currently working on application that need barcode reading and fetch data from server.I am now able to get barcode from a scanned barcode. My question is: how can I get more information about a product from its barcode number in django (e.g. product price)? Can I do this from the barcode_scan library, or will I need something else? -
Django functional index migration (postgres), error: invalid input syntax for type integer: "none"
I'm trying to create a functional index based on a newly created field in Django 3.2 (see the prerelease notes for more info about functional indexing), but keep getting the following error when migrations are run (using postgres): psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type integer: "none" This seems like it may be a bug in the Django prerelease, but I'm not sure. I'm not just dumping all my code in this post; the larger block of code below is actually an auto-generated migration by django. The first code block is my code, where I just include the relevant fields and the problematic functional index. This code creates a new field "registration_volume" and a functional index "raw_demand" which should equal registration_volume/capacity if [capacity is not null and capacity>0], capacity being another field of the model), in a model called "Section": capacity = models.IntegerField( default=0, help_text="The number of allowed registrations for this section, " "e.g. 220 for CIS-120-001 (2020A).", ) registration_volume = models.PositiveIntegerField( default=0, help_text="The number of active PCA registrations watching this section." ) class Meta: indexes = [ Index( Case( When( Q(capacity__isnull=False) & Q(capacity__gt=0), then=( Cast("registration_volume", models.DecimalField()) / Cast("capacity", models.DecimalField()) ), ), default=None, output_field=models.DecimalField(null=True, blank=True), ), name="raw_demand", ), ] The auto-generated … -
Get django-filters working on 2 level foreign key relations
I have 3 models a-->b-->c. I want to add django-filter on c so that it could filter using the attributes/values of a. I have tried using ModelChoiceFilter, but only got it working till model b. Is there any way we could filter through 2 levels of foreign key relations? -
2 Options for permission_required in Django View
I have to render a page that requires either of the 2 permissions. views.py class Dashboard(TemplateView, PermissionRequiredMixin): permission_required = "m.view_dashboard" // I want to add another option like "m.add_item" template_name = "dashboard.html" so permission is either of the two options, view and add. Is there any way I can implement this through permission_required? -
Django: AUTH_USER_MODEL refers to model '%s' that has not been installed
I am trying to deploy a Django app to Heroku. It works on my localhost but I get this error when deploying to heroku: File "./blog/models.py", line 6, in <module> 2021-03-24T23:31:05.696194+00:00 app[web.1]: User = get_user_model() 2021-03-24T23:31:05.696219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 162, in get_user_model 2021-03-24T23:31:05.696372+00:00 app[web.1]: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL 2021-03-24T23:31:05.696397+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed I have tried setting AUTH_USER_MODEL = 'auth.User' in settings after doing from django.contrib.auth.models import User and: from django.contrib.auth import get_user_model User = get_user_model() but nothing works. settings.py import django from django.core.wsgi import get_wsgi_application from django.core.asgi import get_asgi_application # from django.contrib.auth.models import User #todo: this causes ImproperlyConfigured: SECRET_KEY MUST NOT BE EMPTY import os import django_heroku DJANGO_SETTINGS_MODULE = 'django_project.settings' SECRET_KEY = 'asdaf123$9pv98=e6p^gl(-eoj' #todo: test removing this in own deployment DEBUG = 'True' ALLOWED_HOSTS = ['*', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.auth', 'blog.apps.BlogConfig', #allows Django to correctly search your templates for the 'blog' app 'users.apps.UsersConfig', 'chat', 'crispy_forms', 'channels', 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages' ] # ~~~MESSAGES CONFIG~~~ WSGI_APPLICATION = 'django_project.wsgi.application' ASGI_APPLICATION = 'django_project.asgi.application' # older version of django: 'django_project.routing.application' # Channels redis config: CHANNEL_LAYERS = { 'default': { 'BACKEND': … -
Getting an error while using HyperlinkedModelSerializer in DRF
When i run the URL http://127.0.0.1:8000/api/leave/, I get this frustrating error: Could not resolve URL for hyperlinked relationship using view name "leaveapplication-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I found some solutions over the internet but none of them worked for me. What is the best way to solve this error? Currently i got this if i use ModelSerializer but i want to generate URL instead of id { "id": 7, "date_start": "2021-03-20", "date_end": null, "time_start": "09:00:00", "time_end": "13:00:00", "remarks": "something", "status": null, "type": 1, "leave_type": "Test" }, I have a models directory rather than models.py file. Here is the directory: models/ ......__init __.py ...... leaveApplication.py Here is my model: from leave.models.leavetype import LeaveType from django.db import models from authentication.models import TimeStampedModel, User class LeaveApplication(TimeStampedModel): date_start = models.DateField(default=None) date_end = models.DateField(default=None, null=True) time_start = models.TimeField(auto_now=False, auto_now_add=False, null=True) time_end = models.TimeField(auto_now=False, auto_now_add=False, null=True) remarks = models.TextField(default=None, null=True) status = models.CharField(max_length=255, null=True) type = models.ForeignKey(LeaveType, related_name='leave_applications',default = None, on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='leave_applications',default = None, on_delete=models.CASCADE) Here is my Serializer: class LeaveApplicationSerializer(serializers.HyperlinkedModelSerializer): date_start = serializers.DateField(required=True) date_end = serializers.DateField(default=None, required=False, allow_null = True) time_start = serializers.TimeField( required=False, allow_null … -
Is it safe to render python dictionary data in html template in django or shall I use json?
When I learned about JSON data I am confused. I am rendering data in html template. data = {'user': username, 'data': data} return render(request, 'index.html', data) Is this way safe to use or I need to send response as JSON? Can you also explain how can I use JSON data in html template? How can I use jhinja format like python with JSON {{json data here}}? -
TypeError at /api/updateproducts/59 unhashable type: 'collections.OrderedDict' in Django Rest Framework
I created update-product API where I have to update many to many fields. Product models have m2m relationships with the Category and Variants model. I am able to update Category model fields using instance.category.set(), but when I try the same thing with Variants, it generates the above error. I am sending the raw JSON data like this. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" class Variants(models.Model): product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) variants = models.ManyToManyField(Variants,related_name='products') My views: class ProductUpdateView(UpdateAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductUpdateSerializer My serializers: class ProductUpdateSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True) class Meta: model = Product fields = ['id','category','featured', 'top_rated','brand','collection', 'name','description', 'main_product_image','best_seller', 'rating','availability','warranty','services','variants'] def update(self, instance, validated_data): instance.featured = validated_data.get('featured',instance.featured) instance.top_rated = validated_data.get('top_rated', instance.top_rated) instance.brand = validated_data.get('brand', instance.brand) instance.collection = validated_data.get('collection',instance.collection) instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() #category_logic category_data = validated_data.pop('category') instance.category.set(category_data) instance.save() #variants_logic variants_data … -
How to use array fields in Django models?
I have a model class Client and it has different fields. As shown below: class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField(null = True) installment_date = models.SlugField(max_length = 100) I have different templates and views for first 6 fields (as these will be asked when adding a new client to the database),and the last 3 fields(installment_month, installment_amount, installment_date) because these fields will be used everytime when client pays an installment. Now, when I try to add a new installment it asks me for these 3 fields but it replaces the values entered last time, because each of these 3 fields can only store 1 value. Does anyone has an idea how can I declare array fields for these so that they can store all the installments, their months and their date? -
django url not matching right url with reverse match error
I'm getting very unusual error in my django project because django reads the wrong url not stated in the href tag being clicked,the page to be navigated to is just a page with a simple url pattern while the page it's navigating to requires two arguments for reverse matching,since the page to be navigated to is just a simple url and doesn't provide the necessary parameters in the views and url path,it gives a no reverse match error saying it tried to match the reverse url pattern which in actuality is in another page. this what i'm trying to say: error: Reverse for 'search-friend-detail' with arguments '('', '')' not found. 1 pattern(s) tried: ['chat/search\-friend\-detail/(?P[^/]+)/(?P[^/]+)/$'] urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('users.urls')), path('posts/home.html', p_views.PostsListView.as_view(), name='posts-home'), path('friends/search.html', f_views.search, name='friends-search'), path('friends/add-friend/', f_views.SearchDetail, name='friends-search-detail'), path('friends/accept-requests/', f_views.AcceptRequests, name='accept-requests'), path('friends/accept-requests-detail/', f_views.AcceptRequestsDetail, name='accept-requests-detail'), path('chat/chatt.html', pc_views.SearchChat, name='chat-search'), path('chat/search-friend-detail/<str:username>/<str:usernamee>/', pc_views.SearchChatDetail, name='search-friend-detail'), ] the "chat-search" is the actual url i wish to navigate to in base.html file through this link: <a href="{% url 'chat-search' %}"><i class="fa fa-envelope"></i></a> but instead miraculously navigating to the last url i.e 'search-friend-search'. although the link is in my chatt.html file at: <a class="mr-2" href="{% url 'search-friend-detail' results.Accepter.username results.Added.username %}">{{ results.Added.username }}</a> my views.py: def … -
Issue deploying Django/websocket/redis project to heroku
I have a Django project, which is running fine on my machine, that uses redis and a couple of workers to utilize websockets and give constantly updated subway times. It works fine on my machine, but I'm logging errors like such on Heroku when I have it deployed: 2021-03-25T04:23:19.462596+00:00 app[worker2.1]: [2021-03-25 04:23:19,462: ERROR/MainProcess] beat: Connection error: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 32.0 seconds... 2021-03-25T04:23:51.493083+00:00 app[worker2.1]: [2021-03-25 04:23:51,492: ERROR/MainProcess] beat: Connection error: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 32.0 seconds... 2021-03-25T04:22:11.000000+00:00 app[heroku-redis]: source=REDIS addon=redis-concentric-76659 sample#active-connections=1 sample#load-avg-1m=0.23 sample#load-avg-5m=0.51 sample#load-avg-15m=0.42 sample#read-iops=0 sample#write-iops=0.061111 sample#memory-total=15629040kB sample#memory-free=7601200kB sample#memory-cached=3699616kB sample#memory-redis=326704bytes sample#hit-rate=1 sample#evicted-keys=0 2021-03-25T04:24:23.524980+00:00 app[worker2.1]: [2021-03-25 04:24:23,524: ERROR/MainProcess] beat: Connection error: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 32.0 seconds... I've installed and started redis via heroku run bash and the ports are correct. What could be the problem? If there is any info that would be helpful I am happy to update. -
how to ingtegrate of kafka with django with consumer ,producer, queue push ,pull from queue
''' def kfk(request): print("ala re ala") producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092') producer.send('Ptopic', kafka_msg) return HttpResponse(200) ''' -
Django range filter with condition
I have a model and manager as follows, here I want to filter published posts in a date range if dates are given, otherwise I want to show only published posts. class Video(ModelMeta, models.Model): category = models.ForeignKey(VideoCategory, on_delete=models.CASCADE, related_name='videos', blank=True, null=True) video_title = models.CharField(verbose_name='Title', max_length=120, blank=True, null=True) description = models.TextField(blank=True, null=True) title = EmbedVideoField( verbose_name='Either Choose video from youtube/vimeo or', blank=True, null=True) publish = models.CharField(verbose_name='Visibility', max_length=80, choices=PUBLISH_CHOICES, default='publish') is_active = models.BooleanField(default=True) publish_start = models.DateTimeField(blank=True, null=True) publish_end = models.DateTimeField(blank=True, null=True) objects = VideoManager() class VideoManager(models.Manager): def active(self): return self.get_queryset().filter(is_active=True) def active_range(self): return self.get_queryset()\ .filter(publish_end__gte=timezone.now(), publish_start__lte=timezone.now()) \ .filter(publish='publish') def published(self): return self.active().filter(publish='publish') How I can do it, and combine the distinct values -
Django REST Multiple Nested Serializer Filter
Is there a way to filter multiple nested serializers? I have a Student serializer that displays all of the students courses. The courses display all the homework and their scores. They way I want to design the backend is that every student will receive the same homework outline but only the scores change; so to reduce duplicate data I create the scores table that points to the homework and the student. However, when I do a GET request it gets all of the students scores for that homework instance. Is there a way to filter it to only get a particular students score? I simplified my models for this example but the problem is essentially the same. In my Response, you can see "score":1 and "score":2, these belong to two different students but I want to get the specific score that relates to the a particular Student. Models class Student(models.Model): firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) def __str__(self): return self.firstName class Course(models.Model): courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') def __str__(self): return self.courseName + " " + str(self.courseYear) class Homework(models.Model): hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey( Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) … -
Django "abstract" foreign key
With Django, supposed that I am interested in the following models schema. from django.db import models class FirstModel(models.Model): x_name = models.CharField(max_length=64) x_number = models.IntegerField() y_name = models.CharField(max_length=64) y_number = models.IntegerField() def do_something_with_x(self): return f'{self.x_name} {self.x_number}' def do_something_with_y(self): return f'{self.y_name} {self.y_number}' class SecondModel(models.Model): z_name = models.CharField(max_length=64) z_number = models.IntegerField() def do_something_with_z(self): return f'{self.z_name} {self.z_number}' I could refactor the previous code as follows: class CommonModel(models.Model): name = models.CharField(max_length=64) number = models.IntegerField() def do_something(self): return f'{self.name} {self.number}' class FirstModel(models.Model): x = models.ForeignKey(CommonModel) y = models.ForeignKey(CommonModel) class SecondModel(models.Model): z = models.ForeignKey(CommonModel) However, this would create a new database table for CommonModel. Is there a way to have this refactoring only at Python level, while leaving the database schema as in the first snippet? -
How to centralize Django base.html from remote location
I need to set up a project which is across multiple departments. The VP wants to centralize all the CSS. JS and base.html. Those files need to control by QA and no one should have access to them. Does Django have some function like PHP tag, I can force Base.html include header, navi bar, side bar and footer. please help, thanks -
Django rest_framework oAuth2 APIView error
I am making a Django application API, where an authorized user can post a messages, and other users can browse the message and like/dislike/comment on the messages (twitter style). I have implemented oAuth2 already and tested it. The API works fine from the admin panel, but when I access it through url, it is giving error: enter image description here My models.py class is: class Posts(models.Model): def expirationTimeCalculation(self): EXPIRATION_DURATION = 86400 #time in seconds expirationTime = self.creationTimestamp + timedelta(seconds = EXPIRATION_DURATION) return expirationTime def postLiveStatus(self): return (self.expirationTimestamp > timezone.now) def postLiveTimeRemaining(self): if (self.expirationTimestamp > timezone.now): return (self.expirationTimestamp - timezone.now).total_seconds() else: return 0 postIdentifier = models.IntegerField() title = models.CharField(max_length=100) message = models.TextField() topic = models.ManyToManyField('Topics') creationTimestamp = models.DateTimeField(default=timezone.now) expirationTimestamp = property(expirationTimeCalculation) post_owner = models.ForeignKey(AppUser, related_name='post_owner', on_delete=models.CASCADE) isLive = property(postLiveStatus) post_likes = models.ForeignKey('Likes', related_name="post_likes", on_delete=models.CASCADE) post_dislikes = models.ForeignKey('Dislikes', related_name="post_dislikes", on_delete=models.CASCADE) post_comments = models.ForeignKey('Comments', related_name="post_comments", on_delete=models.CASCADE) def __str__(self): return self.title class Topics(models.Model): TOPICS = [('P','Politics'),('H','Health'),('S','Sports'),('T','Tech')] topicName = models.CharField(max_length=2, choices=TOPICS, blank=False) class Likes(models.Model): isLiked = models.BooleanField(null=True) likes_owner = models.ForeignKey(AppUser, related_name='likes_owner', on_delete=models.CASCADE) post = models.ForeignKey(Posts, related_name='likes', on_delete = models.CASCADE) class Dislikes(models.Model): isDisliked = models.BooleanField(null=True) dislikes_owner = models.ForeignKey(AppUser, related_name='dislikes_owner', on_delete=models.CASCADE) post = models.ForeignKey(Posts, related_name='dislikes', on_delete = models.CASCADE) class Comments(models.Model): comment = models.TextField(null=True) comments_owner = models.ForeignKey(AppUser, related_name='comments_owner', … -
django can not close message.info when click crossing button
Not sure what happened. I am using Django messages with bootstrap and once it pops up, it cant seem to close when I click the "x" button. Here are the code for views.py: def post_list(request, slug): if request.user.is_anonymous: msg='Thanks for checking out messages.info(request, msg) return render(request, 'Reddit_app/post_list.html', {'posts': posts, 'subreddits':subreddits, 'station': station, "user_score": user_score}) here is the settings in the file settings.py from django.contrib.messages import constants as messages INSTALLED_APPS = [ 'django.contrib.messages', ] MIDDLEWARE = [ 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+"/templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] MESSAGE_TAGS = { messages.DEBUG: 'alert-secondary', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } here is the template part {% for message in messages %} <div class="container-fluid p-0"> <div class="alert {{ message.tags }} alert-dismissible" role="alert" > <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {{ message }} </div> </div> {% endfor %} -
When Exactly does Django Run the Query?
While I understand the high-level ideas of Django's QuerySet and lazy execution, I don't see in Django (3.1.2) source code how query execution is triggered (i.e., database is being hit). For example, according to Django documentation, get() query seems to hit the database immediately. But looking at the source code (django.db.models.query): def get(self, *args, **kwargs): """ Perform the query and return a single object matching the given keyword arguments. """ clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) if self.query.can_filter() and not self.query.distinct_fields: clone = clone.order_by() limit = None if not clone.query.select_for_update or connections[clone.db].features.supports_select_for_update_with_limit: limit = MAX_GET_RESULTS clone.query.set_limits(high=limit) num = len(clone) if num == 1: return clone._result_cache[0] if not num: raise self.model.DoesNotExist( "%s matching query does not exist." % self.model._meta.object_name ) raise self.model.MultipleObjectsReturned( 'get() returned more than one %s -- it returned %s!' % ( self.model._meta.object_name, num if not limit or num < limit else 'more than %s' % (limit - 1), ) ) I don't see where clone (which is a QuerySet object) sends to the database engine its query (i.e., self._query that contains the actual Query object being parsed into SQL) and somehow caches the result in the _result_cache. In fact, when I tried to step through the … -
How to dealing rest api with huge data using mySQL, Django, vueJS
Circumstance: VueJS request to Django for get all Data where in mySQL. Load mySQL-data (The files-ize is approximately 8GB as CSV) with Django will do. Django make response with this data and send it back to vueJS. The problem is 3. Eventually the Front-End(vueJS) has to not only achieves all the data without loss but also show it to user. Is there some way to make it faster? In my opinion, API Chaining way is a bit useful like bellow. Request) let amout_rows = 20 axios.get("url/" + amout_rows) .then((res) => { if (res.data.status === 200) { axios.get("url/" + amout_rows+20) { .then((res) => {.. continues}.catch(()=>{}) } } }).catch((err) => { console.log(err) }) Django collect data from mySQL response(data=data, status=200) In this opinion occurs API(transaction) frequently so I think it is very bad for solve the issue that give all the data to Front-End. I don't know any other idea and logics. It will be very helpful if there is other way thanks.